piu_core 0.412.1

A modern JavaScript/TypeScript runtime built with V8, Rust, and Tokio
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
// Copyright 2018-2026 the Deno authors. MIT license.

use deno_core::error::CoreError;
use deno_error::JsErrorBox;

use super::CodeCacheInfo;
use super::ModuleMap;
use super::is_internal_scheme;
use crate::ModuleLoadResponse;
use crate::ModuleSource;
use crate::ModuleSpecifier;
use crate::error::CoreErrorKind;
use crate::error::JsError;
use crate::error::exception_to_err;
use crate::modules::LazyEsmModuleLoader;
use crate::modules::ModuleCodeString;
use crate::modules::ModuleId;
use crate::modules::ModuleLoader;
use crate::modules::ModuleName;
use crate::modules::RequestedModuleType;
use crate::modules::loaders::ModuleLoadOptions;

impl ModuleMap {
  /// Load and evaluate an ES module provided the specifier and source code.
  ///
  /// The module should not have Top-Level Await (that is, it should be
  /// possible to evaluate it synchronously).
  ///
  /// It is caller's responsibility to ensure that not duplicate specifiers are
  /// passed to this method.
  pub(crate) fn lazy_load_es_module_with_code(
    &self,
    scope: &mut v8::PinScope,
    module_specifier: &str,
    source_code: ModuleCodeString,
    code_cache_info: Option<CodeCacheInfo>,
  ) -> Result<v8::Global<v8::Value>, CoreError> {
    let specifier = ModuleSpecifier::parse(module_specifier)?;
    let previous_loading_internal_modules =
      is_internal_scheme(specifier.scheme())
        .then(|| self.loading_internal_modules.replace(true));
    let result = self.lazy_load_es_module_with_code_inner(
      scope,
      specifier,
      source_code,
      code_cache_info,
    );
    if let Some(previous) = previous_loading_internal_modules {
      self.loading_internal_modules.set(previous);
    }
    result
  }

  fn lazy_load_es_module_with_code_inner(
    &self,
    scope: &mut v8::PinScope,
    specifier: ModuleSpecifier,
    source_code: ModuleCodeString,
    code_cache_info: Option<CodeCacheInfo>,
  ) -> Result<v8::Global<v8::Value>, CoreError> {
    let mod_id = self
      .new_es_module(
        scope,
        false,
        specifier.into(),
        source_code,
        false,
        code_cache_info,
      )
      .map_err(|e| e.into_error(scope, false, true))?;

    self.instantiate_module(scope, mod_id).map_err(|e| {
      let exception = v8::Local::new(scope, e);
      exception_to_err(scope, exception, false, true)
    })?;

    let module_handle = self.get_handle(mod_id).unwrap();
    let module_local = v8::Local::<v8::Module>::new(scope, module_handle);

    let status = module_local.get_status();
    assert_eq!(status, v8::ModuleStatus::Instantiated);

    let value = module_local.evaluate(scope).unwrap();
    // Under Explicit microtask policy, drain microtasks so the module
    // evaluation promise resolves for synchronous modules.
    //
    // However, skip the checkpoint when we are inside a top-level
    // `module.evaluate()` call (i.e. `evaluating_top_level` is set).
    // Draining microtasks at this point can prematurely resolve
    // TLA-related microtasks (e.g. `await` resume jobs from eagerly-
    // resolved async ops), which prevents the module evaluation promise
    // from settling correctly later.
    if !self.evaluating_top_level.get() {
      scope.perform_microtask_checkpoint();
    }
    let promise = v8::Local::<v8::Promise>::try_from(value).unwrap();
    let result = promise.result(scope);
    if !result.is_undefined() {
      return Err(
        CoreErrorKind::Js(exception_to_err(scope, result, false, true))
          .into_box(),
      );
    }

    let status = module_local.get_status();
    assert_eq!(status, v8::ModuleStatus::Evaluated);

    let mod_ns = module_local.get_module_namespace();

    Ok(v8::Global::new(scope, mod_ns))
  }

