1'use strict'; 2 3// Flags: --experimental-vm-modules 4 5const common = require('../common'); 6 7const assert = require('assert'); 8const { Script, SourceTextModule } = require('vm'); 9 10async function testNoCallback() { 11 const m = new SourceTextModule(` 12 globalThis.importResult = import("foo"); 13 globalThis.importResult.catch(() => {}); 14 `); 15 await m.link(common.mustNotCall()); 16 await m.evaluate(); 17 let threw = false; 18 try { 19 await globalThis.importResult; 20 } catch (err) { 21 threw = true; 22 assert.strictEqual(err.code, 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING'); 23 } 24 delete globalThis.importResult; 25 assert(threw); 26} 27 28async function test() { 29 const foo = new SourceTextModule('export const a = 1;'); 30 await foo.link(common.mustNotCall()); 31 await foo.evaluate(); 32 33 { 34 const s = new Script('import("foo")', { 35 importModuleDynamically: common.mustCall((specifier, wrap) => { 36 assert.strictEqual(specifier, 'foo'); 37 assert.strictEqual(wrap, s); 38 return foo; 39 }), 40 }); 41 42 const result = s.runInThisContext(); 43 assert.strictEqual(foo.namespace, await result); 44 } 45 46 { 47 const m = new SourceTextModule('globalThis.fooResult = import("foo")', { 48 importModuleDynamically: common.mustCall((specifier, wrap) => { 49 assert.strictEqual(specifier, 'foo'); 50 assert.strictEqual(wrap, m); 51 return foo; 52 }), 53 }); 54 await m.link(common.mustNotCall()); 55 await m.evaluate(); 56 assert.strictEqual(foo.namespace, await globalThis.fooResult); 57 delete globalThis.fooResult; 58 } 59} 60 61async function testInvalid() { 62 const m = new SourceTextModule('globalThis.fooResult = import("foo")', { 63 importModuleDynamically: common.mustCall((specifier, wrap) => { 64 return 5; 65 }), 66 }); 67 await m.link(common.mustNotCall()); 68 await m.evaluate(); 69 await globalThis.fooResult.catch(common.mustCall((e) => { 70 assert.strictEqual(e.code, 'ERR_VM_MODULE_NOT_MODULE'); 71 })); 72 delete globalThis.fooResult; 73 74 const s = new Script('import("bar")', { 75 importModuleDynamically: common.mustCall((specifier, wrap) => { 76 return undefined; 77 }), 78 }); 79 let threw = false; 80 try { 81 await s.runInThisContext(); 82 } catch (e) { 83 threw = true; 84 assert.strictEqual(e.code, 'ERR_VM_MODULE_NOT_MODULE'); 85 } 86 assert(threw); 87} 88 89async function testInvalidimportModuleDynamically() { 90 assert.throws( 91 () => new Script( 92 'import("foo")', 93 { importModuleDynamically: false }), 94 { code: 'ERR_INVALID_ARG_TYPE' } 95 ); 96} 97 98(async function() { 99 await testNoCallback(); 100 await test(); 101 await testInvalid(); 102 await testInvalidimportModuleDynamically(); 103}()).then(common.mustCall()); 104