deno_core 0.398.0

A modern JavaScript/TypeScript runtime built with V8, Rust, and Tokio
Documentation
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
// Copyright 2018-2026 the Deno authors. MIT license.

use std::borrow::Cow;
use std::cell::RefCell;
use std::rc::Rc;

use deno_error::JsErrorBox;

use self::runtime::CreateSnapshotOptions;
use self::runtime::create_snapshot;
use crate::modules::ModuleInfo;
use crate::modules::RequestedModuleType;
use crate::runtime::NO_OF_BUILTIN_MODULES;
use crate::*;

#[test]
fn will_snapshot() {
  let snapshot = {
    let mut runtime = JsRuntimeForSnapshot::new(Default::default());
    runtime.execute_script("a.js", "a = 1 + 2").unwrap();
    runtime.snapshot()
  };

  let snapshot = Box::leak(snapshot);
  let mut runtime2 = JsRuntime::new(RuntimeOptions {
    startup_snapshot: Some(snapshot),
    ..Default::default()
  });
  runtime2
    .execute_script("check.js", "if (a != 3) throw Error('x')")
    .unwrap();
}

#[test]
fn will_snapshot2() {
  let startup_data = {
    let mut runtime = JsRuntimeForSnapshot::new(Default::default());
    runtime.execute_script("a.js", "let a = 1 + 2").unwrap();
    runtime.snapshot()
  };

  let snapshot = Box::leak(startup_data);
  let mut runtime = JsRuntimeForSnapshot::new(RuntimeOptions {
    startup_snapshot: Some(snapshot),
    ..Default::default()
  });

  let startup_data = {
    runtime
      .execute_script("check_a.js", "if (a != 3) throw Error('x')")
      .unwrap();
    runtime.execute_script("b.js", "b = 2 + 3").unwrap();
    runtime.snapshot()
  };

  let snapshot = Box::leak(startup_data);
  {
    let mut runtime = JsRuntime::new(RuntimeOptions {
      startup_snapshot: Some(snapshot),
      ..Default::default()
    });
    runtime
      .execute_script("check_b.js", "if (b != 5) throw Error('x')")
      .unwrap();
    runtime
      .execute_script("check2.js", "if (!Deno.core) throw Error('x')")
      .unwrap();
  }
}

#[test]
fn test_snapshot_callbacks() {
  let snapshot = {
    let mut runtime = JsRuntimeForSnapshot::new(Default::default());
    runtime
      .execute_script(
        "a.js",
        r#"
        Deno.core.queueNextTick({
          callback: () => {},
          args: undefined,
          snapshot: undefined,
        });
        Deno.core.ops.op_set_format_exception_callback(()=> {
          return null;
        })
        Deno.core.setUnhandledPromiseRejectionHandler(() => {
          return false;
        });
        a = 1 + 2;
    "#,
      )
      .unwrap();
    runtime.snapshot()
  };

  let snapshot = Box::leak(snapshot);
  let mut runtime2 = JsRuntime::new(RuntimeOptions {
    startup_snapshot: Some(snapshot),
    ..Default::default()
  });
  runtime2
    .execute_script("check.js", "if (a != 3) throw Error('x')")
    .unwrap();
}

#[test]
fn test_from_snapshot() {
  let snapshot = {
    let mut runtime = JsRuntimeForSnapshot::new(Default::default());
    runtime.execute_script("a.js", "a = 1 + 2").unwrap();
    runtime.snapshot()
  };

  let snapshot = Box::leak(snapshot);
  let mut runtime2 = JsRuntime::new(RuntimeOptions {
    startup_snapshot: Some(snapshot),
    ..Default::default()
  });
  runtime2
    .execute_script("check.js", "if (a != 3) throw Error('x')")
    .unwrap();
}

/// Smoke test for create_snapshot.
#[test]
fn test_snapshot_creator() {
  let output = create_snapshot(
    CreateSnapshotOptions {
      cargo_manifest_dir: "",
      startup_snapshot: None,
      skip_op_registration: false,
      extension_transpiler: None,
      extensions: vec![],
      with_runtime_cb: Some(Box::new(|runtime| {
        runtime.execute_script("a.js", "a = 1 + 2").unwrap();
      })),
    },
    None,
  )
  .unwrap();

  let snapshot = Box::leak(output.output);

  let mut runtime2 = JsRuntime::new(RuntimeOptions {
    startup_snapshot: Some(snapshot),
    ..Default::default()
  });
  runtime2
    .execute_script("check.js", "if (a != 3) throw Error('x')")
    .unwrap();
}