  /// Check if a lazy-loaded ESM module is known to exist for the given
  /// specifier.
  pub(crate) fn has_lazy_esm_source(&self, specifier: &str) -> bool {
    let data = self.data.borrow();
    data.known_lazy_esm.borrow().contains(specifier)
  }

  /// Get a lazy-loaded ESM source by specifier. Returns a cheap clone of the
  /// source code if found, keeping it in the lazy sources map so concurrent
  /// loads of the same lazy specifier from independent `RecursiveModuleLoad`
  /// instances each get their own copy. The duplicate `ModuleSource`s are
  /// deduplicated by `new_module_with_pending`'s `get_id` check at register
  /// time.
  ///
  /// The entry only has to survive until the module is registered — at that
  /// point `create_module_info` drops it, so the source text isn't retained
  /// for the life of the process.
  pub(crate) fn take_lazy_esm_source(
    &self,
    specifier: &str,
  ) -> Option<ModuleCodeString> {
    let data = self.data.borrow();
    let mut sources = data.lazy_esm_sources.borrow_mut();
    let entry = sources.get_mut(specifier)?;
    // `into_cheap_copy` always returns two cheap handles to the same backing
    // storage (Arc or Static), so we can keep one in the map and return the
    // other. The Owned variant gets promoted to Arc in the process.
    let placeholder = ModuleCodeString::from_static("");
    let owned = std::mem::replace(entry, placeholder);
    let (keep, give) = owned.into_cheap_copy();
    *entry = keep;
    data
      .consumed_lazy_specifiers
      .borrow_mut()
      .insert(specifier.to_string());
    Some(give)
  }

  pub(crate) fn add_lazy_loaded_esm_source(
    &self,
    specifier: ModuleName,
    code: ModuleCodeString,
  ) {
    let data = self.data.borrow_mut();
    data
      .known_lazy_esm
      .borrow_mut()
      .insert(std::borrow::Cow::Owned(specifier.as_str().to_string()));
    assert!(
      data
        .lazy_esm_sources
        .borrow_mut()
        .insert(specifier, code)
        .is_none()
    );
  }

  /// Lazy load and evaluate an ES module. Only modules that have been added
  /// during build time can be executed (the ones stored in
  /// `ModuleMapData::lazy_esm_sources`), not _any, random_ module.
  /// Sync load + evaluate path for a `synthetic_esm` module. Used by the
  /// dynamic-import fast path. Returns the module namespace.
  pub(crate) fn lazy_load_synthetic_esm_module(
    &self,
    scope: &mut v8::PinScope,
    module_specifier: &str,
  ) -> Result<v8::Global<v8::Value>, CoreError> {
    // Use existing module if already constructed.
    let cached_handle = {
      let data = self.data.borrow();
      data
        .get_id(module_specifier, RequestedModuleType::None)
        .and_then(|id| data.get_handle(id))
    };
    if let Some(handle) = cached_handle {
      let handle_local = v8::Local::new(scope, handle);
      if handle_local.get_status() == v8::ModuleStatus::Instantiated {
        let value = handle_local.evaluate(scope).unwrap();
        if !self.evaluating_top_level.get() {
          scope.perform_microtask_checkpoint();
        }
        let promise = v8::Local::<v8::Promise>::try_from(value).unwrap();
        let result = promise.result(scope);
        if !result.is_undefined() {
          return Err(
            CoreErrorKind::Js(exception_to_err(scope, result, false, true))
              .into_box(),
          );
        }
      }
      return Ok(v8::Global::new(scope, handle_local.get_module_namespace()));
    }

    let module_id = self.build_synthetic_esm_module(scope, module_specifier)?;
    let handle = self.get_handle(module_id).unwrap();
    let handle_local = v8::Local::new(scope, handle);
    let value = handle_local.evaluate(scope).unwrap();
    if !self.evaluating_top_level.get() {
      scope.perform_microtask_checkpoint();
    }
    let promise = v8::Local::<v8::Promise>::try_from(value).unwrap();
    let result = promise.result(scope);
    if !result.is_undefined() {
      return Err(
        CoreErrorKind::Js(exception_to_err(scope, result, false, true))
          .into_box(),
      );
    }
    Ok(v8::Global::new(scope, handle_local.get_module_namespace()))
  }

