vm: add Synthetic modules

- Refactor vm.SourceTextModule (again)
- Add vm.Module abstract superclass
- Add vm.SyntheticModule

Refs: https://heycam.github.io/webidl/#synthetic-module-records

PR-URL: https://github.com/nodejs/node/pull/29864
Reviewed-By: Guy Bedford <guybedford@gmail.com>
This commit is contained in:
Gus Caplan authored and Rich Trott committed 2019-10-14 14:25:38 -07:00
1 parent 7991b57cfd
commit f9caee986c
19 files changed
+768 -536

No files matched your search

+1 -1
View File
@@ -1984,7 +1984,7 @@ The linker function returned a module for which linking has failed.
<a id="ERR_VM_MODULE_NOT_MODULE"></a>
### ERR_VM_MODULE_NOT_MODULE
The fulfilled value of a linking promise is not a `vm.SourceTextModule` object.
The fulfilled value of a linking promise is not a `vm.Module` object.
<a id="ERR_VM_MODULE_STATUS"></a>
### ERR_VM_MODULE_STATUS
+193 -106
View File
@@ -91,11 +91,10 @@ changes:
This option is part of the experimental API for the `--experimental-modules`
flag, and should not be considered stable.
* `specifier` {string} specifier passed to `import()`
* `module` {vm.SourceTextModule}
* Returns: {Module Namespace Object|vm.SourceTextModule} Returning a
`vm.SourceTextModule` is recommended in order to take advantage of error
tracking, and to avoid issues with namespaces that contain `then`
function exports.
* `module` {vm.Module}
* Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
If `options` is a string, then it specifies the filename.
@@ -301,9 +300,9 @@ console.log(globalVar);
// 1000
```
## Class: vm.SourceTextModule
## Class: vm.Module
<!-- YAML
added: v9.6.0
added: REPLACEME
-->
> Stability: 1 - Experimental
@@ -311,20 +310,20 @@ added: v9.6.0
*This feature is only available with the `--experimental-vm-modules` command
flag enabled.*
The `vm.SourceTextModule` class provides a low-level interface for using
The `vm.Module` class provides a low-level interface for using
ECMAScript modules in VM contexts. It is the counterpart of the `vm.Script`
class that closely mirrors [Source Text Module Record][]s as defined in the
ECMAScript specification.
class that closely mirrors [Module Record][]s as defined in the ECMAScript
specification.
Unlike `vm.Script` however, every `vm.SourceTextModule` object is bound to a
context from its creation. Operations on `vm.SourceTextModule` objects are
intrinsically asynchronous, in contrast with the synchronous nature of
`vm.Script` objects. With the help of async functions, however, manipulating
`vm.SourceTextModule` objects is fairly straightforward.
Unlike `vm.Script` however, every `vm.Module` object is bound to a context from
its creation. Operations on `vm.Module` objects are intrinsically asynchronous,
in contrast with the synchronous nature of `vm.Script` objects. With the help
of async functions, however, manipulating `vm.Module` objects is fairly
straightforward.
Using a `vm.SourceTextModule` object requires three distinct steps:
creation/parsing, linking, and evaluation. These three steps are illustrated in
the following example.
Using a `vm.Module` object requires three distinct steps: creation/parsing,
linking, and evaluation. These three steps are illustrated in the following
example.
This implementation lies at a lower level than the [ECMAScript Module
loader][]. There is also currently no way to interact with the Loader, though
@@ -404,70 +403,6 @@ const contextifiedSandbox = vm.createContext({ secret: 42 });
})();
```
### Constructor: new vm.SourceTextModule(code\[, options\])
* `code` {string} JavaScript Module code to parse
* `options`
* `identifier` {string} String used in stack traces.
**Default:** `'vm:module(i)'` where `i` is a context-specific ascending
index.
* `context` {Object} The [contextified][] object as returned by the
`vm.createContext()` method, to compile and evaluate this `Module` in.
* `lineOffset` {integer} Specifies the line number offset that is displayed
in stack traces produced by this `Module`. **Default:** `0`.
* `columnOffset` {integer} Specifies the column number offset that is
displayed in stack traces produced by this `Module`. **Default:** `0`.
* `initializeImportMeta` {Function} Called during evaluation of this `Module`
to initialize the `import.meta`.
* `meta` {import.meta}
* `module` {vm.SourceTextModule}
* `importModuleDynamically` {Function} Called during evaluation of this module
when `import()` is called. If this option is not specified, calls to
`import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].
* `specifier` {string} specifier passed to `import()`
* `module` {vm.SourceTextModule}
* Returns: {Module Namespace Object|vm.SourceTextModule} Returning a
`vm.SourceTextModule` is recommended in order to take advantage of error
tracking, and to avoid issues with namespaces that contain `then`
function exports.
Creates a new ES `Module` object.
Properties assigned to the `import.meta` object that are objects may
allow the `Module` to access information outside the specified `context`, if the
object is created in the top level context. Use `vm.runInContext()` to create
objects in a specific context.
```js
const vm = require('vm');
const contextifiedSandbox = vm.createContext({ secret: 42 });
(async () => {
const module = new vm.SourceTextModule(
'Object.getPrototypeOf(import.meta.prop).secret = secret;',
{
initializeImportMeta(meta) {
// Note: this object is created in the top context. As such,
// Object.getPrototypeOf(import.meta.prop) points to the
// Object.prototype in the top context rather than that in
// the sandbox.
meta.prop = {};
}
});
// Since module has no dependencies, the linker function will never be called.
await module.link(() => {});
await module.evaluate();
// Now, Object.prototype.secret will be equal to 42.
//
// To fix this problem, replace
// meta.prop = {};
// above with
// meta.prop = vm.runInContext('{}', contextifiedSandbox);
})();
```
### module.dependencySpecifiers
* {string[]}
@@ -475,8 +410,8 @@ const contextifiedSandbox = vm.createContext({ secret: 42 });
The specifiers of all dependencies of this module. The returned array is frozen
to disallow any changes to it.
Corresponds to the `[[RequestedModules]]` field of
[Source Text Module Record][]s in the ECMAScript specification.
Corresponds to the `[[RequestedModules]]` field of [Cyclic Module Record][]s in
the ECMAScript specification.
### module.error
@@ -489,7 +424,7 @@ accessing this property will result in a thrown exception.
The value `undefined` cannot be used for cases where there is not a thrown
exception due to possible ambiguity with `throw undefined;`.
Corresponds to the `[[EvaluationError]]` field of [Source Text Module Record][]s
Corresponds to the `[[EvaluationError]]` field of [Cyclic Module Record][]s
in the ECMAScript specification.
### module.evaluate(\[options\])
@@ -519,7 +454,7 @@ evaluated, in which case it will do one of the following two things:
This method cannot be called while the module is being evaluated
(`module.status` is `'evaluating'`) to prevent infinite recursion.
Corresponds to the [Evaluate() concrete method][] field of [Source Text Module
Corresponds to the [Evaluate() concrete method][] field of [Cyclic Module
Record][]s in the ECMAScript specification.
### module.link(linker)
@@ -532,9 +467,8 @@ Record][]s in the ECMAScript specification.
// ^^^^^ the module specifier
```
* `referencingModule` {vm.SourceTextModule} The `Module` object `link()` is
called on.
* Returns: {vm.SourceTextModule|Promise}
* `referencingModule` {vm.Module} The `Module` object `link()` is called on.
* Returns: {vm.Module|Promise}
* Returns: {Promise}
Link module dependencies. This method must be called before evaluation, and
@@ -568,7 +502,7 @@ that point all modules would have been fully linked already, the
[HostResolveImportedModule][] implementation is fully synchronous per
specification.
Corresponds to the [Link() concrete method][] field of [Source Text Module
Corresponds to the [Link() concrete method][] field of [Cyclic Module
Record][]s in the ECMAScript specification.
### module.namespace
@@ -603,7 +537,7 @@ The current status of the module. Will be one of:
* `'errored'`: The module has been evaluated, but an exception was thrown.
Other than `'errored'`, this status string corresponds to the specification's
[Source Text Module Record][]'s `[[Status]]` field. `'errored'` corresponds to
[Cyclic Module Record][]'s `[[Status]]` field. `'errored'` corresponds to
`'evaluated'` in the specification, but with `[[EvaluationError]]` set to a
value that is not `undefined`.
@@ -613,6 +547,159 @@ value that is not `undefined`.
The identifier of the current module, as set in the constructor.
## Class: vm.SourceTextModule
<!-- YAML
added: v9.6.0
-->
> Stability: 1 - Experimental
*This feature is only available with the `--experimental-vm-modules` command
flag enabled.*
* Extends: {vm.Module}
The `vm.SourceTextModule` class provides the [Source Text Module Record][] as
defined in the ECMAScript specification.
### Constructor: new vm.SourceTextModule(code[, options])
* `code` {string} JavaScript Module code to parse
* `options`
* `identifier` {string} String used in stack traces.
**Default:** `'vm:module(i)'` where `i` is a context-specific ascending
index.
* `context` {Object} The [contextified][] object as returned by the
`vm.createContext()` method, to compile and evaluate this `Module` in.
* `lineOffset` {integer} Specifies the line number offset that is displayed
in stack traces produced by this `Module`. **Default:** `0`.
* `columnOffset` {integer} Specifies the column number offset that is
displayed in stack traces produced by this `Module`. **Default:** `0`.
* `initializeImportMeta` {Function} Called during evaluation of this `Module`
to initialize the `import.meta`.
* `meta` {import.meta}
* `module` {vm.SourceTextModule}
* `importModuleDynamically` {Function} Called during evaluation of this module
when `import()` is called. If this option is not specified, calls to
`import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].
* `specifier` {string} specifier passed to `import()`
* `module` {vm.Module}
* Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
Creates a new `SourceTextModule` instance.
Properties assigned to the `import.meta` object that are objects may
allow the module to access information outside the specified `context`. Use
`vm.runInContext()` to create objects in a specific context.
```js
const vm = require('vm');
const contextifiedSandbox = vm.createContext({ secret: 42 });
(async () => {
const module = new vm.SourceTextModule(
'Object.getPrototypeOf(import.meta.prop).secret = secret;',
{
initializeImportMeta(meta) {
// Note: this object is created in the top context. As such,
// Object.getPrototypeOf(import.meta.prop) points to the
// Object.prototype in the top context rather than that in
// the sandbox.
meta.prop = {};
}
});
// Since module has no dependencies, the linker function will never be called.
await module.link(() => {});
await module.evaluate();
// Now, Object.prototype.secret will be equal to 42.
//
// To fix this problem, replace
// meta.prop = {};
// above with
// meta.prop = vm.runInContext('{}', contextifiedSandbox);
})();
```
## Class: vm.SyntheticModule
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental
*This feature is only available with the `--experimental-vm-modules` command
flag enabled.*
* Extends: {vm.Module}
The `vm.SyntheticModule` class provides the [Synthetic Module Record][] as
defined in the WebIDL specification. The purpose of synthetic modules is to
provide a generic interface for exposing non-JavaScript sources to ECMAScript
module graphs.
```js
const vm = require('vm');
const source = '{ "a": 1 }';
const module = new vm.SyntheticModule(['default'], function() {
const obj = JSON.parse(source);
this.setExport('default', obj);
});
// Use `module` in linking...
```
### Constructor: new vm.SyntheticModule(exportNames, evaluateCallback[, options])
<!-- YAML
added: REPLACEME
-->
* `exportNames` {string[]} Array of names that will be exported from the module.
* `evaluateCallback` {Function} Called when the module is evaluated.
* `options`
* `identifier` {string} String used in stack traces.
**Default:** `'vm:module(i)'` where `i` is a context-specific ascending
index.
* `context` {Object} The [contextified][] object as returned by the
`vm.createContext()` method, to compile and evaluate this `Module` in.
Creates a new `SyntheticModule` instance.
Objects assigned to the exports of this instance may allow importers of
the module to access information outside the specified `context`. Use
`vm.runInContext()` to create objects in a specific context.
### syntheticModule.setExport(name, value)
<!-- YAML
added: REPLACEME
-->
* `name` {string} Name of the export to set.
* `value` {any} The value to set the export to.
This method is used after the module is linked to set the values of exports. If
it is called before the module is linked, an [`ERR_VM_MODULE_STATUS`][] error
will be thrown.
```js
const vm = require('vm');
(async () => {
const m = new vm.SyntheticModule(['x'], () => {
m.setExport('x', 1);
});
await m.link(() => {});
await m.evaluate();
assert.strictEqual(m.namespace.x, 1);
})();
```
## vm.compileFunction(code\[, params\[, options\]\])
<!-- YAML
added: v10.10.0
@@ -770,11 +857,10 @@ changes:
This option is part of the experimental API for the `--experimental-modules`
flag, and should not be considered stable.
* `specifier` {string} specifier passed to `import()`
* `module` {vm.SourceTextModule}
* Returns: {Module Namespace Object|vm.SourceTextModule} Returning a
`vm.SourceTextModule` is recommended in order to take advantage of error
tracking, and to avoid issues with namespaces that contain `then`
function exports.
* `module` {vm.Module}
* Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
* Returns: {any} the result of the very last statement executed in the script.
The `vm.runInContext()` method compiles `code`, runs it within the context of
@@ -868,11 +954,10 @@ changes:
This option is part of the experimental API for the `--experimental-modules`
flag, and should not be considered stable.
* `specifier` {string} specifier passed to `import()`
* `module` {vm.SourceTextModule}
* Returns: {Module Namespace Object|vm.SourceTextModule} Returning a
`vm.SourceTextModule` is recommended in order to take advantage of error
tracking, and to avoid issues with namespaces that contain `then`
function exports.
* `module` {vm.Module}
* Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
* Returns: {any} the result of the very last statement executed in the script.
The `vm.runInNewContext()` first contextifies the given `sandbox` object (or
@@ -946,11 +1031,10 @@ changes:
This option is part of the experimental API for the `--experimental-modules`
flag, and should not be considered stable.
* `specifier` {string} specifier passed to `import()`
* `module` {vm.SourceTextModule}
* Returns: {Module Namespace Object|vm.SourceTextModule} Returning a
`vm.SourceTextModule` is recommended in order to take advantage of error
tracking, and to avoid issues with namespaces that contain `then`
function exports.
* `module` {vm.Module}
* Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
* Returns: {any} the result of the very last statement executed in the script.
`vm.runInThisContext()` compiles `code`, runs it within the context of the
@@ -1068,6 +1152,7 @@ This issue occurs because all contexts share the same microtask and nextTick
queues.
[`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`]: errors.html#ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING
[`ERR_VM_MODULE_STATUS`]: errors.html#ERR_VM_MODULE_STATUS
[`Error`]: errors.html#errors_class_error
[`URL`]: url.html#url_class_url
[`eval()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
@@ -1077,12 +1162,14 @@ queues.
[`vm.createContext()`]: #vm_vm_createcontext_sandbox_options
[`vm.runInContext()`]: #vm_vm_runincontext_code_contextifiedsandbox_options
[`vm.runInThisContext()`]: #vm_vm_runinthiscontext_code_options
[Cyclic Module Record]: https://tc39.es/ecma262/#sec-cyclic-module-records
[ECMAScript Module Loader]: esm.html#esm_ecmascript_modules
[Evaluate() concrete method]: https://tc39.es/ecma262/#sec-moduleevaluation
[GetModuleNamespace]: https://tc39.es/ecma262/#sec-getmodulenamespace
[HostResolveImportedModule]: https://tc39.es/ecma262/#sec-hostresolveimportedmodule
[Link() concrete method]: https://tc39.es/ecma262/#sec-moduledeclarationlinking
[Source Text Module Record]: https://tc39.es/ecma262/#sec-source-text-module-records
[Synthetic Module Record]: https://heycam.github.io/webidl/#synthetic-module-records
[V8 Embedder's Guide]: https://v8.dev/docs/embed#contexts
[contextified]: #vm_what_does_it_mean_to_contextify_an_object
[global object]: https://es5.github.io/#x15.1
+6 -4
View File
@@ -243,10 +243,12 @@ NativeModule.prototype.getESMFacade = function() {
const { ModuleWrap } = internalBinding('module_wrap');
const url = this.getURL();
const nativeModule = this;
this.module = new ModuleWrap(function() {
nativeModule.syncExports();
this.setExport('default', nativeModule.exports);
}, [...this.exportKeys, 'default'], url);
this.module = new ModuleWrap(
url, undefined, [...this.exportKeys, 'default'],
function() {
nativeModule.syncExports();
this.setExport('default', nativeModule.exports);
});
// Ensure immediate sync execution to capture exports now
this.module.instantiate();
this.module.evaluate(-1, false);
+1 -1
View File
@@ -59,7 +59,7 @@ function checkSyntax(source, filename) {
}
if (isModule) {
const { ModuleWrap } = internalBinding('module_wrap');
new ModuleWrap(source, filename);
new ModuleWrap(filename, undefined, source, 0, 0);
return;
}
}
+2 -2
View File
@@ -827,9 +827,9 @@ Module.prototype.load = function(filename) {
ESMLoader.moduleMap.set(
url,
new ModuleJob(ESMLoader, url, () =>
new ModuleWrap(function() {
new ModuleWrap(url, undefined, ['default'], function() {
this.setExport('default', exports);
}, ['default'], url)
})
)
);
}
@@ -28,7 +28,7 @@ ${ArrayPrototype.join(ArrayPrototype.map(exports, createExport), '\n')}
import.meta.done();
`;
const { ModuleWrap, callbackMap } = internalBinding('module_wrap');
const m = new ModuleWrap(source, `${url}`);
const m = new ModuleWrap(`${url}`, undefined, source, 0, 0);
const readyfns = new Set();
const reflect = {
+1 -1
View File
@@ -117,7 +117,7 @@ class Loader {
source,
url = pathToFileURL(`${process.cwd()}/[eval${++this.evalIndex}]`).href
) {
const evalInstance = (url) => new ModuleWrap(source, url);
const evalInstance = (url) => new ModuleWrap(url, undefined, source, 0, 0);
const job = new ModuleJob(this, url, evalInstance, false);
this.moduleMap.set(url, job);
const { module, result } = await job.run();
+11 -11
View File
@@ -79,7 +79,7 @@ translators.set('module', async function moduleStrategy(url) {
const source = `${await getSource(url)}`;
maybeCacheSourceMap(url, source);
debug(`Translating StandardModule ${url}`);
const module = new ModuleWrap(source, url);
const module = new ModuleWrap(url, undefined, source, 0, 0);
moduleWrap.callbackMap.set(module, {
initializeImportMeta,
importModuleDynamically,
@@ -103,17 +103,17 @@ translators.set('commonjs', function commonjsStrategy(url, isMain) {
];
if (module && module.loaded) {
const exports = module.exports;
return new ModuleWrap(function() {
return new ModuleWrap(url, undefined, ['default'], function() {
this.setExport('default', exports);
}, ['default'], url);
});
}
return new ModuleWrap(function() {
return new ModuleWrap(url, undefined, ['default'], function() {
debug(`Loading CJSModule ${url}`);
// We don't care about the return val of _load here because Module#load
// will handle it for us by checking the loader registry and filling the
// exports like above
CJSModule._load(pathname, undefined, isMain);
}, ['default'], url);
});
});
// Strategy for loading a node builtin CommonJS module that isn't
@@ -143,9 +143,9 @@ translators.set('json', async function jsonStrategy(url) {
module = CJSModule._cache[modulePath];
if (module && module.loaded) {
const exports = module.exports;
return new ModuleWrap(function() {
return new ModuleWrap(url, undefined, ['default'], function() {
this.setExport('default', exports);
}, ['default'], url);
});
}
}
const content = `${await getSource(url)}`;
@@ -156,9 +156,9 @@ translators.set('json', async function jsonStrategy(url) {
module = CJSModule._cache[modulePath];
if (module && module.loaded) {
const exports = module.exports;
return new ModuleWrap(function() {
return new ModuleWrap(url, undefined, ['default'], function() {
this.setExport('default', exports);
}, ['default'], url);
});
}
}
try {
@@ -178,10 +178,10 @@ translators.set('json', async function jsonStrategy(url) {
if (pathname) {
CJSModule._cache[modulePath] = module;
}
return new ModuleWrap(function() {
return new ModuleWrap(url, undefined, ['default'], function() {
debug(`Parsing JSONModule ${url}`);
this.setExport('default', module.exports);
}, ['default'], url);
});
});
// Strategy for loading a wasm module
+4 -4
View File
@@ -7,15 +7,15 @@ const {
const { Loader } = require('internal/modules/esm/loader');
const { pathToFileURL } = require('internal/url');
const {
wrapToModuleMap,
} = require('internal/vm/source_text_module');
getModuleFromWrap,
} = require('internal/vm/module');
exports.initializeImportMetaObject = function(wrap, meta) {
const { callbackMap } = internalBinding('module_wrap');
if (callbackMap.has(wrap)) {
const { initializeImportMeta } = callbackMap.get(wrap);
if (initializeImportMeta !== undefined) {
initializeImportMeta(meta, wrapToModuleMap.get(wrap) || wrap);
initializeImportMeta(meta, getModuleFromWrap(wrap) || wrap);
}
}
};
@@ -26,7 +26,7 @@ exports.importModuleDynamicallyCallback = async function(wrap, specifier) {
const { importModuleDynamically } = callbackMap.get(wrap);
if (importModuleDynamically !== undefined) {
return importModuleDynamically(
specifier, wrapToModuleMap.get(wrap) || wrap);
specifier, getModuleFromWrap(wrap) || wrap);
}
}
throw new ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING();
+409
View File
@@ -0,0 +1,409 @@
'use strict';
const { Object, Symbol, SafePromise } = primordials;
const { isContext } = internalBinding('contextify');
const { isModuleNamespaceObject } = require('internal/util/types');
const {
getConstructorOf,
customInspectSymbol,
emitExperimentalWarning,
} = require('internal/util');
const {
ERR_INVALID_ARG_TYPE,
ERR_VM_MODULE_ALREADY_LINKED,
ERR_VM_MODULE_DIFFERENT_CONTEXT,
ERR_VM_MODULE_LINKING_ERRORED,
ERR_VM_MODULE_NOT_MODULE,
ERR_VM_MODULE_STATUS,
} = require('internal/errors').codes;
const {
validateInt32,
validateUint32,
validateString,
} = require('internal/validators');
const binding = internalBinding('module_wrap');
const {
ModuleWrap,
kUninstantiated,
kInstantiating,
kInstantiated,
kEvaluating,
kEvaluated,
kErrored,
} = binding;
const STATUS_MAP = {
[kUninstantiated]: 'unlinked',
[kInstantiating]: 'linking',
[kInstantiated]: 'linked',
[kEvaluating]: 'evaluating',
[kEvaluated]: 'evaluated',
[kErrored]: 'errored',
};
let globalModuleId = 0;
const defaultModuleName = 'vm:module';
const wrapToModuleMap = new WeakMap();
const kWrap = Symbol('kWrap');
const kContext = Symbol('kContext');
const kPerContextModuleId = Symbol('kPerContextModuleId');
const kLink = Symbol('kLink');
class Module {
constructor(options) {
emitExperimentalWarning('VM Modules');
if (new.target === Module) {
// eslint-disable-next-line no-restricted-syntax
throw new TypeError('Module is not a constructor');
}
const {
context,
sourceText,
syntheticExportNames,
syntheticEvaluationSteps,
} = options;
if (context !== undefined) {
if (typeof context !== 'object' || context === null) {
throw new ERR_INVALID_ARG_TYPE('options.context', 'Object', context);
}
if (!isContext(context)) {
throw new ERR_INVALID_ARG_TYPE('options.context', 'vm.Context',
context);
}
}
let { identifier } = options;
if (identifier !== undefined) {
validateString(identifier, 'options.identifier');
} else if (context === undefined) {
identifier = `${defaultModuleName}(${globalModuleId++})`;
} else if (context[kPerContextModuleId] !== undefined) {
const curId = context[kPerContextModuleId];
identifier = `${defaultModuleName}(${curId})`;
context[kPerContextModuleId] += 1;
} else {
identifier = `${defaultModuleName}(0)`;
Object.defineProperty(context, kPerContextModuleId, {
value: 1,
writable: true,
enumerable: false,
configurable: true,
});
}
if (sourceText !== undefined) {
this[kWrap] = new ModuleWrap(identifier, context, sourceText,
options.lineOffset, options.columnOffset);
binding.callbackMap.set(this[kWrap], {
initializeImportMeta: options.initializeImportMeta,
importModuleDynamically: options.importModuleDynamically ?
importModuleDynamicallyWrap(options.importModuleDynamically) :
undefined,
});
} else if (syntheticEvaluationSteps) {
this[kWrap] = new ModuleWrap(identifier, context,
syntheticExportNames,
syntheticEvaluationSteps);
} else {
CHECK(false);
}
wrapToModuleMap.set(this[kWrap], this);
this[kContext] = context;
}
get identifier() {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
return this[kWrap].url;
}
get context() {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
return this[kContext];
}
get namespace() {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (this[kWrap].getStatus() < kInstantiated) {
throw new ERR_VM_MODULE_STATUS('must not be unlinked or linking');
}
return this[kWrap].getNamespace();
}
get status() {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
return STATUS_MAP[this[kWrap].getStatus()];
}
get error() {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (this[kWrap].getStatus() !== kErrored) {
throw new ERR_VM_MODULE_STATUS('must be errored');
}
return this[kWrap].getError();
}
async link(linker) {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (typeof linker !== 'function') {
throw new ERR_INVALID_ARG_TYPE('linker', 'function', linker);
}
if (this.status === 'linked') {
throw new ERR_VM_MODULE_ALREADY_LINKED();
}
if (this.status !== 'unlinked') {
throw new ERR_VM_MODULE_STATUS('must be unlinked');
}
await this[kLink](linker);
this[kWrap].instantiate();
}
async evaluate(options = {}) {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (typeof options !== 'object' || options === null) {
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
}
let timeout = options.timeout;
if (timeout === undefined) {
timeout = -1;
} else {
validateUint32(timeout, 'options.timeout', true);
}
const { breakOnSigint = false } = options;
if (typeof breakOnSigint !== 'boolean') {
throw new ERR_INVALID_ARG_TYPE('options.breakOnSigint', 'boolean',
breakOnSigint);
}
const status = this[kWrap].getStatus();
if (status !== kInstantiated &&
status !== kEvaluated &&
status !== kErrored) {
throw new ERR_VM_MODULE_STATUS(
'must be one of linked, evaluated, or errored'
);
}
const result = this[kWrap].evaluate(timeout, breakOnSigint);
return { __proto__: null, result };
}
[customInspectSymbol](depth, options) {
let ctor = getConstructorOf(this);
ctor = ctor === null ? Module : ctor;
if (typeof depth === 'number' && depth < 0)
return options.stylize(`[${ctor.name}]`, 'special');
const o = Object.create({ constructor: ctor });
o.status = this.status;
o.identifier = this.identifier;
o.context = this.context;
return require('internal/util/inspect').inspect(o, options);
}
}
const kDependencySpecifiers = Symbol('kDependencySpecifiers');
const kNoError = Symbol('kNoError');
class SourceTextModule extends Module {
#error = kNoError;
#statusOverride;
constructor(sourceText, options = {}) {
validateString(sourceText, 'sourceText');
if (typeof options !== 'object' || options === null) {
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
}
const {
lineOffset = 0,
columnOffset = 0,
initializeImportMeta,
importModuleDynamically,
context,
identifier,
} = options;
validateInt32(lineOffset, 'options.lineOffset');
validateInt32(columnOffset, 'options.columnOffset');
if (initializeImportMeta !== undefined &&
typeof initializeImportMeta !== 'function') {
throw new ERR_INVALID_ARG_TYPE(
'options.initializeImportMeta', 'function', initializeImportMeta);
}
if (importModuleDynamically !== undefined &&
typeof importModuleDynamically !== 'function') {
throw new ERR_INVALID_ARG_TYPE(
'options.importModuleDynamically', 'function',
importModuleDynamically);
}
super({
sourceText,
context,
identifier,
lineOffset,
columnOffset,
initializeImportMeta,
importModuleDynamically,
});
this[kLink] = async (linker) => {
this.#statusOverride = 'linking';
const promises = this[kWrap].link(async (identifier) => {
const module = await linker(identifier, this);
if (module[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (module.context !== this.context) {
throw new ERR_VM_MODULE_DIFFERENT_CONTEXT();
}
if (module.status === 'errored') {
throw new ERR_VM_MODULE_LINKING_ERRORED();
}
if (module.status === 'unlinked') {
await module[kLink](linker);
}
return module[kWrap];
});
try {
if (promises !== undefined) {
await SafePromise.all(promises);
}
} catch (e) {
this.#error = e;
throw e;
} finally {
this.#statusOverride = undefined;
}
};
this[kDependencySpecifiers] = undefined;
}
get dependencySpecifiers() {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (this[kDependencySpecifiers] === undefined) {
this[kDependencySpecifiers] = this[kWrap].getStaticDependencySpecifiers();
}
return this[kDependencySpecifiers];
}
get status() {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (this.#error !== kNoError) {
return 'errored';
}
if (this.#statusOverride) {
return this.#statusOverride;
}
return super.status;
}
get error() {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (this.#error !== kNoError) {
return this.#error;
}
return super.error;
}
}
class SyntheticModule extends Module {
constructor(exportNames, evaluateCallback, options = {}) {
if (!Array.isArray(exportNames) ||
exportNames.some((e) => typeof e !== 'string')) {
throw new ERR_INVALID_ARG_TYPE('exportNames', 'Array of strings',
exportNames);
}
if (typeof evaluateCallback !== 'function') {
throw new ERR_INVALID_ARG_TYPE('evaluateCallback', 'function',
evaluateCallback);
}
if (typeof options !== 'object' || options === null) {
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
}
const { context, identifier } = options;
super({
syntheticExportNames: exportNames,
syntheticEvaluationSteps: evaluateCallback,
context,
identifier,
});
this[kLink] = () => this[kWrap].link(() => { CHECK(false); });
}
setExport(name, value) {
if (this[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
validateString(name, 'name');
if (this[kWrap].getStatus() < kInstantiated) {
throw new ERR_VM_MODULE_STATUS('must be linked');
}
this[kWrap].setExport(name, value);
}
}
function importModuleDynamicallyWrap(importModuleDynamically) {
const importModuleDynamicallyWrapper = async (...args) => {
const m = await importModuleDynamically(...args);
if (isModuleNamespaceObject(m)) {
return m;
}
if (!m || m[kWrap] === undefined) {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (m.status === 'errored') {
throw m.error;
}
return m.namespace;
};
return importModuleDynamicallyWrapper;
}
module.exports = {
Module,
SourceTextModule,
SyntheticModule,
importModuleDynamicallyWrap,
getModuleFromWrap: (wrap) => wrapToModuleMap.get(wrap),
};
-333
View File
@@ -1,333 +0,0 @@
'use strict';
const { Object, SafePromise } = primordials;
const { isModuleNamespaceObject } = require('internal/util/types');
const { isContext } = internalBinding('contextify');
const {
ERR_INVALID_ARG_TYPE,
ERR_VM_MODULE_ALREADY_LINKED,
ERR_VM_MODULE_DIFFERENT_CONTEXT,
ERR_VM_MODULE_LINKING_ERRORED,
ERR_VM_MODULE_NOT_MODULE,
ERR_VM_MODULE_STATUS,
} = require('internal/errors').codes;
const {
getConstructorOf,
customInspectSymbol,
emitExperimentalWarning
} = require('internal/util');
const {
validateInt32,
validateUint32,
validateString,
} = require('internal/validators');
const binding = internalBinding('module_wrap');
const {
ModuleWrap,
kUninstantiated,
kInstantiating,
kInstantiated,
kEvaluating,
kEvaluated,
kErrored,
} = binding;
const STATUS_MAP = {
[kUninstantiated]: 'unlinked',
[kInstantiating]: 'linking',
[kInstantiated]: 'linked',
[kEvaluating]: 'evaluating',
[kEvaluated]: 'evaluated',
[kErrored]: 'errored',
};
let globalModuleId = 0;
const defaultModuleName = 'vm:module';
const perContextModuleId = new WeakMap();
const wrapToModuleMap = new WeakMap();
const kNoError = Symbol('kNoError');
class SourceTextModule {
#wrap;
#identifier;
#context;
#dependencySpecifiers;
#statusOverride;
#error = kNoError;
constructor(source, options = {}) {
emitExperimentalWarning('vm.SourceTextModule');
validateString(source, 'source');
if (typeof options !== 'object' || options === null)
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
const {
context,
lineOffset = 0,
columnOffset = 0,
initializeImportMeta,
importModuleDynamically,
} = options;
if (context !== undefined) {
if (typeof context !== 'object' || context === null) {
throw new ERR_INVALID_ARG_TYPE('options.context', 'Object', context);
}
if (!isContext(context)) {
throw new ERR_INVALID_ARG_TYPE('options.context', 'vm.Context',
context);
}
}
validateInt32(lineOffset, 'options.lineOffset');
validateInt32(columnOffset, 'options.columnOffset');
if (initializeImportMeta !== undefined &&
typeof initializeImportMeta !== 'function') {
throw new ERR_INVALID_ARG_TYPE(
'options.initializeImportMeta', 'function', initializeImportMeta);
}
if (importModuleDynamically !== undefined &&
typeof importModuleDynamically !== 'function') {
throw new ERR_INVALID_ARG_TYPE(
'options.importModuleDynamically', 'function', importModuleDynamically);
}
let { identifier } = options;
if (identifier !== undefined) {
validateString(identifier, 'options.identifier');
} else if (context === undefined) {
identifier = `${defaultModuleName}(${globalModuleId++})`;
} else if (perContextModuleId.has(context)) {
const curId = perContextModuleId.get(context);
identifier = `${defaultModuleName}(${curId})`;
perContextModuleId.set(context, curId + 1);
} else {
identifier = `${defaultModuleName}(0)`;
perContextModuleId.set(context, 1);
}
this.#wrap = new ModuleWrap(
source, identifier, context,
lineOffset, columnOffset,
);
wrapToModuleMap.set(this.#wrap, this);
this.#identifier = identifier;
this.#context = context;
binding.callbackMap.set(this.#wrap, {
initializeImportMeta,
importModuleDynamically: importModuleDynamically ?
importModuleDynamicallyWrap(importModuleDynamically) :
undefined,
});
}
get status() {
try {
this.#error;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (this.#error !== kNoError) {
return 'errored';
}
if (this.#statusOverride) {
return this.#statusOverride;
}
return STATUS_MAP[this.#wrap.getStatus()];
}
get identifier() {
try {
return this.#identifier;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
}
get context() {
try {
return this.#context;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
}
get namespace() {
try {
this.#wrap;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (this.#wrap.getStatus() < kInstantiated) {
throw new ERR_VM_MODULE_STATUS('must not be unlinked or linking');
}
return this.#wrap.getNamespace();
}
get dependencySpecifiers() {
try {
this.#dependencySpecifiers;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (this.#dependencySpecifiers === undefined) {
this.#dependencySpecifiers = this.#wrap.getStaticDependencySpecifiers();
}
return this.#dependencySpecifiers;
}
get error() {
try {
this.#error;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (this.#error !== kNoError) {
return this.#error;
}
if (this.#wrap.getStatus() !== kErrored) {
throw new ERR_VM_MODULE_STATUS('must be errored');
}
return this.#wrap.getError();
}
async link(linker) {
try {
this.#link;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (typeof linker !== 'function') {
throw new ERR_INVALID_ARG_TYPE('linker', 'function', linker);
}
if (this.status !== 'unlinked') {
throw new ERR_VM_MODULE_ALREADY_LINKED();
}
await this.#link(linker);
this.#wrap.instantiate();
}
#link = async function(linker) {
this.#statusOverride = 'linking';
const promises = this.#wrap.link(async (identifier) => {
const module = await linker(identifier, this);
try {
module.#wrap;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (module.context !== this.context) {
throw new ERR_VM_MODULE_DIFFERENT_CONTEXT();
}
if (module.status === 'errored') {
throw new ERR_VM_MODULE_LINKING_ERRORED();
}
if (module.status === 'unlinked') {
await module.#link(linker);
}
return module.#wrap;
});
try {
if (promises !== undefined) {
await SafePromise.all(promises);
}
} catch (e) {
this.#error = e;
throw e;
} finally {
this.#statusOverride = undefined;
}
};
async evaluate(options = {}) {
try {
this.#wrap;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (typeof options !== 'object' || options === null) {
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
}
let timeout = options.timeout;
if (timeout === undefined) {
timeout = -1;
} else {
validateUint32(timeout, 'options.timeout', true);
}
const { breakOnSigint = false } = options;
if (typeof breakOnSigint !== 'boolean') {
throw new ERR_INVALID_ARG_TYPE('options.breakOnSigint', 'boolean',
breakOnSigint);
}
const status = this.#wrap.getStatus();
if (status !== kInstantiated &&
status !== kEvaluated &&
status !== kErrored) {
throw new ERR_VM_MODULE_STATUS(
'must be one of linked, evaluated, or errored'
);
}
const result = this.#wrap.evaluate(timeout, breakOnSigint);
return { __proto__: null, result };
}
static importModuleDynamicallyWrap(importModuleDynamically) {
// Named declaration for function name
const importModuleDynamicallyWrapper = async (...args) => {
const m = await importModuleDynamically(...args);
if (isModuleNamespaceObject(m)) {
return m;
}
try {
m.#wrap;
} catch {
throw new ERR_VM_MODULE_NOT_MODULE();
}
if (m.status === 'errored') {
throw m.error;
}
return m.namespace;
};
return importModuleDynamicallyWrapper;
}
[customInspectSymbol](depth, options) {
let ctor = getConstructorOf(this);
ctor = ctor === null ? SourceTextModule : ctor;
if (typeof depth === 'number' && depth < 0)
return options.stylize(`[${ctor.name}]`, 'special');
const o = Object.create({ constructor: ctor });
o.status = this.status;
o.identifier = this.identifier;
o.context = this.context;
return require('internal/util/inspect').inspect(o, options);
}
}
// Declared as static to allow access to #wrap
const importModuleDynamicallyWrap =
SourceTextModule.importModuleDynamicallyWrap;
delete SourceTextModule.importModuleDynamicallyWrap;
module.exports = {
SourceTextModule,
wrapToModuleMap,
importModuleDynamicallyWrap,
};
+6 -2
View File
@@ -99,7 +99,7 @@ class Script extends ContextifyScript {
importModuleDynamically);
}
const { importModuleDynamicallyWrap } =
require('internal/vm/source_text_module');
require('internal/vm/module');
const { callbackMap } = internalBinding('module_wrap');
callbackMap.set(this, {
importModuleDynamically:
@@ -409,6 +409,10 @@ module.exports = {
};
if (require('internal/options').getOptionValue('--experimental-vm-modules')) {
const { SourceTextModule } = require('internal/vm/source_text_module');
const {
Module, SourceTextModule, SyntheticModule,
} = require('internal/vm/module');
module.exports.Module = Module;
module.exports.SourceTextModule = SourceTextModule;
module.exports.SyntheticModule = SyntheticModule;
}
+1 -1
View File
@@ -198,7 +198,7 @@
'lib/internal/v8_prof_processor.js',
'lib/internal/validators.js',
'lib/internal/stream_base_commons.js',
'lib/internal/vm/source_text_module.js',
'lib/internal/vm/module.js',
'lib/internal/worker.js',
'lib/internal/worker/io.js',
'lib/internal/streams/lazy_transform.js',
+47 -59
View File
@@ -98,88 +98,77 @@ ModuleWrap* ModuleWrap::GetFromID(Environment* env, uint32_t id) {
return module_wrap_it->second;
}
// new ModuleWrap(source, url)
// new ModuleWrap(source, url, context?, lineOffset, columnOffset)
// new ModuleWrap(syntheticExecutionFunction, export_names, url)
// new ModuleWrap(url, context, source, lineOffset, columnOffset)
// new ModuleWrap(url, context, exportNames, syntheticExecutionFunction)
void ModuleWrap::New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
CHECK_GE(args.Length(), 3);
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();
CHECK(args.IsConstructCall());
Local<Object> that = args.This();
const int argc = args.Length();
CHECK_GE(argc, 2);
CHECK(args[0]->IsString());
Local<String> url = args[0].As<String>();
Local<Context> context;
if (args[1]->IsUndefined()) {
context = that->CreationContext();
} else {
CHECK(args[1]->IsObject());
ContextifyContext* sandbox =
ContextifyContext::ContextFromContextifiedSandbox(
env, args[1].As<Object>());
CHECK_NOT_NULL(sandbox);
context = sandbox->context();
}
Local<Integer> line_offset;
Local<Integer> column_offset;
if (argc == 5) {
// new ModuleWrap(source, url, context?, lineOffset, columnOffset)
if (args[2]->IsUndefined()) {
context = that->CreationContext();
} else {
CHECK(args[2]->IsObject());
ContextifyContext* sandbox =
ContextifyContext::ContextFromContextifiedSandbox(
env, args[2].As<Object>());
CHECK_NOT_NULL(sandbox);
context = sandbox->context();
}
bool synthetic = args[2]->IsArray();
if (synthetic) {
// new ModuleWrap(url, context, exportNames, syntheticExecutionFunction)
CHECK(args[3]->IsFunction());
} else {
// new ModuleWrap(url, context, source, lineOffset, columOffset)
CHECK(args[2]->IsString());
CHECK(args[3]->IsNumber());
line_offset = args[3].As<Integer>();
CHECK(args[4]->IsNumber());
column_offset = args[4].As<Integer>();
} else {
// new ModuleWrap(source, url)
context = that->CreationContext();
line_offset = Integer::New(isolate, 0);
column_offset = Integer::New(isolate, 0);
}
Local<String> url;
Local<Module> module;
Local<PrimitiveArray> host_defined_options =
PrimitiveArray::New(isolate, HostDefinedOptions::kLength);
host_defined_options->Set(isolate, HostDefinedOptions::kType,
Number::New(isolate, ScriptType::kModule));
// new ModuleWrap(syntheticExecutionFunction, export_names, url)
bool synthetic = args[0]->IsFunction();
if (synthetic) {
CHECK(args[1]->IsArray());
Local<Array> export_names_arr = args[1].As<Array>();
ShouldNotAbortOnUncaughtScope no_abort_scope(env);
TryCatchScope try_catch(env);
uint32_t len = export_names_arr->Length();
std::vector<Local<String>> export_names(len);
for (uint32_t i = 0; i < len; i++) {
Local<Value> export_name_val =
export_names_arr->Get(context, i).ToLocalChecked();
CHECK(export_name_val->IsString());
export_names[i] = export_name_val.As<String>();
}
Local<Module> module;
CHECK(args[2]->IsString());
url = args[2].As<String>();
{
Context::Scope context_scope(context);
if (synthetic) {
CHECK(args[2]->IsArray());
Local<Array> export_names_arr = args[2].As<Array>();
module = Module::CreateSyntheticModule(isolate, url, export_names,
uint32_t len = export_names_arr->Length();
std::vector<Local<String>> export_names(len);
for (uint32_t i = 0; i < len; i++) {
Local<Value> export_name_val =
export_names_arr->Get(context, i).ToLocalChecked();
CHECK(export_name_val->IsString());
export_names[i] = export_name_val.As<String>();
}
module = Module::CreateSyntheticModule(isolate, url, export_names,
SyntheticModuleEvaluationStepsCallback);
// Compile
} else {
CHECK(args[0]->IsString());
Local<String> source_text = args[0].As<String>();
CHECK(args[1]->IsString());
url = args[1].As<String>();
ShouldNotAbortOnUncaughtScope no_abort_scope(env);
TryCatchScope try_catch(env);
{
} else {
Local<String> source_text = args[2].As<String>();
ScriptOrigin origin(url,
line_offset, // line offset
column_offset, // column offset
@@ -190,7 +179,6 @@ void ModuleWrap::New(const FunctionCallbackInfo<Value>& args) {
False(isolate), // is WASM
True(isolate), // is ES Module
host_defined_options);
Context::Scope context_scope(context);
ScriptCompiler::Source source(source_text, origin);
if (!ScriptCompiler::CompileModule(isolate, &source).ToLocal(&module)) {
if (try_catch.HasCaught() && !try_catch.HasTerminated()) {
@@ -214,7 +202,7 @@ void ModuleWrap::New(const FunctionCallbackInfo<Value>& args) {
if (synthetic) {
obj->synthetic_ = true;
obj->synthetic_evaluation_steps_.Reset(
env->isolate(), args[0].As<Function>());
env->isolate(), args[3].As<Function>());
}
obj->context_.Reset(isolate, context);
@@ -1413,7 +1401,7 @@ MaybeLocal<Value> ModuleWrap::SyntheticModuleEvaluationStepsCallback(
try_catch.ReThrow();
return MaybeLocal<Value>();
}
return Undefined(isolate);
return ret;
}
void ModuleWrap::SetSyntheticExport(
+2 -2
View File
@@ -10,8 +10,8 @@ const { ModuleWrap } = internalBinding('module_wrap');
const { getPromiseDetails, isPromise } = internalBinding('util');
const setTimeoutAsync = require('util').promisify(setTimeout);
const foo = new ModuleWrap('export * from "bar"; 6;', 'foo');
const bar = new ModuleWrap('export const five = 5', 'bar');
const foo = new ModuleWrap('foo', undefined, 'export * from "bar"; 6;', 0, 0);
const bar = new ModuleWrap('bar', undefined, 'export const five = 5', 0, 0);
(async () => {
const promises = foo.link(() => setTimeoutAsync(1000).then(() => bar));
+21 -7
View File
@@ -4,7 +4,7 @@
const common = require('../common');
const assert = require('assert');
const { SourceTextModule, createContext } = require('vm');
const { SourceTextModule, SyntheticModule, createContext } = require('vm');
const util = require('util');
(async function test1() {
@@ -75,15 +75,29 @@ const util = require('util');
context: { foo: 'bar' }
}`
);
assert.strictEqual(util.inspect(m, { depth: -1 }), '[SourceTextModule]');
assert.strictEqual(
m[util.inspect.custom].call(Object.create(null)),
`SourceTextModule {
status: undefined,
identifier: undefined,
context: undefined
}`,
'Module { status: undefined, identifier: undefined, context: undefined }',
);
assert.strictEqual(util.inspect(m, { depth: -1 }), '[SourceTextModule]');
}
{
const context = createContext({ foo: 'bar' });
const m = new SyntheticModule([], () => {}, { context });
assert.strictEqual(
util.inspect(m),
`SyntheticModule {
status: 'unlinked',
identifier: 'vm:module(0)',
context: { foo: 'bar' }
}`
);
assert.strictEqual(util.inspect(m, { depth: -1 }), '[SyntheticModule]');
}
// Check dependencies getter returns same object every time
+1 -1
View File
@@ -64,7 +64,7 @@ async function checkModuleState() {
assert.strictEqual(m.status, 'linking');
await m.link(common.mustNotCall());
}, {
code: 'ERR_VM_MODULE_ALREADY_LINKED'
code: 'ERR_VM_MODULE_STATUS'
});
await assert.rejects(async () => {
+60
View File
@@ -0,0 +1,60 @@
'use strict';
// Flags: --experimental-vm-modules
require('../common');
const { SyntheticModule, SourceTextModule } = require('vm');
const assert = require('assert');
(async () => {
{
const s = new SyntheticModule(['x'], () => {
s.setExport('x', 1);
});
const m = new SourceTextModule(`
import { x } from 'synthetic';
export const getX = () => x;
`);
await m.link(() => s);
await m.evaluate();
assert.strictEqual(m.namespace.getX(), 1);
s.setExport('x', 42);
assert.strictEqual(m.namespace.getX(), 42);
}
for (const invalidName of [1, Symbol.iterator, {}, [], null, true, 0]) {
const s = new SyntheticModule([], () => {});
await s.link(() => {});
assert.throws(() => {
s.setExport(invalidName, undefined);
}, {
name: 'TypeError',
});
}
// https://bugs.chromium.org/p/v8/issues/detail?id=9828
/*
{
const s = new SyntheticModule([], () => {});
await s.link(() => {});
assert.throws(() => {
s.setExport('does not exist');
}, {
name: 'ReferenceError',
});
}
*/
{
const s = new SyntheticModule([], () => {});
assert.throws(() => {
s.setExport('name', 'value');
}, {
code: 'ERR_VM_MODULE_STATUS',
});
}
})();
+1
View File
@@ -141,6 +141,7 @@ const customTypesMap = {
'URL': 'url.html#url_the_whatwg_url_api',
'URLSearchParams': 'url.html#url_class_urlsearchparams',
'vm.Module': 'vm.html#vm_class_vm_module',
'vm.SourceTextModule': 'vm.html#vm_class_vm_sourcetextmodule',
'MessagePort': 'worker_threads.html#worker_threads_class_messageport',