#[test]
fn test_snapshot_creator_warmup() {
  let counter = Rc::new(RefCell::new(0));

  let c = counter.clone();
  let output = create_snapshot(
    CreateSnapshotOptions {
      cargo_manifest_dir: "",
      startup_snapshot: None,
      skip_op_registration: false,
      extensions: vec![],
      extension_transpiler: None,
      with_runtime_cb: Some(Box::new(move |runtime| {
        c.replace_with(|&mut c| c + 1);

        runtime.execute_script("a.js", "a = 1 + 2").unwrap();
      })),
    },
    Some("const b = 'Hello'"),
  )
  .unwrap();

  // `with_runtime_cb` executes twice, once for snapshot creation
  // and one for the warmup.
  assert_eq!(*counter.borrow(), 2);

  let snapshot = Box::leak(output.output);

  let mut runtime2 = JsRuntime::new(RuntimeOptions {
    startup_snapshot: Some(snapshot),
    ..Default::default()
  });
  runtime2
    .execute_script("check.js", "if (a != 3) throw Error('x')")
    .unwrap();
}

#[test]
fn es_snapshot() {
  fn create_module(
    runtime: &mut JsRuntime,
    i: usize,
    main: bool,
  ) -> ModuleInfo {
    let specifier = crate::resolve_url(&format!("file:///{i}.js")).unwrap();
    let prev = i - 1;
    let source_code = format!(
      r#"
      import {{ f{prev} }} from "file:///{prev}.js";
      export function f{i}() {{ return f{prev}() }}
      "#
    );

    let id = if main {
      futures::executor::block_on(
        runtime.load_main_es_module_from_code(&specifier, source_code),
      )
      .unwrap()
    } else {
      futures::executor::block_on(
        runtime.load_side_es_module_from_code(&specifier, source_code),
      )
      .unwrap()
    };
    assert_eq!(i + NO_OF_BUILTIN_MODULES, id);

    #[allow(clippy::let_underscore_future, reason = "test code")]
    let _ = runtime.mod_evaluate(id);
    futures::executor::block_on(runtime.run_event_loop(Default::default()))
      .unwrap();

    ModuleInfo {
      id,
      main,
      name: specifier.into(),
      requests: vec![crate::modules::ModuleRequest {
        reference: crate::modules::ModuleReference {
          specifier: ModuleSpecifier::parse(&format!("file:///{prev}.js"))
            .unwrap(),
          requested_module_type: RequestedModuleType::None,
        },
        specifier_key: Some(format!("file:///{prev}.js")),
        referrer_source_offset: Some(25 + prev.to_string().len() as i32),
        phase: crate::modules::ModuleImportPhase::Evaluation,
      }],
      module_type: ModuleType::JavaScript,
    }
  }

  #[allow(clippy::unnecessary_wraps, reason = "test code")]
  #[op2]
  #[string]
  fn op_test() -> Result<String, JsErrorBox> {
    Ok(String::from("test"))
  }
  let mut runtime = JsRuntimeForSnapshot::new(RuntimeOptions {
    extensions: vec![Extension {
      name: "test_ext",
      ops: Cow::Borrowed(&[DECL]),
      ..Default::default()
    }],
    ..Default::default()
  });

  let specifier = crate::resolve_url("file:///0.js").unwrap();
  let id = futures::executor::block_on(runtime.load_side_es_module_from_code(
    &specifier,
    r#"export function f0() { return "hello world" }"#,
  ))
  .unwrap();

  #[allow(clippy::let_underscore_future, reason = "test code")]
  let _ = runtime.mod_evaluate(id);
  futures::executor::block_on(runtime.run_event_loop(Default::default()))
    .unwrap();

  let mut modules = vec![];
  modules.push(ModuleInfo {
    id,
    main: false,
    name: specifier.into(),
    requests: vec![],
    module_type: ModuleType::JavaScript,
  });

  modules.extend((1..200).map(|i| create_module(&mut runtime, i, false)));

  runtime.module_map().assert_module_map(&modules);

  let snapshot = runtime.snapshot();
  let snapshot = Box::leak(snapshot);

  let mut runtime2 = JsRuntimeForSnapshot::new(RuntimeOptions {
    startup_snapshot: Some(snapshot),
    extensions: vec![Extension {
      name: "test_ext",
      ops: Cow::Borrowed(&[DECL]),
      ..Default::default()
    }],
    ..Default::default()
  });

  runtime2.module_map().assert_module_map(&modules);

  modules.extend((200..400).map(|i| create_module(&mut runtime2, i, false)));
  modules.push(create_module(&mut runtime2, 400, true));

  runtime2.module_map().assert_module_map(&modules);

  let snapshot2 = runtime2.snapshot();
  let snapshot2 = Box::leak(snapshot2);

  const DECL: OpDecl = op_test();
  let mut runtime3 = JsRuntime::new(RuntimeOptions {
    startup_snapshot: Some(snapshot2),
    extensions: vec![Extension {
      name: "test_ext",
      ops: Cow::Borrowed(&[DECL]),
      ..Default::default()
    }],
    ..Default::default()
  });

  runtime3.module_map().assert_module_map(&modules);

  let source_code = r#"(async () => {
    const mod = await import("file:///400.js");
    return mod.f400() + " " + Deno.core.ops.op_test();
  })();"#;
  let val = runtime3.execute_script(".", source_code).unwrap();
  #[allow(deprecated, reason = "TODO: document")]
  let val = futures::executor::block_on(runtime3.resolve_value(val)).unwrap();
  {
    deno_core::scope!(scope, runtime3);
    let value = v8::Local::new(scope, val);
    let str_ = value.to_string(scope).unwrap().to_rust_string_lossy(scope);
    assert_eq!(str_, "hello world test");
  }
}