  pub(crate) fn lazy_load_esm_module(
    &self,
    scope: &mut v8::PinScope,
    module_specifier: &str,
  ) -> Result<v8::Global<v8::Value>, CoreError> {
    if !self.has_lazy_esm_source(module_specifier) {
      return Err(
        JsErrorBox::generic(format!(
          "Specifier \"{module_specifier}\" cannot be lazy-loaded as it was not included in the binary."
        ))
        .into(),
      );
    }

    let lazy_esm_sources = self.data.borrow().lazy_esm_sources.clone();
    let loader = LazyEsmModuleLoader::new(lazy_esm_sources);

    // Check if this module has already been loaded. We release the
    // `self.data` borrow before doing anything that could re-enter the
    // module map (notably `module.evaluate(scope)`, which can recursively
    // compile dependent modules and would otherwise panic with a
    // `RefCell already borrowed` at `new_module_from_js_source`).
    let cached_id_and_handle = {
      let module_map_data = self.data.borrow();
      module_map_data
        .get_id(module_specifier, RequestedModuleType::None)
        .and_then(|id| module_map_data.get_handle(id).map(|h| (id, h)))
    };
    if let Some((cached_id, handle)) = cached_id_and_handle {
      crate::modules::import_graph::record_lazy_esm_cached(
        scope,
        module_specifier,
      );
      let handle_local = v8::Local::new(scope, handle);
      // The module may be present in the map but not yet instantiated --
      // e.g. when this lazy load fires from inside a sibling module's
      // resolve-callback (a `synthetic_esm` backing script synchronously
      // calling `op_lazy_load_esm` for a peer that the surrounding
      // `RecursiveModuleLoad` has registered but not yet instantiated).
      // `get_module_namespace` requires Instantiated+, so drive the module
      // forward synchronously here.
      if handle_local.get_status() == v8::ModuleStatus::Uninstantiated {
        self.instantiate_module(scope, cached_id).map_err(|e| {
          let exception = v8::Local::new(scope, e);
          exception_to_err(scope, exception, false, true)
        })?;
      }
      // Returning the namespace before evaluation leaves `export const`
      // bindings in the temporal dead zone, so trigger evaluation here.
      if handle_local.get_status() == v8::ModuleStatus::Instantiated {
        let value = handle_local.evaluate(scope).unwrap();
        if !self.evaluating_top_level.get() {
          scope.perform_microtask_checkpoint();
        }
        let promise = v8::Local::<v8::Promise>::try_from(value).unwrap();
        let result = promise.result(scope);
        if !result.is_undefined() {
          return Err(
            CoreErrorKind::Js(exception_to_err(scope, result, false, true))
              .into_box(),
          );
        }
      }
      let module = v8::Global::new(scope, handle_local.get_module_namespace());
      return Ok(module);
    }

    // Cache miss: real load incoming. This is the call that pays the
    // parse/compile/evaluate cost at runtime.
    crate::modules::import_graph::record_lazy_esm(scope, module_specifier);

    let specifier = ModuleSpecifier::parse(module_specifier)?;

    let load_response = loader.load(
      &specifier,
      None,
      ModuleLoadOptions {
        is_dynamic_import: false,
        is_synchronous: false,
        requested_module_type: RequestedModuleType::None,
      },
    );

    let source = match load_response {
      ModuleLoadResponse::Sync(result) => result,
      ModuleLoadResponse::Async(fut) => futures::executor::block_on(fut),
    }?;

    // `LazyEsmModuleLoader` only knows the in-binary static sources and has no
    // DENO_DIR access, so `source.code_cache` is always `None` here. Read the
    // persisted V8 code cache from the REAL loader (Cli/EmbeddedModuleLoader)
    // instead — the same seam the residual `lazy_loaded_js` path uses. Without
    // this, residual ESM (node:process, node:module, the stream/net/tty
    // closure) re-pays parse+compile in every isolate on every cold start.
    let source_code = ModuleSource::get_string_source(source.code);
    // Build a `CodeCacheInfo` whenever the loader returns `Some` — even when
    // `data` is `None` (cold run). The `Some`-with-`data: None` case is what
    // arms the write side so the first run stores; warm runs consume.
    let code_cache_info = self
      .loader
      .borrow()
      .get_code_cache(&specifier, AsRef::<str>::as_ref(&source_code))
      .map(|info| {
        let loader = self.loader.borrow().clone();
        CodeCacheInfo {
          data: info.data,
          // `specifier` is unused after this, so move it straight in.
          ready_callback: Box::new(move |cache| {
            loader.code_cache_ready(specifier, info.hash, cache)
          }),
        }
      });

    self.lazy_load_es_module_with_code(
      scope,
      module_specifier,
      source_code,
      code_cache_info,
    )
  }

