1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use std::cell::RefCell;
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use deno_core::error::ModuleLoaderError;
use deno_core::ModuleLoadResponse;
use deno_core::ModuleLoader;
use deno_core::ModuleSource;
use deno_core::ModuleSourceCode;
use deno_core::ModuleSpecifier;
use deno_core::RequestedModuleType;
use crate::import_map::ImportMap;
use crate::ops::TelemacoState;
/// Observable network activity for ES-module graphs.
///
/// deno_core keeps dynamic-import state inside its private module map. The
/// browser lifecycle still needs to distinguish a genuinely idle page from a
/// graph whose fetch future is being advanced in short event-loop slices. A
/// loader-owned counter provides that signal without treating unrelated
/// fetch/XHR analytics as render-blocking work.
#[derive(Debug, Default)]
pub(crate) struct ModuleLoadActivity {
pending: std::sync::atomic::AtomicUsize,
last_activity: std::sync::Mutex<Option<std::time::Instant>>,
}
impl ModuleLoadActivity {
fn begin(self: &Arc<Self>) -> ModuleLoadGuard {
self.pending
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
*self
.last_activity
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(std::time::Instant::now());
ModuleLoadGuard(self.clone())
}
pub(crate) fn is_pending_or_recent(&self, grace: std::time::Duration) -> bool {
if self.pending.load(std::sync::atomic::Ordering::Relaxed) != 0 {
return true;
}
self.last_activity
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.is_some_and(|last| last.elapsed() <= grace)
}
}
struct ModuleLoadGuard(Arc<ModuleLoadActivity>);
impl Drop for ModuleLoadGuard {
fn drop(&mut self) {
let previous = self
.0
.pending
.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
debug_assert!(previous > 0, "module load activity counter underflow");
*self
.0
.last_activity
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(std::time::Instant::now());
}
}
pub struct TelemacoModuleLoader {
pub base_url: String,
/// Proxy URL threaded through to every dynamic ES-module fetch (#139).
/// `None` keeps the pre-#139 direct-connection behaviour for callers
/// that haven't been updated.
pub proxy_url: Option<String>,
/// The owning page's network context. Production runtimes always install
/// this so every module in a graph uses the same cookie jar, configured
/// identity, redirect/security policy, interception, and callbacks as the
/// entry module. Directly-constructed standalone loaders remain supported.
page_state: Option<Weak<RefCell<TelemacoState>>>,
/// Directly-constructed loaders still use Telemaco's network policy and
/// connection pool; they simply have an isolated cookie jar.
standalone_client: Option<Arc<telemaco_net::TelemacoHttpClient>>,
import_map: Rc<RefCell<ImportMap>>,
activity: Arc<ModuleLoadActivity>,
/// Canonical and requested specifiers fetched into deno_core's module map.
/// The runtime uses a cursor into this append-only list to associate a
/// prepared root with the dependencies that its successful evaluation also
/// evaluates.
loaded_specifiers: Rc<RefCell<Vec<String>>>,
}
impl TelemacoModuleLoader {
pub fn new(base_url: &str) -> Self {
Self::with_proxy(base_url, None)
}
pub fn with_proxy(base_url: &str, proxy_url: Option<String>) -> Self {
let import_map = Rc::new(RefCell::new(ImportMap::default()));
Self::with_proxy_and_import_map(base_url, proxy_url, import_map)
}
fn with_proxy_and_import_map(
base_url: &str,
proxy_url: Option<String>,
import_map: Rc<RefCell<ImportMap>>,
) -> Self {
let standalone_client = Arc::new(telemaco_net::TelemacoHttpClient::with_options(
Arc::new(telemaco_net::CookieJar::new()),
proxy_url.as_deref(),
));
TelemacoModuleLoader {
base_url: base_url.to_string(),
proxy_url,
page_state: None,
standalone_client: Some(standalone_client),
import_map,
activity: Arc::new(ModuleLoadActivity::default()),
loaded_specifiers: Rc::new(RefCell::new(Vec::new())),
}
}
pub(crate) fn with_page_state(
base_url: &str,
proxy_url: Option<String>,
page_state: &Rc<RefCell<TelemacoState>>,
import_map: Rc<RefCell<ImportMap>>,
) -> Self {
TelemacoModuleLoader {
base_url: base_url.to_string(),
proxy_url,
page_state: Some(Rc::downgrade(page_state)),
standalone_client: None,
import_map,
activity: Arc::new(ModuleLoadActivity::default()),
loaded_specifiers: Rc::new(RefCell::new(Vec::new())),
}
}
pub(crate) fn activity(&self) -> Arc<ModuleLoadActivity> {
self.activity.clone()
}
pub(crate) fn loaded_specifiers(&self) -> Rc<RefCell<Vec<String>>> {
self.loaded_specifiers.clone()
}
}
fn io_err(msg: String) -> ModuleLoaderError {
std::io::Error::new(std::io::ErrorKind::Other, msg).into()
}
impl ModuleLoader for TelemacoModuleLoader {
fn resolve(
&self,
specifier: &str,
referrer: &str,
_kind: deno_core::ResolutionKind,
) -> Result<ModuleSpecifier, ModuleLoaderError> {
// deno_core represents the root passed to load_side_es_module with a
// synthetic "." referrer. A browser resolves <script type=module src>
// as a resource URL before it starts a graph; the document import map
// must not remap that root URL.
if referrer == "." {
return deno_core::resolve_import(specifier, &self.base_url)
.map_err(|error| error.into());
}
let base = if referrer.is_empty()
|| referrer.starts_with('<')
|| referrer == "about:blank"
{
&self.base_url
} else {
referrer
};
let base = ModuleSpecifier::parse(base)
.map_err(|e| io_err(format!("Invalid module referrer {}: {}", base, e)))?;
self.import_map
.try_borrow_mut()
.map_err(|_| io_err("Import map is already borrowed".to_string()))?
.resolve(specifier, &base)
.map_err(io_err)
}
fn load(
&self,
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<&ModuleSpecifier>,
is_dyn_import: bool,
_requested_module_type: RequestedModuleType,
) -> ModuleLoadResponse {
let url = module_specifier.to_string();
// Module-graph CORS and same-origin credentials are relative to the
// owning document, not to the importing module. The importer remains
// the HTTP referrer for a dependency; keeping these URLs distinct
// prevents a cross-origin parent module from gaining CDN cookies when
// it imports a sibling on that CDN.
let document_url = ModuleSpecifier::parse(&self.base_url)
.unwrap_or_else(|_| module_specifier.clone());
let referrer = maybe_referrer
.cloned()
.unwrap_or_else(|| document_url.clone());
// Capture the loader's proxy here so the async closure below owns a
// plain Option<String> rather than borrowing &self across an `await`.
let proxy_url = self.proxy_url.clone();
let activity = self.activity.clone();
let loaded_specifiers = self.loaded_specifiers.clone();
loaded_specifiers.borrow_mut().push(url.clone());
// Register before returning the future. The lifecycle can inspect the
// runtime between deno_core accepting the load and first polling it.
// Keeping the guard inside the future makes cancellation/navigation
// decrement the count through Drop as well as success and failure.
let activity_guard = is_dyn_import.then(|| activity.begin());
let page_network = match self.page_state.as_ref() {
Some(weak) => (|| {
let state = weak
.upgrade()
.ok_or_else(|| "Module loader page state was dropped".to_string())?;
let state = state
.try_borrow()
.map_err(|_| "Module loader page state is already borrowed".to_string())?;
let client = state
.http_client
.clone()
.ok_or_else(|| "No http_client wired to module loader".to_string())?;
// Fork: in stealth mode an ES module must be fetched over the
// same transport as the document. Upstream sends it through the
// plain reqwest client, so a `type="module"` script arrives with
// a different TLS fingerprint and none of the browser identity
// headers, while the HTML that referenced it came over wreq.
// That cross-transport mismatch is trivially detectable.
#[cfg(feature = "stealth")]
let stealth = state.stealth_client.clone();
#[cfg(not(feature = "stealth"))]
let stealth: Option<std::sync::Arc<()>> = None;
Ok((client, stealth, state.callbacks.clone()))
})(),
None => self
.standalone_client
.clone()
.map(|client| {
#[cfg(feature = "stealth")]
let stealth = None;
#[cfg(not(feature = "stealth"))]
let stealth: Option<std::sync::Arc<()>> = None;
(client, stealth, None)
})
.ok_or_else(|| "No network context wired to module loader".to_string()),
};
ModuleLoadResponse::Async(Pin::from(Box::new(async move {
// deno_core propagates `is_dyn_import` to every dependency edge in
// the recursive graph, so this excludes parser-discovered/static
// graphs without losing descendant fetches of a lazy graph.
let _activity_guard = activity_guard;
tracing::debug!(
"Loading ES module: {} (proxy: {})",
url,
proxy_url.as_deref().unwrap_or("direct")
);
match page_network {
Ok((client, stealth, callbacks)) => {
let requested = ModuleSpecifier::parse(&url)
.map_err(|e| io_err(format!("Invalid module URL {}: {}", url, e)))?;
let request =
telemaco_net::ResourceRequest::module_script(&document_url, &referrer);
#[cfg(feature = "stealth")]
let resp = match stealth {
Some(stealth) => stealth
.fetch_resource_with_callbacks(
&requested,
request,
callbacks.as_deref(),
)
.await,
None => {
client
.fetch_resource_with_callbacks(
&requested,
request,
callbacks.as_deref(),
)
.await
}
}
.map_err(|e| io_err(format!("Failed to fetch module {}: {}", url, e)))?;
#[cfg(not(feature = "stealth"))]
let resp = {
let _ = &stealth;
client
.fetch_resource_with_callbacks(
&requested,
request,
callbacks.as_deref(),
)
.await
.map_err(|e| io_err(format!("Failed to fetch module {}: {}", url, e)))?
};
if !(200..=299).contains(&resp.status) {
return Err(io_err(format!(
"Module {} returned HTTP {}",
url, resp.status
)));
}
let found = ModuleSpecifier::parse(resp.url.as_str()).map_err(|e| {
io_err(format!("Invalid final module URL {}: {}", resp.url, e))
})?;
if found.as_str() != requested.as_str() {
loaded_specifiers
.borrow_mut()
.push(found.to_string());
}
let code = telemaco_net::decode_non_html(&resp.body, resp.content_type());
Ok(ModuleSource::new_with_redirect(
deno_core::ModuleType::JavaScript,
ModuleSourceCode::String(code.into()),
&requested,
&found,
None,
))
}
Err(error) => Err(io_err(error)),
}
})))
}
}