#[test]
pub(crate) fn es_snapshot_without_runtime_module_loader() {
  let startup_data = {
    deno_core::extension!(
      module_snapshot,
      esm_entry_point = "ext:module_snapshot/test.js",
      esm = ["ext:module_snapshot/test.js" =
        { source = "globalThis.TEST = 'foo'; export const TEST = 'bar';" },]
    );

    let runtime = JsRuntimeForSnapshot::new(RuntimeOptions {
      extensions: vec![module_snapshot::init()],
      ..Default::default()
    });

    runtime.snapshot()
  };

  let snapshot = Box::leak(startup_data);

  let mut runtime = JsRuntime::new(RuntimeOptions {
    module_loader: None,
    startup_snapshot: Some(snapshot),
    ..Default::default()
  });
  let realm = runtime.main_realm();

  // Make sure the module was evaluated.
  {
    deno_core::scope!(scope, runtime);
    let global_test: v8::Local<v8::String> =
      JsRuntime::eval(scope, "globalThis.TEST").unwrap();
    assert_eq!(
      serde_v8::to_utf8(global_test.to_string(scope).unwrap(), scope),
      String::from("foo"),
    );
  }

  // Dynamic imports of ext: from non-ext: modules are not allowed.
  let dyn_import_promise = realm
    .execute_script(
      runtime.v8_isolate(),
      "",
      "import('ext:module_snapshot/test.js')",
    )
    .unwrap();
  #[allow(deprecated, reason = "TODO: document")]
  let dyn_import_result =
    futures::executor::block_on(runtime.resolve_value(dyn_import_promise));
  assert_eq!(
    dyn_import_result.err().unwrap().to_string().as_str(),
    r#"Uncaught (in promise) TypeError: Importing ext: modules is only allowed from ext: and node: modules. Tried to import ext:module_snapshot/test.js from (no referrer)"#
  );

  // But not a new one
  let dyn_import_promise = realm
    .execute_script(
      runtime.v8_isolate(),
      "",
      "import('ext:module_snapshot/test2.js')",
    )
    .unwrap();
  #[allow(deprecated, reason = "TODO: document")]
  let dyn_import_result =
    futures::executor::block_on(runtime.resolve_value(dyn_import_promise));
  assert!(dyn_import_result.is_err());
  assert_eq!(
    dyn_import_result.err().unwrap().to_string().as_str(),
    r#"Uncaught (in promise) TypeError: Importing ext: modules is only allowed from ext: and node: modules. Tried to import ext:module_snapshot/test2.js from (no referrer)"#
  );
}

#[test]
pub fn snapshot_with_additional_extensions() {
  #[op2]
  #[string]
  fn op_before() -> String {
    "before".to_owned()
  }

  #[op2]
  #[string]
  fn op_after() -> String {
    "after".to_owned()
  }

  deno_core::extension!(
    before_snapshot,
    ops = [op_before],
    esm_entry_point = "ext:module_snapshot/before.js",
    esm = ["ext:module_snapshot/before.js" =
      // If this throws, we accidentally tried to evaluate this module twice
      { source = "if (globalThis.before) { throw 'twice?' } globalThis.before = () => { globalThis.BEFORE = Deno.core.ops.op_before(); };" },]
  );
  deno_core::extension!(
    after_snapshot,
    ops = [op_after],
    esm_entry_point = "ext:module_snapshot/after.js",
    esm = ["ext:module_snapshot/after.js" = {
      source =
        "globalThis.before(); globalThis.AFTER = Deno.core.ops.op_after();"
    },]
  );

  let snapshot = {
    let runtime = JsRuntimeForSnapshot::new(RuntimeOptions {
      extensions: vec![before_snapshot::init()],
      ..Default::default()
    });

    Box::leak(runtime.snapshot())
  };

  let mut runtime = JsRuntime::new(RuntimeOptions {
    startup_snapshot: Some(snapshot),
    extensions: vec![before_snapshot::init(), after_snapshot::init()],
    ..Default::default()
  });

  // Make sure the module was evaluated.
  {
    deno_core::scope!(scope, runtime);
    let global_test: v8::Local<v8::String> =
      JsRuntime::eval(scope, "globalThis.BEFORE + '/' + globalThis.AFTER")
        .unwrap();
    assert_eq!(
      serde_v8::to_utf8(global_test.to_string(scope).unwrap(), scope),
      String::from("before/after"),
    );
  }
}