  pub(crate) fn add_lazy_loaded_script_source(
    &self,
    specifier: ModuleName,
    code: ModuleCodeString,
  ) {
    let data = self.data.borrow_mut();
    assert!(
      data
        .lazy_script_sources
        .borrow_mut()
        .insert(specifier, code)
        .is_none(),
      "Duplicate lazy script source"
    );
  }

  /// Check if a specifier was registered as a `synthetic_esm` module.
  pub(crate) fn has_synthetic_esm_module(&self, specifier: &str) -> bool {
    let data = self.data.borrow();
    let modules = data.synthetic_esm_modules.borrow();
    let key: ModuleName = String::from(specifier).into();
    modules.contains_key(&key)
  }

  /// Register a `(module_specifier -> backing_script_specifier)` mapping
  /// for the `synthetic_esm` dispatch. Called at extension init from each
  /// extension's `synthetic_esm_modules` list.
  pub(crate) fn add_synthetic_esm_module(
    &self,
    module_specifier: ModuleName,
    backing_specifier: ModuleName,
  ) {
    let data = self.data.borrow();
    assert!(
      data
        .synthetic_esm_modules
        .borrow_mut()
        .insert(module_specifier, backing_specifier)
        .is_none(),
      "Duplicate synthetic_esm module mapping"
    );
  }

  /// Build a synthetic module for a `synthetic_esm`-registered specifier
  /// by evaluating its backing script (cache hit on second+ call) and
  /// deriving exports from the returned IIFE object. Returns the new
  /// `ModuleId`, or an error if the specifier is not registered or the
  /// backing script did not return an object.
  pub(crate) fn build_synthetic_esm_module(
    &self,
    scope: &mut v8::PinScope,
    specifier: &str,
  ) -> Result<ModuleId, CoreError> {
    let backing_specifier = {
      let data = self.data.borrow();
      let modules = data.synthetic_esm_modules.borrow();
      let key: ModuleName = String::from(specifier).into();
      modules.get(&key).map(|v| v.as_str().to_string())
    }
    .ok_or_else(|| {
      CoreError::from(JsErrorBox::generic(format!(
        "Specifier {specifier} is not a synthetic_esm module"
      )))
    })?;

    let exports_global = self.load_ext_script(scope, &backing_specifier)?;
    let exports_local = v8::Local::new(scope, exports_global);
    let exports_obj = v8::Local::<v8::Object>::try_from(exports_local)
      .map_err(|_| {
        CoreError::from(JsErrorBox::type_error(format!(
          "synthetic_esm backing script {backing_specifier} did not return an object"
        )))
      })?;

    Ok(self.new_synthetic_module_from_exports_object(
      scope,
      String::from(specifier),
      exports_obj,
    ))
  }

  /// Convenience wrapper around `build_synthetic_esm_module` for the V8
  /// `module_resolve_callback` path: returns the module's V8 handle if
  /// `specifier` is registered as a `synthetic_esm` target, or `None` if
  /// not. Throws into `scope` on evaluation failure.
  pub(super) fn try_resolve_synthetic_esm<'s, 'i>(
    &self,
    scope: &mut v8::PinScope<'s, 'i>,
    specifier: &str,
  ) -> Option<v8::Local<'s, v8::Module>> {
    if !self.has_synthetic_esm_module(specifier) {
      return None;
    }
    match self.build_synthetic_esm_module(scope, specifier) {
      Ok(module_id) => {
        let handle = self.get_handle(module_id)?;
        Some(v8::Local::new(scope, handle))
      }
      Err(e) => {
        crate::error::throw_js_error_class(scope, &e);
        None
      }
    }
  }

  /// Load and evaluate a script on demand. The evaluated result is
  /// cached in `loaded_script_results` so later callers (the JS
  /// `Deno.core.loadExtScript()` op, the `synthetic_esm` dispatch, etc.)
  /// share a single evaluation — the source is consumed on first eval,
  /// and re-evaluating polyfill IIFEs would clobber registered hooks and
  /// duplicate class identities. Circular dependencies are detected and
  /// cause an error.
  pub(crate) fn load_ext_script(
    &self,
    scope: &mut v8::PinScope,
    specifier: &str,
  ) -> Result<v8::Global<v8::Value>, CoreError> {
    crate::modules::import_graph::record_lazy_script(scope, specifier);
    let specifier_str = String::from(specifier);
    let data = self.data.borrow();

    // Cache hit: return the previously evaluated result.
    {
      let specifier_key: ModuleName = specifier_str.clone().into();
      if let Some(cached) =
        data.loaded_script_results.borrow().get(&specifier_key)
      {
        return Ok(cached.clone());
      }
    }

    // Circular dependency detection.
    {
      let specifier_key: ModuleName = specifier_str.clone().into();
      let loading = data.lazy_script_loading.borrow();
      if loading.contains(&specifier_key) {
        return Err(
          JsErrorBox::generic(format!(
            "Circular dependency detected when loading script \"{specifier}\""
          ))
          .into(),
        );
      }
    }

    // Look up source.
    let source = {
      let specifier_key: ModuleName = specifier_str.clone().into();
      let mut sources = data.lazy_script_sources.borrow_mut();
      sources.remove(&specifier_key)
    };
    let source = match source {
      Some(s) => s,
      None => {
        return Err(
          JsErrorBox::generic(format!(
            "Script \"{specifier}\" cannot be lazy-loaded as it was not included in the binary."
          ))
          .into(),
        );
      }
    };

    data
      .consumed_lazy_specifiers
      .borrow_mut()
      .insert(specifier_str.clone());

    // Mark as loading for circular dep detection.
    data
      .lazy_script_loading
      .borrow_mut()
      .insert(specifier_str.clone().into());

    // We need to drop `data` before executing the script, since the script
    // may call back into `load_ext_script` for its own dependencies.
    drop(data);

    // Each script's IIFE preamble destructures the snapshot-time
    // `__bootstrap` view (a frozen clone of `core.ops` captured before
    // `removeImportedOps()` runs). To avoid leaving `__bootstrap` on
    // `globalThis` (where user code or `Object.keys` would see it), we
    // compile the source as the body of a function with one named
    // parameter `__bootstrap` and invoke it with the captured value. The
    // script's `(function () { ... })()` is the function body's single
    // expression, so we wrap it with `return ( ... );` to surface the
    // IIFE's result as the function's return value.
    let name = v8::String::new(scope, specifier).unwrap();
    let origin = v8::ScriptOrigin::new(
      scope,
      name.into(),
      0,
      0,
      false,
      -1,
      None,
      false,
      false,
      false,
      None,
    );

    v8::tc_scope!(let tc_scope, scope);

    // The compile_function body is `"use strict"; return (<IIFE>);`. For
    // residual lazy scripts this wrapping is performed at build time
    // (`cli/snapshot/build.rs`), so `source` is a `&'static` external string we
    // can hand to V8 without an owned heap copy (avoiding a per-script source
    // string in the V8 heap). Sources that arrive unwrapped (e.g. consumed
    // during snapshot creation, before that path is build-time wrapped) are
    // wrapped here at runtime via `wrap_lazy_ext_script`.
    let v8_source = if AsRef::<str>::as_ref(&source)
      .starts_with("\"use strict\"; return (")
    {
      // Build-time wrapped residual: hand V8 the `&'static` external string
      // directly so the source stays off the V8 heap (file-backed/clean).
      source.v8_string(tc_scope).unwrap()
    } else {
      // Unwrapped (e.g. consumed during snapshot creation): wrap at runtime.
      let wrapped_source = wrap_lazy_ext_script(AsRef::<str>::as_ref(&source));
      v8::String::new(tc_scope, &wrapped_source).unwrap()
    };
    let bootstrap_param = v8::String::new(tc_scope, "__bootstrap").unwrap();
    // Persist a V8 code cache for this residual `lazy_loaded_js` module through
    // the same on-disk (DENO_DIR) cache user scripts use, keyed by specifier +
    // source hash. Residuals ship source-only in the binary, so without this a
    // node-heavy program re-pays parse+compile of the whole node-polyfill
    // closure at runtime on every cold start. The first run compiles and
    // stores; warm runs consume and skip parse+compile. Producing and consuming
    // binary are identical, so the cache is always accepted.
    //
    // The key is the pre-wrap `source`, while what gets compiled is
    // `v8_source`. That's sound because the wrap above is a pure function of
    // `source`: the same key can only ever have produced the same compiled
    // string.
    let cache_specifier = crate::ModuleSpecifier::parse(&specifier_str).ok();
    let code_cache_info = cache_specifier.as_ref().and_then(|spec| {
      self
        .loader
        .borrow()
        .get_code_cache(spec, AsRef::<str>::as_ref(&source))
    });
    let (mut compile_source, compile_options) =
      match code_cache_info.as_ref().and_then(|i| i.data.as_ref()) {
        Some(data) => (
          v8::script_compiler::Source::new_with_cached_data(
            v8_source,
            Some(&origin),
            v8::CachedData::new(data),
          ),
          v8::script_compiler::CompileOptions::ConsumeCodeCache,
        ),
        None => (
          v8::script_compiler::Source::new(v8_source, Some(&origin)),
          v8::script_compiler::CompileOptions::NoCompileOptions,
        ),
      };
    let function = match v8::script_compiler::compile_function(
      tc_scope,
      &mut compile_source,
      &[bootstrap_param],
      &[],
      compile_options,
      v8::script_compiler::NoCacheReason::NoReason,
    ) {
      Some(f) => f,
      None => {
        let exception = tc_scope.exception().unwrap();
        let err = JsError::from_v8_exception(tc_scope, exception);
        self
          .data
          .borrow()
          .lazy_script_loading
          .borrow_mut()
          .remove(&ModuleName::from(specifier_str.clone()));
        return Err(CoreErrorKind::Js(err).into_box());
      }
    };
    // Store the freshly-compiled cache on the first run (cold), or if V8
    // rejected the existing cache (e.g. the source changed).
    let rejected = compile_source
      .get_cached_data()
      .map(|d| d.rejected())
      .unwrap_or(true);
    let had_data = code_cache_info
      .as_ref()
      .map(|i| i.data.is_some())
      .unwrap_or(false);
    if (!had_data || rejected)
      && let (Some(spec), Some(info)) =
        (cache_specifier.as_ref(), code_cache_info.as_ref())
      && let Some(cache) = function.create_code_cache()
    {
      let fut = self.loader.borrow().code_cache_ready(
        spec.clone(),
        info.hash,
        &cache[..],
      );
      self.code_cache_ready_futs.push(fut);
    }

    let captured = self.data.borrow().captured_bootstrap.borrow().clone();
    let bootstrap_arg = match &captured {
      Some(global) => v8::Local::new(tc_scope, global),
      None => v8::undefined(tc_scope).into(),
    };
    let undefined: v8::Local<v8::Value> = v8::undefined(tc_scope).into();
    let result = match function.call(tc_scope, undefined, &[bootstrap_arg]) {
      Some(value) => v8::Global::new(tc_scope, value),
      None => {
        assert!(tc_scope.has_caught());
        let exception = tc_scope.exception().unwrap();
        let err = JsError::from_v8_exception(tc_scope, exception);
        self
          .data
          .borrow()
          .lazy_script_loading
          .borrow_mut()
          .remove(&ModuleName::from(specifier_str.clone()));
        return Err(CoreErrorKind::Js(err).into_box());
      }
    };

    // Remove from loading set and cache the result.
    {
      let data = self.data.borrow();
      data
        .lazy_script_loading
        .borrow_mut()
        .remove(&ModuleName::from(specifier_str.clone()));
      data
        .loaded_script_results
        .borrow_mut()
        .insert(ModuleName::from(specifier_str), result.clone());
    }

    Ok(result)
  }

  /// Stash the snapshot-time `__bootstrap` view registered from JS via
  /// `op_set_captured_bootstrap`. `load_ext_script` injects this value as
  /// the `__bootstrap` parameter when invoking each lazy script's compiled
  /// function — keeping the value off `globalThis` so user code never sees
  /// it.
  pub(crate) fn set_captured_bootstrap(&self, value: v8::Global<v8::Value>) {
    *self.data.borrow().captured_bootstrap.borrow_mut() = Some(value);
  }

  /// The snapshot-time `__bootstrap` view stashed by `set_captured_bootstrap`,
  /// if any. Used by the deferred fast-call upgrade to also update the cloned
  /// `core.ops` that residual ext modules read through.
  pub(crate) fn captured_bootstrap(&self) -> Option<v8::Global<v8::Value>> {
    self.data.borrow().captured_bootstrap.borrow().clone()
  }
}

/// Skip past a lazy-loaded script's leading prologue (line/block comments and
/// directive prologue like `"use strict";`) and return a slice that starts at
/// the IIFE's opening `(function`. Returns `None` if no such opener is found
/// — callers fall back to using the original source unchanged.
fn strip_script_prologue(source: &str) -> Option<&str> {
  let mut rest = source;
  loop {
    let trimmed = rest.trim_start();
    if let Some(after) = trimmed.strip_prefix("//") {
      // Line comment — skip to end of line.
      let nl = after.find('\n').map(|i| i + 1).unwrap_or(after.len());
      rest = &after[nl..];
      continue;
    }
    if let Some(after) = trimmed.strip_prefix("/*") {
      // Block comment — skip to closing `*/`.
      let end = after.find("*/").map(|i| i + 2).unwrap_or(after.len());
      rest = &after[end..];
      continue;
    }
    // Directive prologue: `"use strict";` or `'use strict';` (or any other
    // string-literal directive). A directive is a string literal followed
    // by a `;`/newline at the statement boundary.
    if trimmed.starts_with('"') || trimmed.starts_with('\'') {
      let quote = trimmed.as_bytes()[0];
      let after_quote = &trimmed[1..];
      if let Some(close) = after_quote.find(quote as char) {
        let after_str = after_quote[close + 1..].trim_start();
        if let Some(after_semi) = after_str.strip_prefix(';') {
          rest = after_semi;
          continue;
        }
      }
    }
    if trimmed.starts_with("(function") {
      return Some(trimmed);
    }
    return None;
  }
}

/// Wrap a lazy ext-script (`loadExtScript`) source into the `compile_function`
/// body we evaluate at load time: `"use strict"; return (<IIFE>);`.
///
/// The IIFE's completion value is the script's exports object (what the
/// original `Script::run` produced). We strip the leading prologue (comments +
/// any `"use strict";` directive — a bare directive is a statement and can't
/// sit inside `return ( ... )`) and the trailing `;`/whitespace so the IIFE is
/// the single operand of `return ( ... )`, and re-emit `"use strict";` at the
/// head so the body still runs in strict mode.
///
/// Performed at build time for residual lazy scripts so the stored source is a
/// `&'static` string that compiles without an owned heap copy; also used as the
/// runtime fallback for sources that arrive unwrapped.
pub fn wrap_lazy_ext_script(source: &str) -> String {
  let expr_start = strip_script_prologue(source).unwrap_or(source);
  let trimmed =
    expr_start.trim_end_matches(|c: char| c.is_whitespace() || c == ';');
  format!("\"use strict\"; return ({trimmed});")
}