diff --git a/.eslintrc.js b/.eslintrc.js index 4863bbd998..eb2daca5cb 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -38,6 +38,8 @@ module.exports = { { files: [ 'doc/api/esm.md', + 'test/es-module/test-esm-type-flag.js', + 'test/es-module/test-esm-type-flag-alias.js', '*.mjs', 'test/es-module/test-esm-example-loader.js', ], diff --git a/doc/api/cli.md b/doc/api/cli.md index cf28d9b2bf..ce59fdfed0 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -131,9 +131,43 @@ conjunction with native stack and other runtime environment data. added: v6.0.0 --> +### `--entry-type=type` + + +Used with `--experimental-modules`, this configures Node.js to interpret the +initial entry point as CommonJS or as an ES module. + +Valid values are `"commonjs"` and `"module"`. The default is to infer from +the file extension and the `"type"` field in the nearest parent `package.json`. + +Works for executing a file as well as `--eval`, `--print`, `STDIN`. + Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with `./configure --openssl-fips`.) +### `--es-module-specifier-resolution=mode` + + +To be used in conjunction with `--experimental-modules`. Sets the resolution +algorithm for resolving specifiers. Valid options are `explicit` and `node`. + +The default is `explicit`, which requires providing the full path to a +module. The `node` mode will enable support for optional file extensions and +the ability to import a directory that has an index file. + +Please see [customizing esm specifier resolution][] for example usage. + +### `--experimental-json-modules` + + +Enable experimental JSON support for the ES Module loader. + ### `--experimental-modules` + +Type: Runtime + +The previously undocumented `timers.active()` is deprecated. +Please use the publicly documented [`timeout.refresh()`][] instead. +If re-referencing the timeout is necessary, [`timeout.ref()`][] can be used +with no performance impact since Node.js 10. + + +### DEP0127: timers._unrefActive() + + +Type: Runtime + +The previously undocumented and "private" `timers._unrefActive()` is deprecated. +Please use the publicly documented [`timeout.refresh()`][] instead. +If unreferencing the timeout is necessary, [`timeout.unref()`][] can be used +with no performance impact since Node.js 10. + [`--pending-deprecation`]: cli.html#cli_pending_deprecation [`Buffer.allocUnsafeSlow(size)`]: buffer.html#buffer_class_method_buffer_allocunsafeslow_size [`Buffer.from(array)`]: buffer.html#buffer_class_method_buffer_from_array @@ -2423,6 +2455,9 @@ The `_stream_wrap` module is deprecated. [`script.createCachedData()`]: vm.html#vm_script_createcacheddata [`setInterval()`]: timers.html#timers_setinterval_callback_delay_args [`setTimeout()`]: timers.html#timers_settimeout_callback_delay_args +[`timeout.ref()`]: timers.html#timers_timeout_ref +[`timeout.refresh()`]: timers.html#timers_timeout_refresh +[`timeout.unref()`]: timers.html#timers_timeout_unref [`tls.CryptoStream`]: tls.html#tls_class_cryptostream [`tls.SecureContext`]: tls.html#tls_tls_createsecurecontext_options [`tls.SecurePair`]: tls.html#tls_class_securepair diff --git a/doc/api/errors.md b/doc/api/errors.md index 716dcdaf32..87051a911c 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -1267,6 +1267,11 @@ An invalid or unexpected value was passed in an options object. An invalid or unknown file encoding was passed. + +### ERR_INVALID_PACKAGE_CONFIG + +An invalid `package.json` file was found which failed parsing. + ### ERR_INVALID_PERFORMANCE_MARK @@ -1440,7 +1445,7 @@ strict compliance with the API specification (which in some cases may accept > Stability: 1 - Experimental -An [ES6 module][] loader hook specified `format: 'dynamic'` but did not provide +An [ES Module][] loader hook specified `format: 'dynamic'` but did not provide a `dynamicInstantiate` hook. @@ -1449,13 +1454,6 @@ a `dynamicInstantiate` hook. A `MessagePort` was found in the object passed to a `postMessage()` call, but not provided in the `transferList` for that call. - -### ERR_MISSING_MODULE - -> Stability: 1 - Experimental - -An [ES6 module][] could not be resolved. - ### ERR_MISSING_PLATFORM_FOR_WORKER @@ -1463,12 +1461,12 @@ The V8 platform used by this instance of Node.js does not support creating Workers. This is caused by lack of embedder support for Workers. In particular, this error will not occur with standard builds of Node.js. - -### ERR_MODULE_RESOLUTION_LEGACY + +### ERR_MODULE_NOT_FOUND > Stability: 1 - Experimental -A failure occurred resolving imports in an [ES6 module][]. +An [ES Module][] could not be resolved. ### ERR_MULTIPLE_CALLBACK @@ -1555,7 +1553,7 @@ A given value is out of the accepted range. > Stability: 1 - Experimental -An attempt was made to `require()` an [ES6 module][]. +An attempt was made to `require()` an [ES Module][]. ### ERR_SCRIPT_EXECUTION_INTERRUPTED @@ -2220,10 +2218,24 @@ A non-specific HTTP/2 error has occurred. Used in the `repl` in case the old history file is used and an error occurred while trying to read and parse it. + +#### ERR_INVALID_REPL_TYPE + +> Stability: 1 - Experimental + +The `--entry-type=...` flag is not compatible with the Node.js REPL. + + +#### ERR_INVALID_TYPE_FLAG + +> Stability: 1 - Experimental + +An invalid `--entry-type=...` flag value was provided. + #### ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK -Used when an [ES6 module][] loader hook specifies `format: 'dynamic'` but does +Used when an [ES Module][] loader hook specifies `format: 'dynamic'` but does not provide a `dynamicInstantiate` hook. @@ -2250,6 +2262,17 @@ size. This `Error` is thrown when a read is attempted on a TTY `WriteStream`, such as `process.stdout.on('data')`. + +#### ERR_TYPE_MISMATCH + +> Stability: 1 - Experimental + +The `--entry-type=commonjs` flag was used to attempt to execute an `.mjs` file +or a `.js` file where the nearest parent `package.json` contains +`"type": "module"`; or +the `--entry-type=module` flag was used to attempt to execute a `.cjs` file or +a `.js` file where the nearest parent `package.json` either lacks a `"type"` +field or contains `"type": "commonjs"`. [`'uncaughtException'`]: process.html#process_event_uncaughtexception [`--force-fips`]: cli.html#cli_force_fips @@ -2293,7 +2316,7 @@ such as `process.stdout.on('data')`. [`subprocess.kill()`]: child_process.html#child_process_subprocess_kill_signal [`subprocess.send()`]: child_process.html#child_process_subprocess_send_message_sendhandle_options_callback [`zlib`]: zlib.html -[ES6 module]: esm.html +[ES Module]: esm.html [ICU]: intl.html#intl_internationalization_support [Node.js Error Codes]: #nodejs-error-codes [V8's stack trace API]: https://github.com/v8/v8/wiki/Stack-Trace-API diff --git a/doc/api/esm.md b/doc/api/esm.md index e81a69c6ed..00eb327523 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -5,39 +5,233 @@ > Stability: 1 - Experimental +## Introduction + +ECMAScript modules are [the official standard format][] to package JavaScript +code for reuse. Modules are defined using a variety of [`import`][] and +[`export`][] statements. + +Node.js fully supports ECMAScript modules as they are currently specified and +provides limited interoperability between them and the existing module format, +[CommonJS][]. + Node.js contains support for ES Modules based upon the -[Node.js EP for ES Modules][]. +[Node.js EP for ES Modules][] and the [ECMAScript-modules implementation][]. -Not all features of the EP are complete and will be landing as both VM support -and implementation is ready. Error messages are still being polished. +Expect major changes in the implementation including interoperability support, +specifier resolution, and default behavior. ## Enabling -The `--experimental-modules` flag can be used to enable features for loading -ESM modules. +The `--experimental-modules` flag can be used to enable support for +ECMAScript modules (ES modules). + +## Running Node.js with an ECMAScript Module -Once this has been set, files ending with `.mjs` will be able to be loaded -as ES Modules. +There are a few ways to start Node.js with an ES module as its input. + +### Initial entry point with an .mjs extension + +A file ending with `.mjs` passed to Node.js as an initial entry point will be +loaded as an ES module. ```sh node --experimental-modules my-app.mjs ``` -## Features +### --entry-type=module flag - +Files ending with `.js` or `.mjs`, or lacking any extension, +will be loaded as ES modules when the `--entry-type=module` flag is set. + +```sh +node --experimental-modules --entry-type=module my-app.js +``` + +For completeness there is also `--entry-type=commonjs`, for explicitly running +a `.js` file as CommonJS. This is the default behavior if `--entry-type` is +unspecified. + +The `--entry-type=module` flag can also be used to configure Node.js to treat +as an ES module input sent in via `--eval` or `--print` (or `-e` or `-p`) or +piped to Node.js via `STDIN`. + +```sh +node --experimental-modules --entry-type=module --eval \ + "import { sep } from 'path'; console.log(sep);" + +echo "import { sep } from 'path'; console.log(sep);" | \ + node --experimental-modules --entry-type=module +``` + +### package.json "type" field + +Files ending with `.js` or `.mjs`, or lacking any extension, +will be loaded as ES modules when the nearest parent `package.json` file +contains a top-level field `"type"` with a value of `"module"`. + +The nearest parent `package.json` is defined as the first `package.json` found +when searching in the current folder, that folder’s parent, and so on up +until the root of the volume is reached. + + +```js +// package.json +{ + "type": "module" +} +``` + +```sh +# In same folder as above package.json +node --experimental-modules my-app.js # Runs as ES module +``` + +If the nearest parent `package.json` lacks a `"type"` field, or contains +`"type": "commonjs"`, extensionless and `.js` files are treated as CommonJS. +If the volume root is reached and no `package.json` is found, +Node.js defers to the default, a `package.json` with no `"type"` +field. + +## Package Scope and File Extensions + +A folder containing a `package.json` file, and all subfolders below that +folder down until the next folder containing another `package.json`, is +considered a _package scope_. The `"type"` field defines how `.js` and +extensionless files should be treated within a particular `package.json` file’s +package scope. Every package in a project’s `node_modules` folder contains its +own `package.json` file, so each project’s dependencies have their own package +scopes. A `package.json` lacking a `"type"` field is treated as if it contained +`"type": "commonjs"`. + +The package scope applies not only to initial entry points (`node +--experimental-modules my-app.js`) but also to files referenced by `import` +statements and `import()` expressions. + +```js +// my-app.js, in an ES module package scope because there is a package.json +// file in the same folder with "type": "module" + +import './startup/init.js'; +// Loaded as ES module since ./startup contains no package.json file, +// and therefore inherits the ES module package scope from one level up + +import 'commonjs-package'; +// Loaded as CommonJS since ./node_modules/commonjs-package/package.json +// lacks a "type" field or contains "type": "commonjs" + +import './node_modules/commonjs-package/index.js'; +// Loaded as CommonJS since ./node_modules/commonjs-package/package.json +// lacks a "type" field or contains "type": "commonjs" +``` + +Files ending with `.mjs` are always loaded as ES modules regardless of package +scope. + +Files ending with `.cjs` are always loaded as CommonJS regardless of package +scope. + +```js +import './legacy-file.cjs'; +// Loaded as CommonJS since .cjs is always loaded as CommonJS + +import 'commonjs-package/src/index.mjs'; +// Loaded as ES module since .mjs is always loaded as ES module +``` + +The `.mjs` and `.cjs` extensions may be used to mix types within the same +package scope: + +- Within a `"type": "module"` package scope, Node.js can be instructed to + interpret a particular file as CommonJS by naming it with a `.cjs` extension + (since both `.js` and `.mjs` files are treated as ES modules within a + `"module"` package scope). + +- Within a `"type": "commonjs"` package scope, Node.js can be instructed to + interpret a particular file as an ES module by naming it with an `.mjs` + extension (since both `.js` and `.cjs` files are treated as CommonJS within a + `"commonjs"` package scope). + +## Package Entry Points + +The `package.json` `"main"` field defines the entry point for a package, +whether the package is included into CommonJS via `require` or into an ES +module via `import`. + + +```js +// ./node_modules/es-module-package/package.json +{ + "type": "module", + "main": "./src/index.js" +} +``` +```js +// ./my-app.mjs + +import { something } from 'es-module-package'; +// Loads from ./node_modules/es-module-package/src/index.js +``` + +An attempt to `require` the above `es-module-package` would attempt to load +`./node_modules/es-module-package/src/index.js` as CommonJS, which would throw +an error as Node.js would not be able to parse the `export` statement in +CommonJS. + +As with `import` statements, for ES module usage the value of `"main"` must be +a full path including extension: `"./index.mjs"`, not `"./index"`. + +If the `package.json` `"type"` field is omitted, a `.js` file in `"main"` will +be interpreted as CommonJS. + +> Currently a package can define _either_ a CommonJS entry point **or** an ES +> module entry point; there is no way to specify separate entry points for +> CommonJS and ES module usage. This means that a package entry point can be +> included via `require` or via `import` but not both. +> +> Such a limitation makes it difficult for packages to support both new versions +> of Node.js that understand ES modules and older versions of Node.js that +> understand only CommonJS. There is work ongoing to remove this limitation, and +> it will very likely entail changes to the behavior of `"main"` as defined +> here. + +## import Specifiers + +### Terminology + +The _specifier_ of an `import` statement is the string after the `from` keyword, +e.g. `'path'` in `import { sep } from 'path'`. Specifiers are also used in +`export from` statements, and as the argument to an `import()` expression. + +There are four types of specifiers: + +- _Bare specifiers_ like `'some-package'`. They refer to an entry point of a + package by the package name. + +- _Deep import specifiers_ like `'some-package/lib/shuffle.mjs'`. They refer to + a path within a package prefixed by the package name. + +- _Relative specifiers_ like `'./startup.js'` or `'../config.mjs'`. They refer + to a path relative to the location of the importing file. + +- _Absolute specifiers_ like `'file:///opt/nodejs/config.js'`. They refer + directly and explicitly to a full path. + +Bare specifiers, and the bare specifier portion of deep import specifiers, are +strings; but everything else in a specifier is a URL. -### Supported +Only `file://` URLs are supported. A specifier like +`'https://example.com/app.js'` may be supported by browsers but it is not +supported in Node.js. -Only the CLI argument for the main entry point to the program can be an entry -point into an ESM graph. Dynamic import can also be used to create entry points -into ESM graphs at runtime. +Specifiers may not begin with `/` or `//`. These are reserved for potential +future use. The root of the current volume may be referenced via `file:///`. -#### import.meta +## import.meta * {Object} @@ -46,63 +240,128 @@ property: * `url` {string} The absolute `file:` URL of the module. -### Unsupported +## Differences Between ES Modules and CommonJS -| Feature | Reason | -| --- | --- | -| `require('./foo.mjs')` | ES Modules have differing resolution and timing, use dynamic import | +### Mandatory file extensions + +A file extension must be provided when using the `import` keyword. Directory +indexes (e.g. `'./startup/index.js'`) must also be fully specified. -## Notable differences between `import` and `require` +This behavior matches how `import` behaves in browser environments, assuming a +typically configured server. -### No NODE_PATH +### No NODE_PATH `NODE_PATH` is not part of resolving `import` specifiers. Please use symlinks if this behavior is desired. -### No `require.extensions` +### No require, exports, module.exports, \_\_filename, \_\_dirname + +These CommonJS variables are not available in ES modules. + +`require` can be imported into an ES module using +[`module.createRequireFromPath()`][]. + +An equivalent for `__filename` and `__dirname` is [`import.meta.url`][]. + +### No require.extensions `require.extensions` is not used by `import`. The expectation is that loader hooks can provide this workflow in the future. -### No `require.cache` +### No require.cache `require.cache` is not used by `import`. It has a separate cache. -### URL based paths +### URL-based paths -ESM are resolved and cached based upon [URL](https://url.spec.whatwg.org/) -semantics. This means that files containing special characters such as `#` and -`?` need to be escaped. +ES modules are resolved and cached based upon +[URL](https://url.spec.whatwg.org/) semantics. This means that files containing +special characters such as `#` and `?` need to be escaped. Modules will be loaded multiple times if the `import` specifier used to resolve them have a different query or fragment. ```js -import './foo?query=1'; // loads ./foo with query of "?query=1" -import './foo?query=2'; // loads ./foo with query of "?query=2" +import './foo.mjs?query=1'; // loads ./foo.mjs with query of "?query=1" +import './foo.mjs?query=2'; // loads ./foo.mjs with query of "?query=2" ``` For now, only modules using the `file:` protocol can be loaded. -## Interop with existing modules +## Interoperability with CommonJS + +### require -All CommonJS, JSON, and C++ modules can be used with `import`. +`require` always treats the files it references as CommonJS. This applies +whether `require` is used the traditional way within a CommonJS environment, or +in an ES module environment using [`module.createRequireFromPath()`][]. -Modules loaded this way will only be loaded once, even if their query -or fragment string differs between `import` statements. +To include an ES module into CommonJS, use [`import()`][]. -When loaded via `import` these modules will provide a single `default` export -representing the value of `module.exports` at the time they finished evaluating. +### import statements + +An `import` statement can reference either ES module or CommonJS JavaScript. +Other file types such as JSON and Native modules are not supported. For those, +use [`module.createRequireFromPath()`][]. + +`import` statements are permitted only in ES modules. For similar functionality +in CommonJS, see [`import()`][]. + +The _specifier_ of an `import` statement (the string after the `from` keyword) +can either be an URL-style relative path like `'./file.mjs'` or a package name +like `'fs'`. + +Like in CommonJS, files within packages can be accessed by appending a path to +the package name. ```js -// foo.js -module.exports = { one: 1 }; +import { sin, cos } from 'geometry/trigonometry-functions.mjs'; +``` + +> Currently only the “default export” is supported for CommonJS files or +> packages: +> +> +> ```js +> import packageMain from 'commonjs-package'; // Works +> +> import { method } from 'commonjs-package'; // Errors +> ``` +> +> There are ongoing efforts to make the latter code possible. -// bar.mjs -import foo from './foo.js'; -foo.one === 1; // true +### import() expressions + +Dynamic `import()` is supported in both CommonJS and ES modules. It can be used +to include ES module files from CommonJS code. + +```js +(async () => { + await import('./my-app.mjs'); +})(); ``` +## CommonJS, JSON, and Native Modules + +CommonJS, JSON, and Native modules can be used with [`module.createRequireFromPath()`][]. + +```js +// cjs.js +module.exports = 'cjs'; + +// esm.mjs +import { createRequireFromPath as createRequire } from 'module'; +import { fileURLToPath as fromURL } from 'url'; + +const require = createRequire(fromURL(import.meta.url)); + +const cjs = require('./cjs'); +cjs === 'cjs'; // true +``` + +## Builtin modules + Builtin modules will provide named exports of their public API, as well as a default export which can be used for, among other things, modifying the named exports. Named exports of builtin modules are updated when the corresponding @@ -132,7 +391,42 @@ fs.readFileSync = () => Buffer.from('Hello, ESM'); fs.readFileSync === readFileSync; ``` -## Loader hooks +## Experimental JSON Modules + +**Note: This API is still being designed and is subject to change.**. + +Currently importing JSON modules are only supported in the `commonjs` mode +and are loaded using the CJS loader. [WHATWG JSON modules][] are currently +being standardized, and are experimentally supported by including the +additional flag `--experimental-json-modules` when running Node.js. + +When the `--experimental-json-modules` flag is included both the +`commonjs` and `module` mode will use the new experimental JSON +loader. The imported JSON only exposes a `default`, there is no +support for named exports. A cache entry is created in the CommonJS +cache, to avoid duplication. The same object will be returned in +CommonJS if the JSON module has already been imported from the +same path. + +Assuming an `index.js` with + + +```js +import packageConfig from './package.json'; +``` + +The `--experimental-json-modules` flag is needed for the module +to work. + + +```bash +node --experimental-modules --entry-type=module index.js # fails +node --experimental-modules --entry-type=module --experimental-json-modules index.js # works +``` + +## Experimental Loader hooks + +**Note: This API is currently being redesigned and will still change.**. @@ -173,11 +467,10 @@ module. This can be one of the following: | `format` | Description | | --- | --- | -| `'esm'` | Load a standard JavaScript module | -| `'cjs'` | Load a node-style CommonJS module | -| `'builtin'` | Load a node builtin CommonJS module | +| `'module'` | Load a standard JavaScript module | +| `'commonjs'` | Load a Node.js CommonJS module | +| `'builtin'` | Load a Node.js builtin module | | `'json'` | Load a JSON file | -| `'addon'` | Load a [C++ Addon][addons] | | `'dynamic'` | Use a [dynamic instantiate hook][] | For example, a dummy loader to load JavaScript restricted to browser resolution @@ -253,6 +546,184 @@ With the list of module exports provided upfront, the `execute` function will then be called at the exact point of module evaluation order for that module in the import tree. +## Resolution Algorithm + +### Features + +The resolver has the following properties: + +* FileURL-based resolution as is used by ES modules +* Support for builtin module loading +* Relative and absolute URL resolution +* No default extensions +* No folder mains +* Bare specifier package resolution lookup through node_modules + +### Resolver Algorithm + +The algorithm to load an ES module specifier is given through the +**ESM_RESOLVE** method below. It returns the resolved URL for a +module specifier relative to a parentURL, in addition to the unique module +format for that resolved URL given by the **ESM_FORMAT** routine. + +The _"module"_ format is returned for an ECMAScript Module, while the +_"commonjs"_ format is used to indicate loading through the legacy +CommonJS loader. Additional formats such as _"wasm"_ or _"addon"_ can be +extended in future updates. + +In the following algorithms, all subroutine errors are propogated as errors +of these top-level routines. + +_isMain_ is **true** when resolving the Node.js application entry point. + +When using the `--entry-type` flag, it overrides the ESM_FORMAT result while +providing errors in the case of explicit conflicts. + +
+Resolver algorithm specification + +**ESM_RESOLVE(_specifier_, _parentURL_, _isMain_)** +> 1. Let _resolvedURL_ be **undefined**. +> 1. If _specifier_ is a valid URL, then +> 1. Set _resolvedURL_ to the result of parsing and reserializing +> _specifier_ as a URL. +> 1. Otherwise, if _specifier_ starts with _"/"_, then +> 1. Throw an _Invalid Specifier_ error. +> 1. Otherwise, if _specifier_ starts with _"./"_ or _"../"_, then +> 1. Set _resolvedURL_ to the URL resolution of _specifier_ relative to +> _parentURL_. +> 1. Otherwise, +> 1. Note: _specifier_ is now a bare specifier. +> 1. Set _resolvedURL_ the result of +> **PACKAGE_RESOLVE**(_specifier_, _parentURL_). +> 1. If the file at _resolvedURL_ does not exist, then +> 1. Throw a _Module Not Found_ error. +> 1. Set _resolvedURL_ to the real path of _resolvedURL_. +> 1. Let _format_ be the result of **ESM_FORMAT**(_resolvedURL_, _isMain_). +> 1. Load _resolvedURL_ as module format, _format_. + +PACKAGE_RESOLVE(_packageSpecifier_, _parentURL_) +> 1. Let _packageName_ be *undefined*. +> 1. Let _packageSubpath_ be *undefined*. +> 1. If _packageSpecifier_ is an empty string, then +> 1. Throw an _Invalid Specifier_ error. +> 1. If _packageSpecifier_ does not start with _"@"_, then +> 1. Set _packageName_ to the substring of _packageSpecifier_ until the +> first _"/"_ separator or the end of the string. +> 1. Otherwise, +> 1. If _packageSpecifier_ does not contain a _"/"_ separator, then +> 1. Throw an _Invalid Specifier_ error. +> 1. Set _packageName_ to the substring of _packageSpecifier_ +> until the second _"/"_ separator or the end of the string. +> 1. Let _packageSubpath_ be the substring of _packageSpecifier_ from the +> position at the length of _packageName_ plus one, if any. +> 1. Assert: _packageName_ is a valid package name or scoped package name. +> 1. Assert: _packageSubpath_ is either empty, or a path without a leading +> separator. +> 1. If _packageSubpath_ contains any _"."_ or _".."_ segments or percent +> encoded strings for _"/"_ or _"\"_ then, +> 1. Throw an _Invalid Specifier_ error. +> 1. If _packageSubpath_ is empty and _packageName_ is a Node.js builtin +> module, then +> 1. Return the string _"node:"_ concatenated with _packageSpecifier_. +> 1. While _parentURL_ is not the file system root, +> 1. Set _parentURL_ to the parent folder URL of _parentURL_. +> 1. Let _packageURL_ be the URL resolution of the string concatenation of +> _parentURL_, _"/node_modules/"_ and _packageSpecifier_. +> 1. If the folder at _packageURL_ does not exist, then +> 1. Set _parentURL_ to the parent URL path of _parentURL_. +> 1. Continue the next loop iteration. +> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). +> 1. If _packageSubpath_ is empty, then +> 1. Return the result of **PACKAGE_MAIN_RESOLVE**(_packageURL_, +> _pjson_). +> 1. Otherwise, +> 1. Return the URL resolution of _packageSubpath_ in _packageURL_. +> 1. Throw a _Module Not Found_ error. + +PACKAGE_MAIN_RESOLVE(_packageURL_, _pjson_) +> 1. If _pjson_ is **null**, then +> 1. Throw a _Module Not Found_ error. +> 1. If _pjson.main_ is a String, then +> 1. Let _resolvedMain_ be the concatenation of _packageURL_, "/", and +> _pjson.main_. +> 1. If the file at _resolvedMain_ exists, then +> 1. Return _resolvedMain_. +> 1. If _pjson.type_ is equal to _"module"_, then +> 1. Throw a _Module Not Found_ error. +> 1. Let _legacyMainURL_ be the result applying the legacy +> **LOAD_AS_DIRECTORY** CommonJS resolver to _packageURL_, throwing a +> _Module Not Found_ error for no resolution. +> 1. If _legacyMainURL_ does not end in _".js"_ then, +> 1. Throw an _Unsupported File Extension_ error. +> 1. Return _legacyMainURL_. + +**ESM_FORMAT(_url_, _isMain_)** +> 1. Assert: _url_ corresponds to an existing file. +> 1. Let _pjson_ be the result of **READ_PACKAGE_SCOPE**(_url_). +> 1. If _url_ ends in _".mjs"_, then +> 1. Return _"module"_. +> 1. If _url_ ends in _".cjs"_, then +> 1. Return _"commonjs"_. +> 1. If _pjson?.type_ exists and is _"module"_, then +> 1. If _isMain_ is **true** or _url_ ends in _".js"_, then +> 1. Return _"module"_. +> 1. Throw an _Unsupported File Extension_ error. +> 1. Otherwise, +> 1. If _isMain_ is **true** or _url_ ends in _".js"_, _".json"_ or +> _".node"_, then +> 1. Return _"commonjs"_. +> 1. Throw an _Unsupported File Extension_ error. + +READ_PACKAGE_SCOPE(_url_) +> 1. Let _scopeURL_ be _url_. +> 1. While _scopeURL_ is not the file system root, +> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_scopeURL_). +> 1. If _pjson_ is not **null**, then +> 1. Return _pjson_. +> 1. Set _scopeURL_ to the parent URL of _scopeURL_. +> 1. Return **null**. + +READ_PACKAGE_JSON(_packageURL_) +> 1. Let _pjsonURL_ be the resolution of _"package.json"_ within _packageURL_. +> 1. If the file at _pjsonURL_ does not exist, then +> 1. Return **null**. +> 1. If the file at _packageURL_ does not parse as valid JSON, then +> 1. Throw an _Invalid Package Configuration_ error. +> 1. Return the parsed JSON source of the file at _pjsonURL_. + +
+ +### Customizing ESM specifier resolution algorithm + +The current specifier resolution does not support all default behavior of +the CommonJS loader. One of the behavior differences is automatic resolution +of file extensions and the ability to import directories that have an index +file. + +The `--es-module-specifier-resolution=[mode]` flag can be used to customize +the extension resolution algorithm. The default mode is `explicit`, which +requires the full path to a module be provided to the loader. To enable the +automatic extension resolution and importing from directories that include an +index file use the `node` mode. + +```bash +$ node --experimental-modules index.mjs +success! +$ node --experimental-modules index #Failure! +Error: Cannot find module +$ node --experimental-modules --es-module-specifier-resolution=node index +success! +``` + +[`export`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export +[`import`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import +[`import()`]: #esm_import-expressions +[`import.meta.url`]: #esm_import_meta +[`module.createRequireFromPath()`]: modules.html#modules_module_createrequirefrompath_filename +[CommonJS]: modules.html +[ECMAScript-modules implementation]: https://github.com/nodejs/modules/blob/master/doc/plan-for-new-modules-implementation.md [Node.js EP for ES Modules]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md -[addons]: addons.html +[WHATWG JSON modules]: https://github.com/whatwg/html/issues/4315 [dynamic instantiate hook]: #esm_dynamic_instantiate_hook +[the official standard format]: https://tc39.github.io/ecma262/#sec-modules diff --git a/doc/node.1 b/doc/node.1 index 7bcb1edc59..2b742c4e3a 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -119,6 +119,9 @@ Enable FIPS-compliant crypto at startup. Requires Node.js to be built with .Sy ./configure --openssl-fips . . +.It Fl -entry-type Ns = Ns Ar type +Set the top-level module resolution type. +. .It Fl -experimental-modules Enable experimental ES module support and caching modules. . diff --git a/lib/.eslintrc.yaml b/lib/.eslintrc.yaml index fcb9ea7feb..3b041d5db4 100644 --- a/lib/.eslintrc.yaml +++ b/lib/.eslintrc.yaml @@ -15,6 +15,8 @@ rules: # Config specific to lib - selector: "NewExpression[callee.name=/Error$/]:not([callee.name=/^(AssertionError|NghttpError)$/])" message: "Use an error exported by the internal/errors module." + - selector: "CallExpression[callee.object.name='Error'][callee.property.name='captureStackTrace']" + message: "Please use `require('internal/errors').hideStackFrames()` instead." # Custom rules in tools/eslint-rules node-core/require-globals: error node-core/no-let-in-for-declaration: error diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 9d308525c6..ba5d226e7b 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -34,16 +34,19 @@ const { symbols: { async_id_symbol } } = require('internal/async_hooks'); const { - ERR_HTTP_HEADERS_SENT, - ERR_HTTP_INVALID_HEADER_VALUE, - ERR_HTTP_TRAILER_INVALID, - ERR_INVALID_HTTP_TOKEN, - ERR_INVALID_ARG_TYPE, - ERR_INVALID_CHAR, - ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_WRITE_AFTER_END -} = require('internal/errors').codes; + codes: { + ERR_HTTP_HEADERS_SENT, + ERR_HTTP_INVALID_HEADER_VALUE, + ERR_HTTP_TRAILER_INVALID, + ERR_INVALID_HTTP_TOKEN, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CHAR, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_WRITE_AFTER_END + }, + hideStackFrames +} = require('internal/errors'); const { validateString } = require('internal/validators'); const { CRLF, debug } = common; @@ -443,39 +446,21 @@ function matchHeader(self, state, field, value) { } } -function validateHeaderName(name) { +const validateHeaderName = hideStackFrames((name) => { if (typeof name !== 'string' || !name || !checkIsHttpToken(name)) { - // Reducing the limit improves the performance significantly. We do not - // lose the stack frames due to the `captureStackTrace()` function that is - // called later. - const tmpLimit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - const err = new ERR_INVALID_HTTP_TOKEN('Header name', name); - Error.stackTraceLimit = tmpLimit; - Error.captureStackTrace(err, validateHeaderName); - throw err; + throw new ERR_INVALID_HTTP_TOKEN('Header name', name); } -} +}); -function validateHeaderValue(name, value) { - let err; - // Reducing the limit improves the performance significantly. We do not loose - // the stack frames due to the `captureStackTrace()` function that is called - // later. - const tmpLimit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; +const validateHeaderValue = hideStackFrames((name, value) => { if (value === undefined) { - err = new ERR_HTTP_INVALID_HEADER_VALUE(value, name); - } else if (checkInvalidHeaderChar(value)) { - debug('Header "%s" contains invalid characters', name); - err = new ERR_INVALID_CHAR('header content', name); + throw new ERR_HTTP_INVALID_HEADER_VALUE(value, name); } - Error.stackTraceLimit = tmpLimit; - if (err !== undefined) { - Error.captureStackTrace(err, validateHeaderValue); - throw err; + if (checkInvalidHeaderChar(value)) { + debug('Header "%s" contains invalid characters', name); + throw new ERR_INVALID_CHAR('header content', name); } -} +}); OutgoingMessage.prototype.setHeader = function setHeader(name, value) { if (this._header) { diff --git a/lib/assert.js b/lib/assert.js index 99c000e316..51ee781b59 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -240,6 +240,7 @@ function getErrMessage(message, fn) { // We only need the stack trace. To minimize the overhead use an object // instead of an error. const err = {}; + // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(err, fn); Error.stackTraceLimit = tmpLimit; diff --git a/lib/buffer.js b/lib/buffer.js index c5497e18aa..b072ac407d 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -62,15 +62,18 @@ const { } = require('internal/util/inspect'); const { - ERR_BUFFER_OUT_OF_BOUNDS, - ERR_OUT_OF_RANGE, - ERR_INVALID_ARG_TYPE, - ERR_INVALID_ARG_VALUE, - ERR_INVALID_BUFFER_SIZE, - ERR_INVALID_OPT_VALUE, - ERR_NO_LONGER_SUPPORTED, - ERR_UNKNOWN_ENCODING -} = require('internal/errors').codes; + codes: { + ERR_BUFFER_OUT_OF_BOUNDS, + ERR_OUT_OF_RANGE, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE, + ERR_INVALID_BUFFER_SIZE, + ERR_INVALID_OPT_VALUE, + ERR_NO_LONGER_SUPPORTED, + ERR_UNKNOWN_ENCODING + }, + hideStackFrames +} = require('internal/errors'); const { validateString } = require('internal/validators'); const { @@ -247,20 +250,14 @@ Object.setPrototypeOf(Buffer, Uint8Array); // The 'assertSize' method will remove itself from the callstack when an error // occurs. This is done simply to keep the internal details of the // implementation from bleeding out to users. -function assertSize(size) { - let err = null; - +const assertSize = hideStackFrames((size) => { if (typeof size !== 'number') { - err = new ERR_INVALID_ARG_TYPE('size', 'number', size); - } else if (!(size >= 0 && size <= kMaxLength)) { - err = new ERR_INVALID_OPT_VALUE.RangeError('size', size); + throw new ERR_INVALID_ARG_TYPE('size', 'number', size); } - - if (err !== null) { - Error.captureStackTrace(err, assertSize); - throw err; + if (!(size >= 0 && size <= kMaxLength)) { + throw new ERR_INVALID_OPT_VALUE.RangeError('size', size); } -} +}); /** * Creates a new filled Buffer instance. diff --git a/lib/events.js b/lib/events.js index 8a676773b6..6a141f44d8 100644 --- a/lib/events.js +++ b/lib/events.js @@ -158,6 +158,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) { try { const { kExpandStackSymbol } = require('internal/util'); const capture = {}; + // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(capture, EventEmitter.prototype.emit); Object.defineProperty(er, kExpandStackSymbol, { value: enhanceStackTrace.bind(null, er, capture), diff --git a/lib/fs.js b/lib/fs.js index 46f26fe9eb..cfe856eaeb 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -43,13 +43,15 @@ const pathModule = require('path'); const { isArrayBufferView } = require('internal/util/types'); const binding = internalBinding('fs'); const { Buffer, kMaxLength } = require('buffer'); -const errors = require('internal/errors'); const { - ERR_FS_FILE_TOO_LARGE, - ERR_INVALID_ARG_VALUE, - ERR_INVALID_ARG_TYPE, - ERR_INVALID_CALLBACK -} = errors.codes; + codes: { + ERR_FS_FILE_TOO_LARGE, + ERR_INVALID_ARG_VALUE, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK + }, + uvException +} = require('internal/errors'); const { FSReqCallback, statValues } = binding; const { toPathIfFileURL } = require('internal/url'); @@ -114,13 +116,16 @@ function showTruncateDeprecation() { function handleErrorFromBinding(ctx) { if (ctx.errno !== undefined) { // libuv error numbers - const err = errors.uvException(ctx); + const err = uvException(ctx); + // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(err, handleErrorFromBinding); throw err; - } else if (ctx.error !== undefined) { // errors created in C++ land. + } + if (ctx.error !== undefined) { // errors created in C++ land. // TODO(joyeecheung): currently, ctx.error are encoding errors // usually caused by memory problems. We need to figure out proper error // code(s) for this. + // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(ctx.error, handleErrorFromBinding); throw ctx.error; } @@ -310,7 +315,7 @@ function tryStatSync(fd, isUserFd) { const stats = binding.fstat(fd, false, undefined, ctx); if (ctx.errno !== undefined && !isUserFd) { fs.closeSync(fd); - throw errors.uvException(ctx); + throw uvException(ctx); } return stats; } diff --git a/lib/internal/assert/assertion_error.js b/lib/internal/assert/assertion_error.js index a13a610da1..7c9bace378 100644 --- a/lib/internal/assert/assertion_error.js +++ b/lib/internal/assert/assertion_error.js @@ -300,6 +300,9 @@ class AssertionError extends Error { stackStartFn } = options; + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + if (message != null) { super(String(message)); } else { @@ -387,13 +390,29 @@ class AssertionError extends Error { } } + Error.stackTraceLimit = limit; + this.generatedMessage = !message; - this.name = 'AssertionError [ERR_ASSERTION]'; + Object.defineProperty(this, 'name', { + value: 'AssertionError [ERR_ASSERTION]', + enumerable: false, + writable: true, + configurable: true + }); this.code = 'ERR_ASSERTION'; this.actual = actual; this.expected = expected; this.operator = operator; + // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(this, stackStartFn); + // Create error message including the error code in the name. + this.stack; + // Reset the name. + this.name = 'AssertionError'; + } + + toString() { + return `${this.name} [${this.code}]: ${this.message}`; } [inspect.custom](recurseTimes, ctx) { diff --git a/lib/internal/async_hooks.js b/lib/internal/async_hooks.js index 206cdc5c15..55f6ea1c07 100644 --- a/lib/internal/async_hooks.js +++ b/lib/internal/async_hooks.js @@ -105,6 +105,7 @@ function fatalError(e) { process._rawDebug(e.stack); } else { const o = { message: e }; + // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(o, fatalError); process._rawDebug(o.stack); } diff --git a/lib/internal/console/constructor.js b/lib/internal/console/constructor.js index b8f2ae2924..7c141ce898 100644 --- a/lib/internal/console/constructor.js +++ b/lib/internal/console/constructor.js @@ -331,6 +331,7 @@ const consoleMethods = { name: 'Trace', message: this[kFormatForStderr](args) }; + // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(err, this.trace); this.error(err.stack); }, diff --git a/lib/internal/crypto/pbkdf2.js b/lib/internal/crypto/pbkdf2.js index e1a7a4811a..4694c6ce9a 100644 --- a/lib/internal/crypto/pbkdf2.js +++ b/lib/internal/crypto/pbkdf2.js @@ -65,8 +65,8 @@ function check(password, salt, iterations, keylen, digest) { password = validateArrayBufferView(password, 'password'); salt = validateArrayBufferView(salt, 'salt'); - iterations = validateUint32(iterations, 'iterations', 0); - keylen = validateUint32(keylen, 'keylen', 0); + validateUint32(iterations, 'iterations', 0); + validateUint32(keylen, 'keylen', 0); return { password, salt, iterations, keylen, digest }; } diff --git a/lib/internal/errors.js b/lib/internal/errors.js index d283fda143..dd6d7d5679 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -18,6 +18,8 @@ const codes = {}; const { kMaxLength } = internalBinding('buffer'); const { defineProperty } = Object; +let excludedStackFn; + // Lazily loaded let util; let assert; @@ -47,7 +49,15 @@ function lazyBuffer() { // and may have .path and .dest. class SystemError extends Error { constructor(key, context) { - super(); + if (excludedStackFn === undefined) { + super(); + } else { + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + super(); + // Reset the limit and setting the name property. + Error.stackTraceLimit = limit; + } const prefix = getMessage(key, [], this); let message = `${prefix}: ${context.syscall} returned ` + `${context.code} (${context.message})`; @@ -74,19 +84,7 @@ class SystemError extends Error { value: key, writable: true }); - } - - get name() { - return `SystemError [${this[kCode]}]`; - } - - set name(value) { - defineProperty(this, 'name', { - configurable: true, - enumerable: true, - value, - writable: true - }); + addCodeToName(this, 'SystemError', key); } get code() { @@ -141,6 +139,10 @@ class SystemError extends Error { this[kInfo].dest = val ? lazyBuffer().from(val.toString()) : undefined; } + + toString() { + return `${this.name} [${this.code}]: ${this.message}`; + } } function makeSystemErrorWithCode(key) { @@ -151,12 +153,18 @@ function makeSystemErrorWithCode(key) { }; } -let useOriginalName = false; - function makeNodeErrorWithCode(Base, key) { return class NodeError extends Base { constructor(...args) { - super(); + if (excludedStackFn === undefined) { + super(); + } else { + const limit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + super(); + // Reset the limit and setting the name property. + Error.stackTraceLimit = limit; + } const message = getMessage(key, args, this); Object.defineProperty(this, 'message', { value: message, @@ -164,22 +172,7 @@ function makeNodeErrorWithCode(Base, key) { writable: true, configurable: true }); - } - - get name() { - if (useOriginalName) { - return super.name; - } - return `${super.name} [${key}]`; - } - - set name(value) { - defineProperty(this, 'name', { - configurable: true, - enumerable: true, - value, - writable: true - }); + addCodeToName(this, super.name, key); } get code() { @@ -194,9 +187,56 @@ function makeNodeErrorWithCode(Base, key) { writable: true }); } + + toString() { + return `${this.name} [${key}]: ${this.message}`; + } + }; +} + +// This function removes unnecessary frames from Node.js core errors. +function hideStackFrames(fn) { + return function hidden(...args) { + // Make sure the most outer `hideStackFrames()` function is used. + let setStackFn = false; + if (excludedStackFn === undefined) { + excludedStackFn = hidden; + setStackFn = true; + } + try { + return fn(...args); + } finally { + if (setStackFn === true) { + excludedStackFn = undefined; + } + } }; } +function addCodeToName(err, name, code) { + // Set the stack + if (excludedStackFn !== undefined) { + // eslint-disable-next-line no-restricted-syntax + Error.captureStackTrace(err, excludedStackFn); + } + // Add the error code to the name to include it in the stack trace. + err.name = `${name} [${code}]`; + // Access the stack to generate the error message including the error code + // from the name. + err.stack; + // Reset the name to the actual name. + if (name === 'SystemError') { + defineProperty(err, 'name', { + value: name, + enumerable: false, + writable: true, + configurable: true + }); + } else { + delete err.name; + } +} + // Utility function for registering the error codes. Only used here. Exported // *only* to allow for testing. function E(sym, val, def, ...otherClasses) { @@ -305,6 +345,7 @@ function uvException(ctx) { err[prop] = ctx[prop]; } + // TODO(BridgeAR): Show the `code` property as part of the stack. err.code = code; if (path) { err.path = path; @@ -313,7 +354,8 @@ function uvException(ctx) { err.dest = dest; } - Error.captureStackTrace(err, uvException); + // eslint-disable-next-line no-restricted-syntax + Error.captureStackTrace(err, excludedStackFn || uvException); return err; } @@ -355,7 +397,8 @@ function uvExceptionWithHostPort(err, syscall, address, port) { ex.port = port; } - Error.captureStackTrace(ex, uvExceptionWithHostPort); + // eslint-disable-next-line no-restricted-syntax + Error.captureStackTrace(ex, excludedStackFn || uvExceptionWithHostPort); return ex; } @@ -383,7 +426,8 @@ function errnoException(err, syscall, original) { ex.code = ex.errno = code; ex.syscall = syscall; - Error.captureStackTrace(ex, errnoException); + // eslint-disable-next-line no-restricted-syntax + Error.captureStackTrace(ex, excludedStackFn || errnoException); return ex; } @@ -431,7 +475,8 @@ function exceptionWithHostPort(err, syscall, address, port, additional) { ex.port = port; } - Error.captureStackTrace(ex, exceptionWithHostPort); + // eslint-disable-next-line no-restricted-syntax + Error.captureStackTrace(ex, excludedStackFn || exceptionWithHostPort); return ex; } @@ -470,7 +515,9 @@ function dnsException(code, syscall, hostname) { if (hostname) { ex.hostname = hostname; } - Error.captureStackTrace(ex, dnsException); + + // eslint-disable-next-line no-restricted-syntax + Error.captureStackTrace(ex, excludedStackFn || dnsException); return ex; } @@ -520,21 +567,19 @@ function oneOf(expected, thing) { } module.exports = { + addCodeToName, // Exported for NghttpError + codes, dnsException, errnoException, exceptionWithHostPort, + getMessage, + hideStackFrames, + isStackOverflowError, uvException, uvExceptionWithHostPort, - isStackOverflowError, - getMessage, SystemError, - codes, // This is exported only to facilitate testing. - E, - // This allows us to tell the type of the errors without using - // instanceof, which is necessary in WPT harness. - get useOriginalName() { return useOriginalName; }, - set useOriginalName(value) { useOriginalName = value; } + E }; // To declare an error message, use the E(sym, val, def) function above. The sym @@ -553,7 +598,6 @@ module.exports = { // Note: Please try to keep these in alphabetical order // // Note: Node.js specific errors must begin with the prefix ERR_ - E('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); E('ERR_ARG_NOT_ITERABLE', '%s must be iterable', TypeError); E('ERR_ASSERTION', '%s', Error); @@ -627,7 +671,10 @@ E('ERR_ENCODING_INVALID_ENCODED_DATA', function(encoding, ret) { }, TypeError); E('ERR_ENCODING_NOT_SUPPORTED', 'The "%s" encoding is not supported', RangeError); -E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value', Error); +E('ERR_FALSY_VALUE_REJECTION', function(reason) { + this.reason = reason; + return 'Promise was rejected with falsy value'; +}, Error); E('ERR_FS_FILE_TOO_LARGE', 'File size (%s) is greater than possible Buffer: ' + `${kMaxLength} bytes`, RangeError); @@ -810,6 +857,8 @@ E('ERR_INVALID_OPT_VALUE', (name, value) => RangeError); E('ERR_INVALID_OPT_VALUE_ENCODING', 'The value "%s" is invalid for option "encoding"', TypeError); +E('ERR_INVALID_PACKAGE_CONFIG', + 'Invalid package config in \'%s\' imported from %s', Error); E('ERR_INVALID_PERFORMANCE_MARK', 'The "%s" performance mark has not been set', Error); E('ERR_INVALID_PROTOCOL', @@ -817,6 +866,8 @@ E('ERR_INVALID_PROTOCOL', TypeError); E('ERR_INVALID_REPL_EVAL_CONFIG', 'Cannot specify both "breakEvalOnSigint" and "eval" for REPL', TypeError); +E('ERR_INVALID_REPL_TYPE', + 'Cannot specify --entry-type for REPL', TypeError); E('ERR_INVALID_RETURN_PROPERTY', (input, name, prop, value) => { return `Expected a valid ${input} to be returned for the "${prop}" from the` + ` "${name}" function but got ${value}.`; @@ -847,6 +898,9 @@ E('ERR_INVALID_SYNC_FORK_INPUT', TypeError); E('ERR_INVALID_THIS', 'Value of "this" must be of type %s', TypeError); E('ERR_INVALID_TUPLE', '%s must be an iterable %s tuple', TypeError); +E('ERR_INVALID_TYPE_FLAG', + 'Type flag must be one of "module", "commonjs". Received --entry-type=%s', + TypeError); E('ERR_INVALID_URI', 'URI malformed', URIError); E('ERR_INVALID_URL', function(input) { this.input = input; @@ -904,11 +958,6 @@ E('ERR_MISSING_ARGS', E('ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK', 'The ES Module loader may not return a format of \'dynamic\' when no ' + 'dynamicInstantiate function was provided', Error); -E('ERR_MISSING_MODULE', 'Cannot find module %s', Error); -E('ERR_MODULE_RESOLUTION_LEGACY', - '%s not found by import in %s.' + - ' Legacy behavior in require() would have found it at %s', - Error); E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error); E('ERR_NAPI_CONS_FUNCTION', 'Constructor must be a function', TypeError); E('ERR_NAPI_INVALID_DATAVIEW_ARGS', @@ -997,6 +1046,20 @@ E('ERR_TRANSFORM_ALREADY_TRANSFORMING', E('ERR_TRANSFORM_WITH_LENGTH_0', 'Calling transform done when writableState.length != 0', Error); E('ERR_TTY_INIT_FAILED', 'TTY initialization failed', SystemError); +E('ERR_TYPE_MISMATCH', (filename, ext, typeFlag, conflict) => { + const typeString = + typeFlag === 'module' ? '--entry-type=module' : '--entry-type=commonjs'; + // --entry-type mismatches file extension + if (conflict === 'extension') + return `Extension ${ext} is not supported for ` + + `${typeString} loading ${filename}`; + // --entry-type mismatches package.json "type" + else if (conflict === 'scope') + return `Cannot use ${typeString} because nearest parent package.json ` + + ((typeFlag === 'module') ? + 'includes "type": "commonjs"' : 'includes "type": "module",') + + ` which controls the type to use for ${filename}`; +}, TypeError); E('ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET', '`process.setupUncaughtExceptionCapture()` was called while a capture ' + 'callback was already active', @@ -1013,9 +1076,8 @@ E('ERR_UNHANDLED_ERROR', E('ERR_UNKNOWN_BUILTIN_MODULE', 'No such built-in module: %s', Error); E('ERR_UNKNOWN_CREDENTIAL', '%s identifier does not exist: %s', Error); E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError); - +E('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension: %s', TypeError); // This should probably be a `TypeError`. -E('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension: %s', Error); E('ERR_UNKNOWN_MODULE_FORMAT', 'Unknown module format: %s', RangeError); E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s', TypeError); diff --git a/lib/internal/fs/utils.js b/lib/internal/fs/utils.js index 0c5ce1ecb7..a0b3eec5f7 100644 --- a/lib/internal/fs/utils.js +++ b/lib/internal/fs/utils.js @@ -2,13 +2,16 @@ const { Buffer, kMaxLength } = require('buffer'); const { - ERR_FS_INVALID_SYMLINK_TYPE, - ERR_INVALID_ARG_TYPE, - ERR_INVALID_ARG_VALUE, - ERR_INVALID_OPT_VALUE, - ERR_INVALID_OPT_VALUE_ENCODING, - ERR_OUT_OF_RANGE -} = require('internal/errors').codes; + codes: { + ERR_FS_INVALID_SYMLINK_TYPE, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE, + ERR_INVALID_OPT_VALUE, + ERR_INVALID_OPT_VALUE_ENCODING, + ERR_OUT_OF_RANGE + }, + hideStackFrames +} = require('internal/errors'); const { isUint8Array, isArrayBufferView } = require('internal/util/types'); const { once } = require('internal/util'); const pathModule = require('path'); @@ -185,7 +188,7 @@ function getOptions(options, defaultOptions) { // Check if the path contains null types if it is a string nor Uint8Array, // otherwise return silently. -function nullCheck(path, propName, throwError = true) { +const nullCheck = hideStackFrames((path, propName, throwError = true) => { const pathIsString = typeof path === 'string'; const pathIsUint8Array = isUint8Array(path); @@ -196,26 +199,16 @@ function nullCheck(path, propName, throwError = true) { return; } - // Reducing the limit improves the performance significantly. We do not loose - // the stack frames due to the `captureStackTrace()` function that is called - // later. - const tmpLimit = Error.stackTraceLimit; - if (throwError) { - Error.stackTraceLimit = 0; - } const err = new ERR_INVALID_ARG_VALUE( propName, path, 'must be a string or Uint8Array without null bytes' ); - if (throwError) { - Error.stackTraceLimit = tmpLimit; - Error.captureStackTrace(err, nullCheck); throw err; } return err; -} +}); function preprocessSymlinkDestination(path, type, linkPath) { if (!isWindows) { @@ -359,7 +352,7 @@ function stringToFlags(flags) { throw new ERR_INVALID_OPT_VALUE('flags', flags); } -function stringToSymlinkType(type) { +const stringToSymlinkType = hideStackFrames((type) => { let flags = 0; if (typeof type === 'string') { switch (type) { @@ -372,13 +365,11 @@ function stringToSymlinkType(type) { case 'file': break; default: - const err = new ERR_FS_INVALID_SYMLINK_TYPE(type); - Error.captureStackTrace(err, stringToSymlinkType); - throw err; + throw new ERR_FS_INVALID_SYMLINK_TYPE(type); } } return flags; -} +}); // converts Date or number to a fractional UNIX timestamp function toUnixTimestamp(time, name = 'time') { @@ -399,65 +390,51 @@ function toUnixTimestamp(time, name = 'time') { throw new ERR_INVALID_ARG_TYPE(name, ['Date', 'Time in seconds'], time); } -function validateBuffer(buffer) { +const validateBuffer = hideStackFrames((buffer) => { if (!isArrayBufferView(buffer)) { - const err = new ERR_INVALID_ARG_TYPE('buffer', - ['Buffer', 'TypedArray', 'DataView'], - buffer); - Error.captureStackTrace(err, validateBuffer); - throw err; + throw new ERR_INVALID_ARG_TYPE('buffer', + ['Buffer', 'TypedArray', 'DataView'], + buffer); } -} +}); -function validateOffsetLengthRead(offset, length, bufferLength) { - let err; - - if (offset < 0 || offset >= bufferLength) { - err = new ERR_OUT_OF_RANGE('offset', - `>= 0 && <= ${bufferLength}`, offset); - } else if (length < 0 || offset + length > bufferLength) { - err = new ERR_OUT_OF_RANGE('length', - `>= 0 && <= ${bufferLength - offset}`, length); - } - - if (err !== undefined) { - Error.captureStackTrace(err, validateOffsetLengthRead); - throw err; +const validateOffsetLengthRead = hideStackFrames( + (offset, length, bufferLength) => { + if (offset < 0 || offset >= bufferLength) { + throw new ERR_OUT_OF_RANGE('offset', + `>= 0 && <= ${bufferLength}`, offset); + } + if (length < 0 || offset + length > bufferLength) { + throw new ERR_OUT_OF_RANGE('length', + `>= 0 && <= ${bufferLength - offset}`, length); + } } -} +); -function validateOffsetLengthWrite(offset, length, byteLength) { - let err; +const validateOffsetLengthWrite = hideStackFrames( + (offset, length, byteLength) => { + if (offset > byteLength) { + throw new ERR_OUT_OF_RANGE('offset', `<= ${byteLength}`, offset); + } - if (offset > byteLength) { - err = new ERR_OUT_OF_RANGE('offset', `<= ${byteLength}`, offset); - } else { const max = byteLength > kMaxLength ? kMaxLength : byteLength; if (length > max - offset) { - err = new ERR_OUT_OF_RANGE('length', `<= ${max - offset}`, length); + throw new ERR_OUT_OF_RANGE('length', `<= ${max - offset}`, length); } } +); - if (err !== undefined) { - Error.captureStackTrace(err, validateOffsetLengthWrite); - throw err; - } -} - -function validatePath(path, propName = 'path') { - let err; - +const validatePath = hideStackFrames((path, propName = 'path') => { if (typeof path !== 'string' && !isUint8Array(path)) { - err = new ERR_INVALID_ARG_TYPE(propName, ['string', 'Buffer', 'URL'], path); - } else { - err = nullCheck(path, propName, false); + throw new ERR_INVALID_ARG_TYPE(propName, ['string', 'Buffer', 'URL'], path); } + const err = nullCheck(path, propName, false); + if (err !== undefined) { - Error.captureStackTrace(err, validatePath); throw err; } -} +}); module.exports = { assertEncoding, diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js index 551c9f1efa..23266eb6c2 100644 --- a/lib/internal/http2/compat.js +++ b/lib/internal/http2/compat.js @@ -6,17 +6,20 @@ const Readable = Stream.Readable; const binding = internalBinding('http2'); const constants = binding.constants; const { - ERR_HTTP2_HEADERS_SENT, - ERR_HTTP2_INFO_STATUS_NOT_ALLOWED, - ERR_HTTP2_INVALID_HEADER_VALUE, - ERR_HTTP2_INVALID_STREAM, - ERR_HTTP2_NO_SOCKET_MANIPULATION, - ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED, - ERR_HTTP2_STATUS_INVALID, - ERR_INVALID_ARG_VALUE, - ERR_INVALID_CALLBACK, - ERR_INVALID_HTTP_TOKEN -} = require('internal/errors').codes; + codes: { + ERR_HTTP2_HEADERS_SENT, + ERR_HTTP2_INFO_STATUS_NOT_ALLOWED, + ERR_HTTP2_INVALID_HEADER_VALUE, + ERR_HTTP2_INVALID_STREAM, + ERR_HTTP2_NO_SOCKET_MANIPULATION, + ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED, + ERR_HTTP2_STATUS_INVALID, + ERR_INVALID_ARG_VALUE, + ERR_INVALID_CALLBACK, + ERR_INVALID_HTTP_TOKEN + }, + hideStackFrames +} = require('internal/errors'); const { validateString } = require('internal/validators'); const { kSocket, kRequest, kProxySocket } = require('internal/http2/util'); @@ -51,22 +54,20 @@ let statusConnectionHeaderWarned = false; // HTTP/2 implementation, intended to provide an interface that is as // close as possible to the current require('http') API -function assertValidHeader(name, value) { - let err; +const assertValidHeader = hideStackFrames((name, value) => { if (name === '' || typeof name !== 'string') { - err = new ERR_INVALID_HTTP_TOKEN('Header name', name); - } else if (isPseudoHeader(name)) { - err = new ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED(); - } else if (value === undefined || value === null) { - err = new ERR_HTTP2_INVALID_HEADER_VALUE(value, name); - } else if (!isConnectionHeaderAllowed(name, value)) { - connectionHeaderMessageWarn(); + throw new ERR_INVALID_HTTP_TOKEN('Header name', name); } - if (err !== undefined) { - Error.captureStackTrace(err, assertValidHeader); - throw err; + if (isPseudoHeader(name)) { + throw new ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED(); } -} + if (value === undefined || value === null) { + throw new ERR_HTTP2_INVALID_HEADER_VALUE(value, name); + } + if (!isConnectionHeaderAllowed(name, value)) { + connectionHeaderMessageWarn(); + } +}); function isPseudoHeader(name) { switch (name) { diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 39e9dd625a..393970cf47 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -76,7 +76,8 @@ const { ERR_INVALID_OPT_VALUE, ERR_OUT_OF_RANGE, ERR_SOCKET_CLOSED - } + }, + hideStackFrames } = require('internal/errors'); const { validateNumber, validateString } = require('internal/validators'); const { utcDate } = require('internal/http'); @@ -606,37 +607,31 @@ function requestOnConnect(headers, options) { // 4. if specified, options.silent must be a boolean // // Also sets the default priority options if they are not set. -function validatePriorityOptions(options) { - let err; +const validatePriorityOptions = hideStackFrames((options) => { if (options.weight === undefined) { options.weight = NGHTTP2_DEFAULT_WEIGHT; } else if (typeof options.weight !== 'number') { - err = new ERR_INVALID_OPT_VALUE('weight', options.weight); + throw new ERR_INVALID_OPT_VALUE('weight', options.weight); } if (options.parent === undefined) { options.parent = 0; } else if (typeof options.parent !== 'number' || options.parent < 0) { - err = new ERR_INVALID_OPT_VALUE('parent', options.parent); + throw new ERR_INVALID_OPT_VALUE('parent', options.parent); } if (options.exclusive === undefined) { options.exclusive = false; } else if (typeof options.exclusive !== 'boolean') { - err = new ERR_INVALID_OPT_VALUE('exclusive', options.exclusive); + throw new ERR_INVALID_OPT_VALUE('exclusive', options.exclusive); } if (options.silent === undefined) { options.silent = false; } else if (typeof options.silent !== 'boolean') { - err = new ERR_INVALID_OPT_VALUE('silent', options.silent); - } - - if (err) { - Error.captureStackTrace(err, validatePriorityOptions); - throw err; + throw new ERR_INVALID_OPT_VALUE('silent', options.silent); } -} +}); // When an error occurs internally at the binding level, immediately // destroy the session. @@ -788,7 +783,7 @@ function pingCallback(cb) { // 5. maxHeaderListSize must be a number in the range 0 <= n <= kMaxInt // 6. enablePush must be a boolean // All settings are optional and may be left undefined -function validateSettings(settings) { +const validateSettings = hideStackFrames((settings) => { settings = { ...settings }; assertWithinRange('headerTableSize', settings.headerTableSize, @@ -807,13 +802,11 @@ function validateSettings(settings) { 0, kMaxInt); if (settings.enablePush !== undefined && typeof settings.enablePush !== 'boolean') { - const err = new ERR_HTTP2_INVALID_SETTING_VALUE('enablePush', - settings.enablePush); - Error.captureStackTrace(err, 'validateSettings'); - throw err; + throw new ERR_HTTP2_INVALID_SETTING_VALUE('enablePush', + settings.enablePush); } return settings; -} +}); // Creates the internal binding.Http2Session handle for an Http2Session // instance. This occurs only after the socket connection has been diff --git a/lib/internal/http2/util.js b/lib/internal/http2/util.js index 81b28e2ed4..80422cdc8b 100644 --- a/lib/internal/http2/util.js +++ b/lib/internal/http2/util.js @@ -2,12 +2,16 @@ const binding = internalBinding('http2'); const { - ERR_HTTP2_HEADER_SINGLE_VALUE, - ERR_HTTP2_INVALID_CONNECTION_HEADERS, - ERR_HTTP2_INVALID_PSEUDOHEADER, - ERR_HTTP2_INVALID_SETTING_VALUE, - ERR_INVALID_ARG_TYPE -} = require('internal/errors').codes; + codes: { + ERR_HTTP2_HEADER_SINGLE_VALUE, + ERR_HTTP2_INVALID_CONNECTION_HEADERS, + ERR_HTTP2_INVALID_PSEUDOHEADER, + ERR_HTTP2_INVALID_SETTING_VALUE, + ERR_INVALID_ARG_TYPE + }, + addCodeToName, + hideStackFrames +} = require('internal/errors'); const kSocket = Symbol('socket'); const kProxySocket = Symbol('proxySocket'); @@ -404,27 +408,21 @@ function isIllegalConnectionSpecificHeader(name, value) { } } -function assertValidPseudoHeader(key) { +const assertValidPseudoHeader = hideStackFrames((key) => { if (!kValidPseudoHeaders.has(key)) { - const err = new ERR_HTTP2_INVALID_PSEUDOHEADER(key); - Error.captureStackTrace(err, assertValidPseudoHeader); - throw err; + throw new ERR_HTTP2_INVALID_PSEUDOHEADER(key); } -} +}); -function assertValidPseudoHeaderResponse(key) { +const assertValidPseudoHeaderResponse = hideStackFrames((key) => { if (key !== ':status') { - const err = new ERR_HTTP2_INVALID_PSEUDOHEADER(key); - Error.captureStackTrace(err, assertValidPseudoHeaderResponse); - throw err; + throw new ERR_HTTP2_INVALID_PSEUDOHEADER(key); } -} +}); -function assertValidPseudoHeaderTrailer(key) { - const err = new ERR_HTTP2_INVALID_PSEUDOHEADER(key); - Error.captureStackTrace(err, assertValidPseudoHeaderTrailer); - throw err; -} +const assertValidPseudoHeaderTrailer = hideStackFrames((key) => { + throw new ERR_HTTP2_INVALID_PSEUDOHEADER(key); +}); function mapToHeaders(map, assertValuePseudoHeader = assertValidPseudoHeader) { @@ -496,31 +494,33 @@ class NghttpError extends Error { constructor(ret) { super(binding.nghttp2ErrorString(ret)); this.code = 'ERR_HTTP2_ERROR'; - this.name = 'Error [ERR_HTTP2_ERROR]'; this.errno = ret; + addCodeToName(this, super.name, 'ERR_HTTP2_ERROR'); + } + + toString() { + return `${this.name} [${this.code}]: ${this.message}`; } } -function assertIsObject(value, name, types) { +const assertIsObject = hideStackFrames((value, name, types) => { if (value !== undefined && (value === null || typeof value !== 'object' || Array.isArray(value))) { - const err = new ERR_INVALID_ARG_TYPE(name, types || 'Object', value); - Error.captureStackTrace(err, assertIsObject); - throw err; + throw new ERR_INVALID_ARG_TYPE(name, types || 'Object', value); } -} +}); -function assertWithinRange(name, value, min = 0, max = Infinity) { - if (value !== undefined && +const assertWithinRange = hideStackFrames( + (name, value, min = 0, max = Infinity) => { + if (value !== undefined && (typeof value !== 'number' || value < min || value > max)) { - const err = new ERR_HTTP2_INVALID_SETTING_VALUE.RangeError( - name, value, min, max); - Error.captureStackTrace(err, assertWithinRange); - throw err; + throw new ERR_HTTP2_INVALID_SETTING_VALUE.RangeError( + name, value, min, max); + } } -} +); function toHeaderObject(headers) { const obj = Object.create(null); diff --git a/lib/internal/main/check_syntax.js b/lib/internal/main/check_syntax.js index 7df70b2720..2795f5766e 100644 --- a/lib/internal/main/check_syntax.js +++ b/lib/internal/main/check_syntax.js @@ -11,12 +11,18 @@ const { readStdin } = require('internal/process/execution'); -const CJSModule = require('internal/modules/cjs/loader'); +const { pathToFileURL } = require('url'); + const vm = require('vm'); const { stripShebang, stripBOM } = require('internal/modules/cjs/helpers'); +let CJSModule; +function CJSModuleInit() { + if (!CJSModule) + CJSModule = require('internal/modules/cjs/loader'); +} if (process.argv[1] && process.argv[1] !== '-') { // Expand process.argv[1] into a full path. @@ -25,7 +31,7 @@ if (process.argv[1] && process.argv[1] !== '-') { // TODO(joyeecheung): not every one of these are necessary prepareMainThreadExecution(); - + CJSModuleInit(); // Read the source. const filename = CJSModule._resolveFilename(process.argv[1]); @@ -34,20 +40,40 @@ if (process.argv[1] && process.argv[1] !== '-') { markBootstrapComplete(); - checkScriptSyntax(source, filename); + checkSyntax(source, filename); } else { // TODO(joyeecheung): not every one of these are necessary prepareMainThreadExecution(); + CJSModuleInit(); markBootstrapComplete(); readStdin((code) => { - checkScriptSyntax(code, '[stdin]'); + checkSyntax(code, '[stdin]'); }); } -function checkScriptSyntax(source, filename) { +function checkSyntax(source, filename) { // Remove Shebang. source = stripShebang(source); + + const experimentalModules = + require('internal/options').getOptionValue('--experimental-modules'); + if (experimentalModules) { + let isModule = false; + if (filename === '[stdin]' || filename === '[eval]') { + isModule = require('internal/process/esm_loader').typeFlag === 'module'; + } else { + const resolve = require('internal/modules/esm/default_resolve'); + const { format } = resolve(pathToFileURL(filename).toString()); + isModule = format === 'module'; + } + if (isModule) { + const { ModuleWrap } = internalBinding('module_wrap'); + new ModuleWrap(source, filename); + return; + } + } + // Remove BOM. source = stripBOM(source); // Wrap it. diff --git a/lib/internal/main/eval_stdin.js b/lib/internal/main/eval_stdin.js index 2a2ef6d38a..869a3675b6 100644 --- a/lib/internal/main/eval_stdin.js +++ b/lib/internal/main/eval_stdin.js @@ -7,6 +7,7 @@ const { } = require('internal/bootstrap/pre_execution'); const { + evalModule, evalScript, readStdin } = require('internal/process/execution'); @@ -16,5 +17,8 @@ markBootstrapComplete(); readStdin((code) => { process._eval = code; - evalScript('[stdin]', process._eval, process._breakFirstLine); + if (require('internal/process/esm_loader').typeFlag === 'module') + evalModule(process._eval); + else + evalScript('[stdin]', process._eval, process._breakFirstLine); }); diff --git a/lib/internal/main/eval_string.js b/lib/internal/main/eval_string.js index 953fab386d..9328a114aa 100644 --- a/lib/internal/main/eval_string.js +++ b/lib/internal/main/eval_string.js @@ -6,11 +6,14 @@ const { prepareMainThreadExecution } = require('internal/bootstrap/pre_execution'); -const { evalScript } = require('internal/process/execution'); +const { evalModule, evalScript } = require('internal/process/execution'); const { addBuiltinLibsToObject } = require('internal/modules/cjs/helpers'); const source = require('internal/options').getOptionValue('--eval'); prepareMainThreadExecution(); addBuiltinLibsToObject(global); markBootstrapComplete(); -evalScript('[eval]', source, process._breakFirstLine); +if (require('internal/process/esm_loader').typeFlag === 'module') + evalModule(source); +else + evalScript('[eval]', source, process._breakFirstLine); diff --git a/lib/internal/main/repl.js b/lib/internal/main/repl.js index e6b9885351..cc15cda7fd 100644 --- a/lib/internal/main/repl.js +++ b/lib/internal/main/repl.js @@ -11,8 +11,15 @@ const { evalScript } = require('internal/process/execution'); +const { ERR_INVALID_REPL_TYPE } = require('internal/errors').codes; + prepareMainThreadExecution(); +// --entry-type flag not supported in REPL +if (require('internal/process/esm_loader').typeFlag) { + throw ERR_INVALID_REPL_TYPE(); +} + const cliRepl = require('internal/repl'); cliRepl.createInternalRepl(process.env, (err, repl) => { if (err) { diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index ee1c814c81..8be5b06120 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -873,9 +873,11 @@ Module.runMain = function() { .catch((e) => { internalBinding('task_queue').triggerFatalException(e); }); - } else { - Module._load(process.argv[1], null, true); + // Handle any nextTicks added in the first tick of the program + process._tickCallback(); + return; } + Module._load(process.argv[1], null, true); // Handle any nextTicks added in the first tick of the program process._tickCallback(); }; diff --git a/lib/internal/modules/esm/default_resolve.js b/lib/internal/modules/esm/default_resolve.js index 33366f0069..7b6b6fd4a3 100644 --- a/lib/internal/modules/esm/default_resolve.js +++ b/lib/internal/modules/esm/default_resolve.js @@ -1,57 +1,54 @@ 'use strict'; -const { URL } = require('url'); -const CJSmodule = require('internal/modules/cjs/loader'); const internalFS = require('internal/fs/utils'); const { NativeModule } = require('internal/bootstrap/loaders'); const { extname } = require('path'); const { realpathSync } = require('fs'); const { getOptionValue } = require('internal/options'); + const preserveSymlinks = getOptionValue('--preserve-symlinks'); const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main'); -const { - ERR_MISSING_MODULE, - ERR_MODULE_RESOLUTION_LEGACY, - ERR_UNKNOWN_FILE_EXTENSION -} = require('internal/errors').codes; -const { resolve: moduleWrapResolve } = internalBinding('module_wrap'); -const StringStartsWith = Function.call.bind(String.prototype.startsWith); +const experimentalJsonModules = getOptionValue('--experimental-json-modules'); + +const { resolve: moduleWrapResolve, + getPackageType } = internalBinding('module_wrap'); const { pathToFileURL, fileURLToPath } = require('internal/url'); +const asyncESM = require('internal/process/esm_loader'); +const { ERR_TYPE_MISMATCH, + ERR_UNKNOWN_FILE_EXTENSION } = require('internal/errors').codes; const realpathCache = new Map(); -function search(target, base) { - if (base === undefined) { - // We cannot search without a base. - throw new ERR_MISSING_MODULE(target); - } - try { - return moduleWrapResolve(target, base); - } catch (e) { - e.stack; // cause V8 to generate stack before rethrow - let error = e; - try { - const questionedBase = new URL(base); - const tmpMod = new CJSmodule(questionedBase.pathname, null); - tmpMod.paths = CJSmodule._nodeModulePaths( - new URL('./', questionedBase).pathname); - const found = CJSmodule._resolveFilename(target, tmpMod); - error = new ERR_MODULE_RESOLUTION_LEGACY(target, base, found); - } catch { - // ignore - } - throw error; - } -} +// const TYPE_NONE = 0; +const TYPE_COMMONJS = 1; +const TYPE_MODULE = 2; const extensionFormatMap = { '__proto__': null, - '.mjs': 'esm', - '.json': 'json', - '.node': 'addon', - '.js': 'cjs' + '.cjs': 'commonjs', + '.js': 'module', + '.mjs': 'module' }; +const legacyExtensionFormatMap = { + '__proto__': null, + '.cjs': 'commonjs', + '.js': 'commonjs', + '.json': 'commonjs', + '.mjs': 'module', + '.node': 'commonjs' +}; + +if (experimentalJsonModules) { + // This is a total hack + Object.assign(extensionFormatMap, { + '.json': 'json' + }); + Object.assign(legacyExtensionFormatMap, { + '.json': 'json' + }); +} + function resolve(specifier, parentURL) { if (NativeModule.canBeRequiredByUsers(specifier)) { return { @@ -60,21 +57,11 @@ function resolve(specifier, parentURL) { }; } - let url; - try { - url = search(specifier, - parentURL || pathToFileURL(`${process.cwd()}/`).href); - } catch (e) { - if (typeof e.message === 'string' && - StringStartsWith(e.message, 'Cannot find module')) { - e.code = 'MODULE_NOT_FOUND'; - // TODO: also add e.requireStack to match behavior with CJS - // MODULE_NOT_FOUND. - } - throw e; - } - const isMain = parentURL === undefined; + if (isMain) + parentURL = pathToFileURL(`${process.cwd()}/`).href; + + let url = moduleWrapResolve(specifier, parentURL); if (isMain ? !preserveSymlinksMain : !preserveSymlinks) { const real = realpathSync(fileURLToPath(url), { @@ -86,19 +73,40 @@ function resolve(specifier, parentURL) { url.hash = old.hash; } + const type = getPackageType(url.href); + const ext = extname(url.pathname); + const extMap = + type !== TYPE_MODULE ? legacyExtensionFormatMap : extensionFormatMap; + let format = extMap[ext]; - let format = extensionFormatMap[ext]; + if (isMain && asyncESM.typeFlag) { + // Conflict between explicit extension (.mjs, .cjs) and --entry-type + if (ext === '.cjs' && asyncESM.typeFlag === 'module' || + ext === '.mjs' && asyncESM.typeFlag === 'commonjs') { + throw new ERR_TYPE_MISMATCH( + fileURLToPath(url), ext, asyncESM.typeFlag, 'extension'); + } + + // Conflict between package scope type and --entry-type + if (ext === '.js') { + if (type === TYPE_MODULE && asyncESM.typeFlag === 'commonjs' || + type === TYPE_COMMONJS && asyncESM.typeFlag === 'module') { + throw new ERR_TYPE_MISMATCH( + fileURLToPath(url), ext, asyncESM.typeFlag, 'scope'); + } + } + } if (!format) { - if (isMain) - format = 'cjs'; + if (isMain && asyncESM.typeFlag) + format = asyncESM.typeFlag; + else if (isMain) + format = type === TYPE_MODULE ? 'module' : 'commonjs'; else - throw new ERR_UNKNOWN_FILE_EXTENSION(url.pathname); + throw new ERR_UNKNOWN_FILE_EXTENSION(fileURLToPath(url), + fileURLToPath(parentURL)); } - return { url: `${url}`, format }; } module.exports = resolve; -// exported for tests -module.exports.search = search; diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index a1a1621909..dced45f7a0 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -11,10 +11,12 @@ const { URL } = require('url'); const { validateString } = require('internal/validators'); const ModuleMap = require('internal/modules/esm/module_map'); const ModuleJob = require('internal/modules/esm/module_job'); + const defaultResolve = require('internal/modules/esm/default_resolve'); const createDynamicModule = require( 'internal/modules/esm/create_dynamic_module'); -const translators = require('internal/modules/esm/translators'); +const { translators } = require('internal/modules/esm/translators'); +const { ModuleWrap } = internalBinding('module_wrap'); const FunctionBind = Function.call.bind(Function.prototype.bind); @@ -32,6 +34,9 @@ class Loader { // Registry of loaded modules, akin to `require.cache` this.moduleMap = new ModuleMap(); + // Map of already-loaded CJS modules to use + this.cjsCache = new Map(); + // The resolver has the signature // (specifier : string, parentURL : string, defaultResolve) // -> Promise<{ url : string, format: string }> @@ -48,6 +53,8 @@ class Loader { // an object with the same keys as `exports`, whose values are get/set // functions for the actual exported values. this._dynamicInstantiate = undefined; + // The index for assigning unique URLs to anonymous module evaluation + this.evalIndex = 0; } async resolve(specifier, parentURL) { @@ -95,9 +102,25 @@ class Loader { return { url, format }; } + async eval(source, url = `eval:${++this.evalIndex}`) { + const evalInstance = async (url) => { + return { + module: new ModuleWrap(source, url), + reflect: undefined + }; + }; + const job = new ModuleJob(this, url, evalInstance, false); + this.moduleMap.set(url, job); + const { module, result } = await job.run(); + return { + namespace: module.namespace(), + result + }; + } + async import(specifier, parent) { const job = await this.getModuleJob(specifier, parent); - const module = await job.run(); + const { module } = await job.run(); return module.namespace(); } @@ -143,4 +166,4 @@ class Loader { Object.setPrototypeOf(Loader.prototype, null); -module.exports = Loader; +exports.Loader = Loader; diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js index 016495096c..5666032df1 100644 --- a/lib/internal/modules/esm/module_job.js +++ b/lib/internal/modules/esm/module_job.js @@ -23,7 +23,7 @@ class ModuleJob { // This is a Promise<{ module, reflect }>, whose fields will be copied // onto `this` by `link()` below once it has been resolved. - this.modulePromise = moduleProvider(url, isMain); + this.modulePromise = moduleProvider.call(loader, url, isMain); this.module = undefined; this.reflect = undefined; @@ -101,8 +101,9 @@ class ModuleJob { async run() { const module = await this.instantiate(); - module.evaluate(-1, false); - return module; + const timeout = -1; + const breakOnSigint = false; + return { module, result: module.evaluate(timeout, breakOnSigint) }; } } Object.setPrototypeOf(ModuleJob.prototype, null); diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js index cf1765c7c3..5755e4f837 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -11,28 +11,23 @@ const internalURLModule = require('internal/url'); const createDynamicModule = require( 'internal/modules/esm/create_dynamic_module'); const fs = require('fs'); -const { _makeLong } = require('path'); const { SafeMap, - JSON, - FunctionPrototype, - StringPrototype } = primordials; -const { URL } = require('url'); +const { fileURLToPath, URL } = require('url'); const { debuglog, promisify } = require('util'); const esmLoader = require('internal/process/esm_loader'); const { ERR_UNKNOWN_BUILTIN_MODULE } = require('internal/errors').codes; const readFileAsync = promisify(fs.readFile); -const readFileSync = fs.readFileSync; -const StringReplace = FunctionPrototype.call.bind(StringPrototype.replace); +const StringReplace = Function.call.bind(String.prototype.replace); const JsonParse = JSON.parse; const debug = debuglog('esm'); const translators = new SafeMap(); -module.exports = translators; +exports.translators = translators; function initializeImportMeta(meta, { url }) { meta.url = url; @@ -44,7 +39,7 @@ async function importModuleDynamically(specifier, { url }) { } // Strategy for loading a standard JavaScript module -translators.set('esm', async (url) => { +translators.set('module', async function moduleStrategy(url) { const source = `${await readFileAsync(new URL(url))}`; debug(`Translating StandardModule ${url}`); const module = new ModuleWrap(stripShebang(source), url); @@ -61,9 +56,14 @@ translators.set('esm', async (url) => { // Strategy for loading a node-style CommonJS module const isWindows = process.platform === 'win32'; const winSepRegEx = /\//g; -translators.set('cjs', async (url, isMain) => { +translators.set('commonjs', async function commonjsStrategy(url, isMain) { debug(`Translating CJSModule ${url}`); const pathname = internalURLModule.fileURLToPath(new URL(url)); + const cached = this.cjsCache.get(url); + if (cached) { + this.cjsCache.delete(url); + return cached; + } const module = CJSModule._cache[ isWindows ? StringReplace(pathname, winSepRegEx, '\\') : pathname]; if (module && module.loaded) { @@ -83,7 +83,7 @@ translators.set('cjs', async (url, isMain) => { // Strategy for loading a node builtin CommonJS module that isn't // through normal resolution -translators.set('builtin', async (url) => { +translators.set('builtin', async function builtinStrategy(url) { debug(`Translating BuiltinModule ${url}`); // slice 'node:' scheme const id = url.slice(5); @@ -102,31 +102,34 @@ translators.set('builtin', async (url) => { }); }); -// Strategy for loading a node native module -translators.set('addon', async (url) => { - debug(`Translating NativeModule ${url}`); - return createDynamicModule(['default'], url, (reflect) => { - debug(`Loading NativeModule ${url}`); - const module = { exports: {} }; - const pathname = internalURLModule.fileURLToPath(new URL(url)); - process.dlopen(module, _makeLong(pathname)); - reflect.exports.default.set(module.exports); - }); -}); - // Strategy for loading a JSON file -translators.set('json', async (url) => { +translators.set('json', async function jsonStrategy(url) { debug(`Translating JSONModule ${url}`); - return createDynamicModule(['default'], url, (reflect) => { - debug(`Loading JSONModule ${url}`); - const pathname = internalURLModule.fileURLToPath(new URL(url)); - const content = readFileSync(pathname, 'utf8'); - try { - const exports = JsonParse(stripBOM(content)); + debug(`Loading JSONModule ${url}`); + const pathname = fileURLToPath(url); + const modulePath = isWindows ? + StringReplace(pathname, winSepRegEx, '\\') : pathname; + let module = CJSModule._cache[modulePath]; + if (module && module.loaded) { + const exports = module.exports; + return createDynamicModule(['default'], url, (reflect) => { reflect.exports.default.set(exports); - } catch (err) { - err.message = pathname + ': ' + err.message; - throw err; - } + }); + } + const content = await readFileAsync(pathname, 'utf-8'); + try { + const exports = JsonParse(stripBOM(content)); + module = { + exports, + loaded: true + }; + } catch (err) { + err.message = pathname + ': ' + err.message; + throw err; + } + CJSModule._cache[modulePath] = module; + return createDynamicModule(['default'], url, (reflect) => { + debug(`Parsing JSONModule ${url}`); + reflect.exports.default.set(module.exports); }); }); diff --git a/lib/internal/policy/manifest.js b/lib/internal/policy/manifest.js index 6c777a7c78..1715bcba56 100644 --- a/lib/internal/policy/manifest.js +++ b/lib/internal/policy/manifest.js @@ -4,7 +4,7 @@ const { ERR_MANIFEST_INTEGRITY_MISMATCH, ERR_MANIFEST_UNKNOWN_ONERROR, } = require('internal/errors').codes; -const debug = require('util').debuglog('policy'); +const debug = require('internal/util/debuglog').debuglog('policy'); const SRI = require('internal/policy/sri'); const { SafeWeakMap, diff --git a/lib/internal/process/esm_loader.js b/lib/internal/process/esm_loader.js index 0b7f1be6ff..b5475769c7 100644 --- a/lib/internal/process/esm_loader.js +++ b/lib/internal/process/esm_loader.js @@ -3,15 +3,22 @@ const { callbackMap, } = internalBinding('module_wrap'); +const { + ERR_INVALID_TYPE_FLAG, + ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING, +} = require('internal/errors').codes; +const { emitExperimentalWarning } = require('internal/util'); + +const type = require('internal/options').getOptionValue('--entry-type'); +if (type && type !== 'commonjs' && type !== 'module') + throw new ERR_INVALID_TYPE_FLAG(type); +exports.typeFlag = type; +const { Loader } = require('internal/modules/esm/loader'); const { pathToFileURL } = require('internal/url'); -const Loader = require('internal/modules/esm/loader'); const { wrapToModuleMap, } = require('internal/vm/source_text_module'); -const { - ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING, -} = require('internal/errors').codes; exports.initializeImportMetaObject = function(wrap, meta) { if (callbackMap.has(wrap)) { @@ -34,9 +41,7 @@ exports.importModuleDynamicallyCallback = async function(wrap, specifier) { }; let loaderResolve; -exports.loaderPromise = new Promise((resolve, reject) => { - loaderResolve = resolve; -}); +exports.loaderPromise = new Promise((resolve) => loaderResolve = resolve); exports.ESMLoader = undefined; @@ -44,6 +49,7 @@ exports.initializeLoader = function(cwd, userLoader) { let ESMLoader = new Loader(); const loaderPromise = (async () => { if (userLoader) { + emitExperimentalWarning('--loader'); const hooks = await ESMLoader.import( userLoader, pathToFileURL(`${cwd}/`).href); ESMLoader = new Loader(); diff --git a/lib/internal/process/execution.js b/lib/internal/process/execution.js index 7118dbf3ad..070410ef6f 100644 --- a/lib/internal/process/execution.js +++ b/lib/internal/process/execution.js @@ -33,6 +33,24 @@ function tryGetCwd() { } } +function evalModule(source) { + const { decorateErrorStack } = require('internal/util'); + const asyncESM = require('internal/process/esm_loader'); + asyncESM.loaderPromise.then(async (loader) => { + const { result } = await loader.eval(source); + if (require('internal/options').getOptionValue('--print')) { + console.log(result); + } + }) + .catch((e) => { + decorateErrorStack(e); + console.error(e); + process.exit(1); + }); + // Handle any nextTicks added in the first tick of the program. + process._tickCallback(); +} + function evalScript(name, body, breakFirstLine) { const CJSModule = require('internal/modules/cjs/loader'); const { kVmBreakFirstLineSymbol } = require('internal/util'); @@ -176,6 +194,7 @@ function readStdin(callback) { module.exports = { readStdin, tryGetCwd, + evalModule, evalScript, fatalException: createFatalException(), setUncaughtExceptionCaptureCallback, diff --git a/lib/internal/process/warning.js b/lib/internal/process/warning.js index 2052ecf707..e0e1709bdb 100644 --- a/lib/internal/process/warning.js +++ b/lib/internal/process/warning.js @@ -112,6 +112,7 @@ function emitWarning(warning, type, code, ctor, now) { warning.name = String(type || 'Warning'); if (code !== undefined) warning.code = code; if (detail !== undefined) warning.detail = detail; + // eslint-disable-next-line no-restricted-syntax Error.captureStackTrace(warning, ctor || process.emitWarning); } else if (!(warning instanceof Error)) { throw new ERR_INVALID_ARG_TYPE('warning', ['Error', 'string'], warning); diff --git a/lib/internal/repl/history.js b/lib/internal/repl/history.js index a0ae07441e..9f41b18b67 100644 --- a/lib/internal/repl/history.js +++ b/lib/internal/repl/history.js @@ -4,8 +4,7 @@ const { Interface } = require('readline'); const path = require('path'); const fs = require('fs'); const os = require('os'); -const util = require('util'); -const debug = util.debuglog('repl'); +const debug = require('internal/util/debuglog').debuglog('repl'); // XXX(chrisdickinson): The 15ms debounce value is somewhat arbitrary. // The debounce is to guard against code pasted into the REPL. diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index ca78425a52..dc0a1dcb27 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -993,6 +993,7 @@ function formatPrimitive(fn, value, ctx) { } function formatError(value) { + // TODO(BridgeAR): Always show the error code if present. return value.stack || errorToString(value); } diff --git a/lib/internal/validators.js b/lib/internal/validators.js index 6de46349c0..a80917ee7e 100644 --- a/lib/internal/validators.js +++ b/lib/internal/validators.js @@ -1,10 +1,13 @@ 'use strict'; const { - ERR_INVALID_ARG_TYPE, - ERR_INVALID_ARG_VALUE, - ERR_OUT_OF_RANGE -} = require('internal/errors').codes; + hideStackFrames, + codes: { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE, + ERR_OUT_OF_RANGE + } +} = require('internal/errors'); function isInt32(value) { return value === (value | 0); @@ -52,66 +55,52 @@ function validateMode(value, name, def) { throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc); } -function validateInteger(value, name) { - let err; - +const validateInteger = hideStackFrames((value, name) => { if (typeof value !== 'number') - err = new ERR_INVALID_ARG_TYPE(name, 'number', value); - else if (!Number.isSafeInteger(value)) - err = new ERR_OUT_OF_RANGE(name, 'an integer', value); - - if (err) { - Error.captureStackTrace(err, validateInteger); - throw err; - } - + throw new ERR_INVALID_ARG_TYPE(name, 'number', value); + if (!Number.isSafeInteger(value)) + throw new ERR_OUT_OF_RANGE(name, 'an integer', value); return value; -} - -function validateInt32(value, name, min = -2147483648, max = 2147483647) { - // The defaults for min and max correspond to the limits of 32-bit integers. - if (!isInt32(value)) { - let err; - if (typeof value !== 'number') { - err = new ERR_INVALID_ARG_TYPE(name, 'number', value); - } else if (!Number.isInteger(value)) { - err = new ERR_OUT_OF_RANGE(name, 'an integer', value); - } else { - err = new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); +}); + +const validateInt32 = hideStackFrames( + (value, name, min = -2147483648, max = 2147483647) => { + // The defaults for min and max correspond to the limits of 32-bit integers. + if (!isInt32(value)) { + if (typeof value !== 'number') { + throw new ERR_INVALID_ARG_TYPE(name, 'number', value); + } + if (!Number.isInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, 'an integer', value); + } + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); } - Error.captureStackTrace(err, validateInt32); - throw err; - } else if (value < min || value > max) { - const err = new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); - Error.captureStackTrace(err, validateInt32); - throw err; + if (value < min || value > max) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value); + } + return value; } +); - return value; -} - -function validateUint32(value, name, positive) { +const validateUint32 = hideStackFrames((value, name, positive) => { if (!isUint32(value)) { - let err; if (typeof value !== 'number') { - err = new ERR_INVALID_ARG_TYPE(name, 'number', value); - } else if (!Number.isInteger(value)) { - err = new ERR_OUT_OF_RANGE(name, 'an integer', value); - } else { - const min = positive ? 1 : 0; - // 2 ** 32 === 4294967296 - err = new ERR_OUT_OF_RANGE(name, `>= ${min} && < 4294967296`, value); + throw new ERR_INVALID_ARG_TYPE(name, 'number', value); } - Error.captureStackTrace(err, validateUint32); - throw err; - } else if (positive && value === 0) { - const err = new ERR_OUT_OF_RANGE(name, '>= 1 && < 4294967296', value); - Error.captureStackTrace(err, validateUint32); - throw err; + if (!Number.isInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, 'an integer', value); + } + const min = positive ? 1 : 0; + // 2 ** 32 === 4294967296 + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && < 4294967296`, value); } - + if (positive && value === 0) { + throw new ERR_OUT_OF_RANGE(name, '>= 1 && < 4294967296', value); + } + // TODO(BridgeAR): Remove return values from validation functions and + // especially reduce side effects caused by validation functions. return value; -} +}); function validateString(value, name) { if (typeof value !== 'string') diff --git a/lib/internal/worker/io.js b/lib/internal/worker/io.js index 664055b5c5..ece0f2741a 100644 --- a/lib/internal/worker/io.js +++ b/lib/internal/worker/io.js @@ -18,7 +18,7 @@ const { const { Readable, Writable } = require('stream'); const EventEmitter = require('events'); -const util = require('util'); +const { inspect } = require('internal/util/inspect'); let debuglog; function debug(...args) { @@ -122,7 +122,7 @@ MessagePort.prototype.close = function(cb) { MessagePortPrototype.close.call(this); }; -Object.defineProperty(MessagePort.prototype, util.inspect.custom, { +Object.defineProperty(MessagePort.prototype, inspect.custom, { enumerable: false, writable: false, value: function inspect() { // eslint-disable-line func-name-matching diff --git a/lib/os.js b/lib/os.js index d6ecd29f57..af97f40e57 100644 --- a/lib/os.js +++ b/lib/os.js @@ -26,7 +26,12 @@ const constants = internalBinding('constants').os; const { deprecate } = require('internal/util'); const isWindows = process.platform === 'win32'; -const { codes: { ERR_SYSTEM_ERROR } } = require('internal/errors'); +const { + codes: { + ERR_SYSTEM_ERROR + }, + hideStackFrames +} = require('internal/errors'); const { validateInt32 } = require('internal/validators'); const { @@ -47,16 +52,14 @@ const { } = internalBinding('os'); function getCheckedFunction(fn) { - return function checkError(...args) { + return hideStackFrames(function checkError(...args) { const ctx = {}; const ret = fn(...args, ctx); if (ret === undefined) { - const err = new ERR_SYSTEM_ERROR(ctx); - Error.captureStackTrace(err, checkError); - throw err; + throw new ERR_SYSTEM_ERROR(ctx); } return ret; - }; + }); } const getHomeDirectory = getCheckedFunction(_getHomeDirectory); diff --git a/lib/readline.js b/lib/readline.js index c3484000d8..4012af8bce 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -32,7 +32,7 @@ const { ERR_INVALID_OPT_VALUE } = require('internal/errors').codes; const { validateString } = require('internal/validators'); -const { inspect } = require('util'); +const { inspect } = require('internal/util/inspect'); const { emitExperimentalWarning } = require('internal/util'); const EventEmitter = require('events'); const { diff --git a/lib/timers.js b/lib/timers.js index 1ed88f2823..dff7eb4994 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -304,14 +304,21 @@ function clearImmediate(immediate) { } module.exports = { - _unrefActive: unrefActive, - active, setTimeout, clearTimeout, setImmediate, clearImmediate, setInterval, clearInterval, + _unrefActive: deprecate( + unrefActive, + 'timers._unrefActive() is deprecated.' + + ' Please use timeout.refresh() instead.', + 'DEP0127'), + active: deprecate( + active, + 'timers.active() is deprecated. Please use timeout.refresh() instead.', + 'DEP0126'), unenroll: deprecate( unenroll, 'timers.unenroll() is deprecated. Please use clearTimeout instead.', diff --git a/lib/util.js b/lib/util.js index d087c740b0..f6f99f82b4 100644 --- a/lib/util.js +++ b/lib/util.js @@ -21,18 +21,22 @@ 'use strict'; -const errors = require('internal/errors'); +const { + codes: { + ERR_FALSY_VALUE_REJECTION, + ERR_INVALID_ARG_TYPE, + ERR_OUT_OF_RANGE + }, + errnoException, + exceptionWithHostPort, + hideStackFrames +} = require('internal/errors'); const { format, formatWithOptions, inspect } = require('internal/util/inspect'); const { debuglog } = require('internal/util/debuglog'); -const { - ERR_FALSY_VALUE_REJECTION, - ERR_INVALID_ARG_TYPE, - ERR_OUT_OF_RANGE -} = errors.codes; const { validateNumber } = require('internal/validators'); const { TextDecoder, TextEncoder } = require('internal/encoding'); const { isBuffer } = require('buffer').Buffer; @@ -158,19 +162,16 @@ function _extend(target, source) { return target; } -function callbackifyOnRejected(reason, cb) { +const callbackifyOnRejected = hideStackFrames((reason, cb) => { // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). // Because `null` is a special error value in callbacks which means "no error // occurred", we error-wrap so the callback consumer can distinguish between // "the promise rejected with null" or "the promise fulfilled with undefined". if (!reason) { - const newReason = new ERR_FALSY_VALUE_REJECTION(); - newReason.reason = reason; - reason = newReason; - Error.captureStackTrace(reason, callbackifyOnRejected); + reason = new ERR_FALSY_VALUE_REJECTION(reason); } return cb(reason); -} +}); function callbackify(original) { if (typeof original !== 'function') { @@ -209,8 +210,8 @@ function getSystemErrorName(err) { // Keep the `exports =` so that various functions can still be monkeypatched module.exports = exports = { - _errnoException: errors.errnoException, - _exceptionWithHostPort: errors.exceptionWithHostPort, + _errnoException: errnoException, + _exceptionWithHostPort: exceptionWithHostPort, _extend, callbackify, debuglog, diff --git a/lib/zlib.js b/lib/zlib.js index ec08db9f7c..9220b11b0f 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -22,12 +22,15 @@ 'use strict'; const { - ERR_BROTLI_INVALID_PARAM, - ERR_BUFFER_TOO_LARGE, - ERR_INVALID_ARG_TYPE, - ERR_OUT_OF_RANGE, - ERR_ZLIB_INITIALIZATION_FAILED, -} = require('internal/errors').codes; + codes: { + ERR_BROTLI_INVALID_PARAM, + ERR_BUFFER_TOO_LARGE, + ERR_INVALID_ARG_TYPE, + ERR_OUT_OF_RANGE, + ERR_ZLIB_INITIALIZATION_FAILED, + }, + hideStackFrames +} = require('internal/errors'); const Transform = require('_stream_transform'); const { deprecate, @@ -170,7 +173,7 @@ function zlibOnError(message, errno, code) { // 2. Returns true for finite numbers // 3. Throws ERR_INVALID_ARG_TYPE for non-numbers // 4. Throws ERR_OUT_OF_RANGE for infinite numbers -function checkFiniteNumber(number, name) { +const checkFiniteNumber = hideStackFrames((number, name) => { // Common case if (number === undefined) { return false; @@ -186,33 +189,29 @@ function checkFiniteNumber(number, name) { // Other non-numbers if (typeof number !== 'number') { - const err = new ERR_INVALID_ARG_TYPE(name, 'number', number); - Error.captureStackTrace(err, checkFiniteNumber); - throw err; + throw new ERR_INVALID_ARG_TYPE(name, 'number', number); } // Infinite numbers - const err = new ERR_OUT_OF_RANGE(name, 'a finite number', number); - Error.captureStackTrace(err, checkFiniteNumber); - throw err; -} + throw new ERR_OUT_OF_RANGE(name, 'a finite number', number); +}); // 1. Returns def for number when it's undefined or NaN // 2. Returns number for finite numbers >= lower and <= upper // 3. Throws ERR_INVALID_ARG_TYPE for non-numbers // 4. Throws ERR_OUT_OF_RANGE for infinite numbers or numbers > upper or < lower -function checkRangesOrGetDefault(number, name, lower, upper, def) { - if (!checkFiniteNumber(number, name)) { - return def; - } - if (number < lower || number > upper) { - const err = new ERR_OUT_OF_RANGE(name, - `>= ${lower} and <= ${upper}`, number); - Error.captureStackTrace(err, checkRangesOrGetDefault); - throw err; +const checkRangesOrGetDefault = hideStackFrames( + (number, name, lower, upper, def) => { + if (!checkFiniteNumber(number, name)) { + return def; + } + if (number < lower || number > upper) { + throw new ERR_OUT_OF_RANGE(name, + `>= ${lower} and <= ${upper}`, number); + } + return number; } - return number; -} +); // The base class for all Zlib-style streams. function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) { diff --git a/src/env.h b/src/env.h index 1b7022704f..4b32723281 100644 --- a/src/env.h +++ b/src/env.h @@ -74,14 +74,26 @@ namespace loader { class ModuleWrap; struct PackageConfig { - enum class Exists { Yes, No }; - enum class IsValid { Yes, No }; - enum class HasMain { Yes, No }; - - Exists exists; - IsValid is_valid; - HasMain has_main; - std::string main; + struct Exists { + enum Bool { No, Yes }; + }; + struct IsValid { + enum Bool { No, Yes }; + }; + struct HasMain { + enum Bool { No, Yes }; + }; + struct IsModule { + enum Bool { No, Yes }; + }; + struct PackageType { + enum Type : uint32_t { None = 0, CommonJS, Module }; + }; + const Exists::Bool exists; + const IsValid::Bool is_valid; + const HasMain::Bool has_main; + const std::string main; + const PackageType::Type type; }; } // namespace loader @@ -141,6 +153,7 @@ constexpr size_t kFsStatsBufferLength = kFsStatsFieldsNumber * 2; V(channel_string, "channel") \ V(chunks_sent_since_last_write_string, "chunksSentSinceLastWrite") \ V(code_string, "code") \ + V(commonjs_string, "commonjs") \ V(config_string, "config") \ V(constants_string, "constants") \ V(crypto_dsa_string, "dsa") \ diff --git a/src/inspector_socket.cc b/src/inspector_socket.cc index 161e93c0af..a7019281af 100644 --- a/src/inspector_socket.cc +++ b/src/inspector_socket.cc @@ -156,10 +156,10 @@ static void generate_accept_string(const std::string& client_key, } static std::string TrimPort(const std::string& host) { - size_t last_colon_pos = host.rfind(":"); + size_t last_colon_pos = host.rfind(':'); if (last_colon_pos == std::string::npos) return host; - size_t bracket = host.rfind("]"); + size_t bracket = host.rfind(']'); if (bracket == std::string::npos || last_colon_pos > bracket) return host.substr(0, last_colon_pos); return host; diff --git a/src/js_native_api_v8.cc b/src/js_native_api_v8.cc index 8df89f9a38..f7c6b6db4f 100644 --- a/src/js_native_api_v8.cc +++ b/src/js_native_api_v8.cc @@ -395,9 +395,7 @@ struct CallbackBundle { // This will be called when the v8::External containing `this` pointer // is being GC-ed. CallbackBundle* bundle = info.GetParameter(); - if (bundle != nullptr) { - delete bundle; - } + delete bundle; } }; @@ -1534,33 +1532,6 @@ static inline napi_status set_error_code(napi_env env, RETURN_STATUS_IF_FALSE(env, set_maybe.FromMaybe(false), napi_generic_failure); - - // now update the name to be "name [code]" where name is the - // original name and code is the code associated with the Error - v8::Local name_string; - CHECK_NEW_FROM_UTF8(env, name_string, ""); - v8::Local name_key; - CHECK_NEW_FROM_UTF8(env, name_key, "name"); - - auto maybe_name = err_object->Get(context, name_key); - if (!maybe_name.IsEmpty()) { - v8::Local name = maybe_name.ToLocalChecked(); - if (name->IsString()) { - name_string = - v8::String::Concat(isolate, name_string, name.As()); - } - } - name_string = v8::String::Concat( - isolate, name_string, NAPI_FIXED_ONE_BYTE_STRING(isolate, " [")); - name_string = - v8::String::Concat(isolate, name_string, code_value.As()); - name_string = v8::String::Concat( - isolate, name_string, NAPI_FIXED_ONE_BYTE_STRING(isolate, "]")); - - set_maybe = err_object->Set(context, name_key, name_string); - RETURN_STATUS_IF_FALSE(env, - set_maybe.FromMaybe(false), - napi_generic_failure); } return napi_ok; } diff --git a/src/module_wrap.cc b/src/module_wrap.cc index ac5d28fb23..839b5eac30 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -29,7 +29,6 @@ using v8::HandleScope; using v8::Integer; using v8::IntegrityLevel; using v8::Isolate; -using v8::JSON; using v8::Just; using v8::Local; using v8::Maybe; @@ -46,7 +45,13 @@ using v8::String; using v8::Undefined; using v8::Value; -static const char* const EXTENSIONS[] = {".mjs", ".js", ".json", ".node"}; +static const char* const EXTENSIONS[] = { + ".mjs", + ".cjs", + ".js", + ".json", + ".node" +}; ModuleWrap::ModuleWrap(Environment* env, Local object, @@ -471,100 +476,239 @@ std::string ReadFile(uv_file file) { return contents; } -enum CheckFileOptions { - LEAVE_OPEN_AFTER_CHECK, - CLOSE_AFTER_CHECK +enum DescriptorType { + FILE, + DIRECTORY, + NONE }; -Maybe CheckFile(const std::string& path, - CheckFileOptions opt = CLOSE_AFTER_CHECK) { +// When DescriptorType cache is added, this can also return +// Nothing for the "null" cache entries. +inline Maybe OpenDescriptor(const std::string& path) { uv_fs_t fs_req; - if (path.empty()) { - return Nothing(); - } - uv_file fd = uv_fs_open(nullptr, &fs_req, path.c_str(), O_RDONLY, 0, nullptr); uv_fs_req_cleanup(&fs_req); + if (fd < 0) return Nothing(); + return Just(fd); +} - if (fd < 0) { - return Nothing(); - } - - uv_fs_fstat(nullptr, &fs_req, fd, nullptr); - uint64_t is_directory = fs_req.statbuf.st_mode & S_IFDIR; +inline void CloseDescriptor(uv_file fd) { + uv_fs_t fs_req; + uv_fs_close(nullptr, &fs_req, fd, nullptr); uv_fs_req_cleanup(&fs_req); +} - if (is_directory) { - CHECK_EQ(0, uv_fs_close(nullptr, &fs_req, fd, nullptr)); +inline DescriptorType CheckDescriptorAtFile(uv_file fd) { + uv_fs_t fs_req; + int rc = uv_fs_fstat(nullptr, &fs_req, fd, nullptr); + if (rc == 0) { + uint64_t is_directory = fs_req.statbuf.st_mode & S_IFDIR; uv_fs_req_cleanup(&fs_req); - return Nothing(); + return is_directory ? DIRECTORY : FILE; } + uv_fs_req_cleanup(&fs_req); + return NONE; +} - if (opt == CLOSE_AFTER_CHECK) { - CHECK_EQ(0, uv_fs_close(nullptr, &fs_req, fd, nullptr)); - uv_fs_req_cleanup(&fs_req); - } +// TODO(@guybedford): Add a DescriptorType cache layer here. +// Should be directory based -> if path/to/dir doesn't exist +// then the cache should early-fail any path/to/dir/file check. +DescriptorType CheckDescriptorAtPath(const std::string& path) { + Maybe fd = OpenDescriptor(path); + if (fd.IsNothing()) return NONE; + DescriptorType type = CheckDescriptorAtFile(fd.FromJust()); + CloseDescriptor(fd.FromJust()); + return type; +} - return Just(fd); +Maybe ReadIfFile(const std::string& path) { + Maybe fd = OpenDescriptor(path); + if (fd.IsNothing()) return Nothing(); + DescriptorType type = CheckDescriptorAtFile(fd.FromJust()); + if (type != FILE) return Nothing(); + std::string source = ReadFile(fd.FromJust()); + CloseDescriptor(fd.FromJust()); + return Just(source); } using Exists = PackageConfig::Exists; using IsValid = PackageConfig::IsValid; using HasMain = PackageConfig::HasMain; +using PackageType = PackageConfig::PackageType; -const PackageConfig& GetPackageConfig(Environment* env, - const std::string& path) { +Maybe GetPackageConfig(Environment* env, + const std::string& path, + const URL& base) { auto existing = env->package_json_cache.find(path); if (existing != env->package_json_cache.end()) { - return existing->second; + const PackageConfig* pcfg = &existing->second; + if (pcfg->is_valid == IsValid::No) { + std::string msg = "Invalid JSON in '" + path + + "' imported from " + base.ToFilePath(); + node::THROW_ERR_INVALID_PACKAGE_CONFIG(env, msg.c_str()); + return Nothing(); + } + return Just(pcfg); } - Maybe check = CheckFile(path, LEAVE_OPEN_AFTER_CHECK); - if (check.IsNothing()) { + + Maybe source = ReadIfFile(path); + + if (source.IsNothing()) { auto entry = env->package_json_cache.emplace(path, - PackageConfig { Exists::No, IsValid::Yes, HasMain::No, "" }); - return entry.first->second; + PackageConfig { Exists::No, IsValid::Yes, HasMain::No, "", + PackageType::None }); + return Just(&entry.first->second); } + std::string pkg_src = source.FromJust(); + Isolate* isolate = env->isolate(); v8::HandleScope handle_scope(isolate); - std::string pkg_src = ReadFile(check.FromJust()); - uv_fs_t fs_req; - CHECK_EQ(0, uv_fs_close(nullptr, &fs_req, check.FromJust(), nullptr)); - uv_fs_req_cleanup(&fs_req); - - Local src; - if (!String::NewFromUtf8(isolate, - pkg_src.c_str(), - v8::NewStringType::kNormal, - pkg_src.length()).ToLocal(&src)) { - auto entry = env->package_json_cache.emplace(path, - PackageConfig { Exists::No, IsValid::Yes, HasMain::No, "" }); - return entry.first->second; - } - - Local pkg_json_v; + bool parsed = false; Local pkg_json; + { + Local src; + Local pkg_json_v; + if (String::NewFromUtf8(isolate, + pkg_src.c_str(), + v8::NewStringType::kNormal, + pkg_src.length()).ToLocal(&src) && + v8::JSON::Parse(env->context(), src).ToLocal(&pkg_json_v) && + pkg_json_v->ToObject(env->context()).ToLocal(&pkg_json)) { + parsed = true; + } + } - if (!JSON::Parse(env->context(), src).ToLocal(&pkg_json_v) || - !pkg_json_v->ToObject(env->context()).ToLocal(&pkg_json)) { - auto entry = env->package_json_cache.emplace(path, - PackageConfig { Exists::Yes, IsValid::No, HasMain::No, "" }); - return entry.first->second; + if (!parsed) { + env->package_json_cache.emplace(path, + PackageConfig { Exists::Yes, IsValid::No, HasMain::No, "", + PackageType::None }); + std::string msg = "Invalid JSON in '" + path + + "' imported from " + base.ToFilePath(); + node::THROW_ERR_INVALID_PACKAGE_CONFIG(env, msg.c_str()); + return Nothing(); } Local pkg_main; - HasMain has_main = HasMain::No; + HasMain::Bool has_main = HasMain::No; std::string main_std; if (pkg_json->Get(env->context(), env->main_string()).ToLocal(&pkg_main)) { - has_main = HasMain::Yes; + if (pkg_main->IsString()) { + has_main = HasMain::Yes; + } Utf8Value main_utf8(isolate, pkg_main); main_std.assign(std::string(*main_utf8, main_utf8.length())); } + PackageType::Type pkg_type = PackageType::None; + Local type_v; + if (pkg_json->Get(env->context(), env->type_string()).ToLocal(&type_v)) { + if (type_v->StrictEquals(env->module_string())) { + pkg_type = PackageType::Module; + } else if (type_v->StrictEquals(env->commonjs_string())) { + pkg_type = PackageType::CommonJS; + } + // ignore unknown types for forwards compatibility + } + + Local exports_v; + if (pkg_json->Get(env->context(), + env->exports_string()).ToLocal(&exports_v) && + (exports_v->IsObject() || exports_v->IsString() || + exports_v->IsBoolean())) { + Persistent exports; + exports.Reset(env->isolate(), exports_v); + + auto entry = env->package_json_cache.emplace(path, + PackageConfig { Exists::Yes, IsValid::Yes, has_main, main_std, + pkg_type }); + return Just(&entry.first->second); + } + auto entry = env->package_json_cache.emplace(path, - PackageConfig { Exists::Yes, IsValid::Yes, has_main, main_std }); - return entry.first->second; + PackageConfig { Exists::Yes, IsValid::Yes, has_main, main_std, + pkg_type }); + return Just(&entry.first->second); +} + +Maybe GetPackageScopeConfig(Environment* env, + const URL& resolved, + const URL& base) { + URL pjson_url("./package.json", &resolved); + while (true) { + Maybe pkg_cfg = + GetPackageConfig(env, pjson_url.ToFilePath(), base); + if (pkg_cfg.IsNothing()) return pkg_cfg; + if (pkg_cfg.FromJust()->exists == Exists::Yes) return pkg_cfg; + + URL last_pjson_url = pjson_url; + pjson_url = URL("../package.json", pjson_url); + + // Terminates at root where ../package.json equals ../../package.json + // (can't just check "/package.json" for Windows support). + if (pjson_url.path() == last_pjson_url.path()) { + auto entry = env->package_json_cache.emplace(pjson_url.ToFilePath(), + PackageConfig { Exists::No, IsValid::Yes, HasMain::No, "", + PackageType::None }); + const PackageConfig* pcfg = &entry.first->second; + return Just(pcfg); + } + } +} + +/* + * Legacy CommonJS main resolution: + * 1. let M = pkg_url + (json main field) + * 2. TRY(M, M.js, M.json, M.node) + * 3. TRY(M/index.js, M/index.json, M/index.node) + * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node) + * 5. NOT_FOUND + */ +inline bool FileExists(const URL& url) { + return CheckDescriptorAtPath(url.ToFilePath()) == FILE; +} +Maybe LegacyMainResolve(const URL& pjson_url, + const PackageConfig& pcfg) { + URL guess; + if (pcfg.has_main == HasMain::Yes) { + // Note: fs check redundances will be handled by Descriptor cache here. + if (FileExists(guess = URL("./" + pcfg.main, pjson_url))) { + return Just(guess); + } + if (FileExists(guess = URL("./" + pcfg.main + ".js", pjson_url))) { + return Just(guess); + } + if (FileExists(guess = URL("./" + pcfg.main + ".json", pjson_url))) { + return Just(guess); + } + if (FileExists(guess = URL("./" + pcfg.main + ".node", pjson_url))) { + return Just(guess); + } + if (FileExists(guess = URL("./" + pcfg.main + "/index.js", pjson_url))) { + return Just(guess); + } + // Such stat. + if (FileExists(guess = URL("./" + pcfg.main + "/index.json", pjson_url))) { + return Just(guess); + } + if (FileExists(guess = URL("./" + pcfg.main + "/index.node", pjson_url))) { + return Just(guess); + } + // Fallthrough. + } + if (FileExists(guess = URL("./index.js", pjson_url))) { + return Just(guess); + } + // So fs. + if (FileExists(guess = URL("./index.json", pjson_url))) { + return Just(guess); + } + if (FileExists(guess = URL("./index.node", pjson_url))) { + return Just(guess); + } + // Not found. + return Nothing(); } enum ResolveExtensionsOptions { @@ -575,17 +719,14 @@ enum ResolveExtensionsOptions { template Maybe ResolveExtensions(const URL& search) { if (options == TRY_EXACT_NAME) { - std::string filePath = search.ToFilePath(); - Maybe check = CheckFile(filePath); - if (!check.IsNothing()) { + if (FileExists(search)) { return Just(search); } } for (const char* extension : EXTENSIONS) { URL guess(search.path() + extension, &search); - Maybe check = CheckFile(guess.ToFilePath()); - if (!check.IsNothing()) { + if (FileExists(guess)) { return Just(guess); } } @@ -597,93 +738,150 @@ inline Maybe ResolveIndex(const URL& search) { return ResolveExtensions(URL("index", search)); } -Maybe ResolveMain(Environment* env, const URL& search) { - URL pkg("package.json", &search); - - const PackageConfig& pjson = - GetPackageConfig(env, pkg.ToFilePath()); - // Note invalid package.json should throw in resolver - // currently we silently ignore which is incorrect - if (pjson.exists == Exists::No || - pjson.is_valid == IsValid::No || - pjson.has_main == HasMain::No) { +Maybe FinalizeResolution(Environment* env, + const URL& resolved, + const URL& base) { + if (env->options()->es_module_specifier_resolution == "node") { + Maybe file = ResolveExtensions(resolved); + if (!file.IsNothing()) { + return file; + } + if (resolved.path().back() != '/') { + file = ResolveIndex(URL(resolved.path() + "/", &base)); + } else { + file = ResolveIndex(resolved); + } + if (!file.IsNothing()) { + return file; + } + std::string msg = "Cannot find module '" + resolved.path() + + "' imported from " + base.ToFilePath(); + node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str()); return Nothing(); } - if (!ShouldBeTreatedAsRelativeOrAbsolutePath(pjson.main)) { - return Resolve(env, "./" + pjson.main, search, IgnoreMain); + + const std::string& path = resolved.ToFilePath(); + if (CheckDescriptorAtPath(path) != FILE) { + std::string msg = "Cannot find module '" + path + + "' imported from " + base.ToFilePath(); + node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str()); + return Nothing(); } - return Resolve(env, pjson.main, search, IgnoreMain); + + return Just(resolved); } -Maybe ResolveModule(Environment* env, - const std::string& specifier, - const URL& base) { - URL parent(".", base); - URL dir(""); - do { - dir = parent; - Maybe check = - Resolve(env, "./node_modules/" + specifier, dir, CheckMain); - if (!check.IsNothing()) { - const size_t limit = specifier.find('/'); - const size_t spec_len = - limit == std::string::npos ? specifier.length() : - limit + 1; - std::string chroot = - dir.path() + "node_modules/" + specifier.substr(0, spec_len); - if (check.FromJust().path().substr(0, chroot.length()) != chroot) { - return Nothing(); +Maybe PackageMainResolve(Environment* env, + const URL& pjson_url, + const PackageConfig& pcfg, + const URL& base) { + if (pcfg.exists == Exists::Yes) { + if (pcfg.has_main == HasMain::Yes) { + URL resolved(pcfg.main, pjson_url); + const std::string& path = resolved.ToFilePath(); + if (CheckDescriptorAtPath(path) == FILE) { + return Just(resolved); + } + } + if (env->options()->es_module_specifier_resolution == "node") { + if (pcfg.has_main == HasMain::Yes) { + return FinalizeResolution(env, URL(pcfg.main, pjson_url), base); + } else { + return FinalizeResolution(env, URL("index", pjson_url), base); + } + } + if (pcfg.type != PackageType::Module) { + Maybe resolved = LegacyMainResolve(pjson_url, pcfg); + if (!resolved.IsNothing()) { + return resolved; } - return check; - } else { - // TODO(bmeck) PREVENT FALLTHROUGH } - parent = URL("..", &dir); - } while (parent.path() != dir.path()); + } + std::string msg = "Cannot find main entry point for '" + + URL(".", pjson_url).ToFilePath() + "' imported from " + + base.ToFilePath(); + node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str()); return Nothing(); } -Maybe ResolveDirectory(Environment* env, - const URL& search, - PackageMainCheck check_pjson_main) { - if (check_pjson_main) { - Maybe main = ResolveMain(env, search); - if (!main.IsNothing()) - return main; +Maybe PackageResolve(Environment* env, + const std::string& specifier, + const URL& base) { + size_t sep_index = specifier.find('/'); + if (specifier[0] == '@' && (sep_index == std::string::npos || + specifier.length() == 0)) { + std::string msg = "Invalid package name '" + specifier + + "' imported from " + base.ToFilePath(); + node::THROW_ERR_INVALID_MODULE_SPECIFIER(env, msg.c_str()); + return Nothing(); + } + bool scope = false; + if (specifier[0] == '@') { + scope = true; + sep_index = specifier.find('/', sep_index + 1); } - return ResolveIndex(search); + std::string pkg_name = specifier.substr(0, + sep_index == std::string::npos ? std::string::npos : sep_index); + std::string pkg_subpath; + if ((sep_index == std::string::npos || + sep_index == specifier.length() - 1)) { + pkg_subpath = ""; + } else { + pkg_subpath = "." + specifier.substr(sep_index); + } + URL pjson_url("./node_modules/" + pkg_name + "/package.json", &base); + std::string pjson_path = pjson_url.ToFilePath(); + std::string last_path; + do { + DescriptorType check = + CheckDescriptorAtPath(pjson_path.substr(0, pjson_path.length() - 13)); + if (check != DIRECTORY) { + last_path = pjson_path; + pjson_url = URL((scope ? + "../../../../node_modules/" : "../../../node_modules/") + + pkg_name + "/package.json", &pjson_url); + pjson_path = pjson_url.ToFilePath(); + continue; + } + + // Package match. + Maybe pcfg = GetPackageConfig(env, pjson_path, base); + // Invalid package configuration error. + if (pcfg.IsNothing()) return Nothing(); + if (!pkg_subpath.length()) { + return PackageMainResolve(env, pjson_url, *pcfg.FromJust(), base); + } else { + return FinalizeResolution(env, URL(pkg_subpath, pjson_url), base); + } + CHECK(false); + // Cross-platform root check. + } while (pjson_path.length() != last_path.length()); + + std::string msg = "Cannot find package '" + pkg_name + + "' imported from " + base.ToFilePath(); + node::THROW_ERR_MODULE_NOT_FOUND(env, msg.c_str()); + return Nothing(); } } // anonymous namespace Maybe Resolve(Environment* env, const std::string& specifier, - const URL& base, - PackageMainCheck check_pjson_main) { - URL pure_url(specifier); - if (!(pure_url.flags() & URL_FLAGS_FAILED)) { - // just check existence, without altering - Maybe check = CheckFile(pure_url.ToFilePath()); - if (check.IsNothing()) { - return Nothing(); - } - return Just(pure_url); - } - if (specifier.length() == 0) { - return Nothing(); - } + const URL& base) { + // Order swapped from spec for minor perf gain. + // Ok since relative URLs cannot parse as URLs. + URL resolved; if (ShouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { - URL resolved(specifier, base); - Maybe file = ResolveExtensions(resolved); - if (!file.IsNothing()) - return file; - if (specifier.back() != '/') { - resolved = URL(specifier + "/", base); - } - return ResolveDirectory(env, resolved, check_pjson_main); + resolved = URL(specifier, base); } else { - return ResolveModule(env, specifier, base); + URL pure_url(specifier); + if (!(pure_url.flags() & URL_FLAGS_FAILED)) { + resolved = pure_url; + } else { + return PackageResolve(env, specifier, base); + } } + return FinalizeResolution(env, resolved, base); } void ModuleWrap::Resolve(const FunctionCallbackInfo& args) { @@ -705,15 +903,40 @@ void ModuleWrap::Resolve(const FunctionCallbackInfo& args) { env, "second argument is not a URL string"); } - Maybe result = node::loader::Resolve(env, specifier_std, url); - if (result.IsNothing() || (result.FromJust().flags() & URL_FLAGS_FAILED)) { - std::string msg = "Cannot find module " + specifier_std; - return node::THROW_ERR_MISSING_MODULE(env, msg.c_str()); + Maybe result = + node::loader::Resolve(env, + specifier_std, + url); + if (result.IsNothing()) { + return; + } + + URL resolution = result.FromJust(); + CHECK(!(resolution.flags() & URL_FLAGS_FAILED)); + + Local resolution_obj; + if (resolution.ToObject(env).ToLocal(&resolution_obj)) + args.GetReturnValue().Set(resolution_obj); +} + +void ModuleWrap::GetPackageType(const FunctionCallbackInfo& args) { + Environment* env = Environment::GetCurrent(args); + + // module.getPackageType(url) + CHECK_EQ(args.Length(), 1); + + CHECK(args[0]->IsString()); + Utf8Value url_utf8(env->isolate(), args[0]); + URL url(*url_utf8, url_utf8.length()); + + PackageType::Type pkg_type = PackageType::None; + Maybe pcfg = + GetPackageScopeConfig(env, url, url); + if (!pcfg.IsNothing()) { + pkg_type = pcfg.FromJust()->type; } - MaybeLocal obj = result.FromJust().ToObject(env); - if (!obj.IsEmpty()) - args.GetReturnValue().Set(obj.ToLocalChecked()); + args.GetReturnValue().Set(Integer::New(env->isolate(), pkg_type)); } static MaybeLocal ImportModuleDynamically( @@ -849,6 +1072,7 @@ void ModuleWrap::Initialize(Local target, target->Set(env->context(), FIXED_ONE_BYTE_STRING(isolate, "ModuleWrap"), tpl->GetFunction(context).ToLocalChecked()).FromJust(); env->SetMethod(target, "resolve", Resolve); + env->SetMethod(target, "getPackageType", GetPackageType); env->SetMethod(target, "setImportModuleDynamicallyCallback", SetImportModuleDynamicallyCallback); diff --git a/src/module_wrap.h b/src/module_wrap.h index dc34685fed..6b7025f8a9 100644 --- a/src/module_wrap.h +++ b/src/module_wrap.h @@ -12,11 +12,6 @@ namespace node { namespace loader { -enum PackageMainCheck : bool { - CheckMain = true, - IgnoreMain = false -}; - enum ScriptType : int { kScript, kModule, @@ -29,11 +24,6 @@ enum HostDefinedOptions : int { kLength = 10, }; -v8::Maybe Resolve(Environment* env, - const std::string& specifier, - const url::URL& base, - PackageMainCheck read_pkg_json = CheckMain); - class ModuleWrap : public BaseObject { public: static const std::string EXTENSIONS[]; @@ -75,6 +65,7 @@ class ModuleWrap : public BaseObject { const v8::FunctionCallbackInfo& args); static void Resolve(const v8::FunctionCallbackInfo& args); + static void GetPackageType(const v8::FunctionCallbackInfo& args); static void SetImportModuleDynamicallyCallback( const v8::FunctionCallbackInfo& args); static void SetInitializeImportMetaObjectCallback( diff --git a/src/node_errors.h b/src/node_errors.h index 835794b178..9d3f2ead71 100644 --- a/src/node_errors.h +++ b/src/node_errors.h @@ -45,12 +45,14 @@ void FatalException(v8::Isolate* isolate, V(ERR_CONSTRUCT_CALL_REQUIRED, Error) \ V(ERR_INVALID_ARG_VALUE, TypeError) \ V(ERR_INVALID_ARG_TYPE, TypeError) \ + V(ERR_INVALID_MODULE_SPECIFIER, TypeError) \ + V(ERR_INVALID_PACKAGE_CONFIG, SyntaxError) \ V(ERR_INVALID_TRANSFER_OBJECT, TypeError) \ V(ERR_MEMORY_ALLOCATION_FAILED, Error) \ V(ERR_MISSING_ARGS, TypeError) \ V(ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST, TypeError) \ - V(ERR_MISSING_MODULE, Error) \ V(ERR_MISSING_PLATFORM_FOR_WORKER, Error) \ + V(ERR_MODULE_NOT_FOUND, Error) \ V(ERR_OUT_OF_RANGE, RangeError) \ V(ERR_SCRIPT_EXECUTION_INTERRUPTED, Error) \ V(ERR_SCRIPT_EXECUTION_TIMEOUT, Error) \ diff --git a/src/node_options.cc b/src/node_options.cc index 5687fb327b..ef240ef2c9 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -107,6 +107,27 @@ void EnvironmentOptions::CheckOptions(std::vector* errors) { errors->push_back("--loader requires --experimental-modules be enabled"); } + if (!module_type.empty() && !experimental_modules) { + errors->push_back("--entry-type requires" + "--experimental-modules be enabled"); + } + + if (experimental_json_modules && !experimental_modules) { + errors->push_back("--experimental-json-modules requires " + "--experimental-modules be enabled"); + } + + if (!es_module_specifier_resolution.empty()) { + if (!experimental_modules) { + errors->push_back("--es-module-specifier-resolution requires " + "--experimental-modules be enabled"); + } + if (es_module_specifier_resolution != "node" && + es_module_specifier_resolution != "explicit") { + errors->push_back("invalid value for --es-module-specifier-resolution"); + } + } + if (syntax_check_only && has_eval_string) { errors->push_back("either --check or --eval can be used, not both"); } @@ -214,6 +235,10 @@ DebugOptionsParser::DebugOptionsParser() { } EnvironmentOptionsParser::EnvironmentOptionsParser() { + AddOption("--experimental-json-modules", + "experimental JSON interop support for the ES Module loader", + &EnvironmentOptions::experimental_json_modules, + kAllowedInEnvironment); AddOption("--experimental-modules", "experimental ES Module support and caching modules", &EnvironmentOptions::experimental_modules, @@ -253,6 +278,11 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { "custom loader", &EnvironmentOptions::userland_loader, kAllowedInEnvironment); + AddOption("--es-module-specifier-resolution", + "Select extension resolution algorithm for es modules; " + "either 'explicit' (default) or 'node'", + &EnvironmentOptions::es_module_specifier_resolution, + kAllowedInEnvironment); AddOption("--no-deprecation", "silence deprecation warnings", &EnvironmentOptions::no_deprecation, @@ -271,10 +301,12 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { kAllowedInEnvironment); AddOption("--preserve-symlinks", "preserve symbolic links when resolving", - &EnvironmentOptions::preserve_symlinks); + &EnvironmentOptions::preserve_symlinks, + kAllowedInEnvironment); AddOption("--preserve-symlinks-main", "preserve symbolic links when resolving the main module", - &EnvironmentOptions::preserve_symlinks_main); + &EnvironmentOptions::preserve_symlinks_main, + kAllowedInEnvironment); AddOption("--prof-process", "process V8 profiler output generated using --prof", &EnvironmentOptions::prof_process); @@ -301,6 +333,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { "show stack traces on process warnings", &EnvironmentOptions::trace_warnings, kAllowedInEnvironment); + AddOption("--entry-type", + "top-level module type name", + &EnvironmentOptions::module_type, + kAllowedInEnvironment); AddOption("--check", "syntax check script without executing", diff --git a/src/node_options.h b/src/node_options.h index bcd6d2457d..e07ee7fb35 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -91,7 +91,10 @@ class DebugOptions : public Options { class EnvironmentOptions : public Options { public: bool abort_on_uncaught_exception = false; + bool experimental_json_modules = false; bool experimental_modules = false; + std::string es_module_specifier_resolution; + std::string module_type; std::string experimental_policy; bool experimental_repl_await = false; bool experimental_vm_modules = false; diff --git a/src/node_report.cc b/src/node_report.cc index 00d6a2454c..f9cf921143 100644 --- a/src/node_report.cc +++ b/src/node_report.cc @@ -507,7 +507,7 @@ static void PrintSystemInformation(JSONWriter* writer) { WideCharToMultiByte( CP_UTF8, 0, lpszVariable, -1, str, size, nullptr, nullptr); std::string env(str); - int sep = env.rfind("="); + int sep = env.rfind('='); std::string key = env.substr(0, sep); std::string value = env.substr(sep + 1); writer->json_keyvalue(key, value); diff --git a/src/node_worker.h b/src/node_worker.h index 9510faafe6..b23ab704b0 100644 --- a/src/node_worker.h +++ b/src/node_worker.h @@ -70,7 +70,7 @@ class Worker : public AsyncWrap { bool thread_joined_ = true; int exit_code_ = 0; uint64_t thread_id_ = -1; - uintptr_t stack_base_; + uintptr_t stack_base_ = 0; // Full size of the thread's stack. static constexpr size_t kStackSize = 4 * 1024 * 1024; diff --git a/test/addons/hello-world-esm/binding.cc b/test/addons/hello-world-esm/binding.cc deleted file mode 100644 index 02eecec099..0000000000 --- a/test/addons/hello-world-esm/binding.cc +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include - -void Method(const v8::FunctionCallbackInfo& args) { - v8::Isolate* isolate = args.GetIsolate(); - args.GetReturnValue().Set(v8::String::NewFromUtf8( - isolate, "world", v8::NewStringType::kNormal).ToLocalChecked()); -} - -void init(v8::Local exports) { - NODE_SET_METHOD(exports, "hello", Method); -} - -NODE_MODULE(NODE_GYP_MODULE_NAME, init) diff --git a/test/addons/hello-world-esm/binding.gyp b/test/addons/hello-world-esm/binding.gyp deleted file mode 100644 index 55fbe7050f..0000000000 --- a/test/addons/hello-world-esm/binding.gyp +++ /dev/null @@ -1,9 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'binding', - 'sources': [ 'binding.cc' ], - 'includes': ['../common.gypi'], - } - ] -} diff --git a/test/addons/hello-world-esm/test.js b/test/addons/hello-world-esm/test.js deleted file mode 100644 index d0faf65540..0000000000 --- a/test/addons/hello-world-esm/test.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; -const common = require('../../common'); - -const assert = require('assert'); -const { spawnSync } = require('child_process'); -const { copyFileSync } = require('fs'); -const { join } = require('path'); - -const buildDir = join(__dirname, 'build'); - -copyFileSync(join(buildDir, common.buildType, 'binding.node'), - join(buildDir, 'binding.node')); - -const result = spawnSync(process.execPath, - ['--experimental-modules', `${__dirname}/test.mjs`]); - -assert.ifError(result.error); -// TODO: Uncomment this once ESM is no longer experimental. -// assert.strictEqual(result.stderr.toString().trim(), ''); -assert.strictEqual(result.stdout.toString().trim(), 'binding.hello() = world'); diff --git a/test/addons/hello-world-esm/test.mjs b/test/addons/hello-world-esm/test.mjs deleted file mode 100644 index d98de5bf87..0000000000 --- a/test/addons/hello-world-esm/test.mjs +++ /dev/null @@ -1,6 +0,0 @@ -/* eslint-disable node-core/required-modules */ - -import assert from 'assert'; -import binding from './build/binding.node'; -assert.strictEqual(binding.hello(), 'world'); -console.log('binding.hello() =', binding.hello()); diff --git a/test/common/index.mjs b/test/common/index.mjs index de9119f37e..41592098eb 100644 --- a/test/common/index.mjs +++ b/test/common/index.mjs @@ -1,6 +1,15 @@ // Flags: --experimental-modules /* eslint-disable node-core/required-modules */ -import common from './index.js'; + +import { createRequireFromPath } from 'module'; +import { fileURLToPath as toPath } from 'url'; + +function createRequire(metaUrl) { + return createRequireFromPath(toPath(metaUrl)); +} + +const require = createRequire(import.meta.url); +const common = require('./index.js'); const { isMainThread, @@ -91,5 +100,6 @@ export { getBufferSources, disableCrashOnUnhandledRejection, getTTYfd, - runWithInvalidFD + runWithInvalidFD, + createRequire }; diff --git a/test/common/wpt.js b/test/common/wpt.js index f9e48c5f97..5592ddfd4a 100644 --- a/test/common/wpt.js +++ b/test/common/wpt.js @@ -287,11 +287,6 @@ class WPTRunner { // TODO(joyeecheung): work with the upstream to port more tests in .html // to .js. runJsTests() { - // TODO(joyeecheung): it's still under discussion whether we should leave - // err.name alone. See https://github.com/nodejs/node/issues/20253 - const internalErrors = require('internal/errors'); - internalErrors.useOriginalName = true; - let queue = []; // If the tests are run as `node test/wpt/test-something.js subset.any.js`, diff --git a/test/es-module/test-esm-basic-imports.mjs b/test/es-module/test-esm-basic-imports.mjs index 78a4106f94..d9bb22be0a 100644 --- a/test/es-module/test-esm-basic-imports.mjs +++ b/test/es-module/test-esm-basic-imports.mjs @@ -1,5 +1,6 @@ // Flags: --experimental-modules -import '../common'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; import assert from 'assert'; import ok from '../fixtures/es-modules/test-esm-ok.mjs'; import okShebang from './test-esm-shebang.mjs'; diff --git a/test/es-module/test-esm-cyclic-dynamic-import.mjs b/test/es-module/test-esm-cyclic-dynamic-import.mjs index c8dfff919c..a207efc73e 100644 --- a/test/es-module/test-esm-cyclic-dynamic-import.mjs +++ b/test/es-module/test-esm-cyclic-dynamic-import.mjs @@ -1,3 +1,4 @@ // Flags: --experimental-modules -import '../common'; -import('./test-esm-cyclic-dynamic-import'); +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; +import('./test-esm-cyclic-dynamic-import.mjs'); diff --git a/test/es-module/test-esm-double-encoding.mjs b/test/es-module/test-esm-double-encoding.mjs index c81d0530d3..9366d4bd6b 100644 --- a/test/es-module/test-esm-double-encoding.mjs +++ b/test/es-module/test-esm-double-encoding.mjs @@ -1,6 +1,7 @@ // Flags: --experimental-modules -import '../common'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; // Assert we can import files with `%` in their pathname. -import '../fixtures/es-modules/test-esm-double-encoding-native%2520.js'; +import '../fixtures/es-modules/test-esm-double-encoding-native%2520.mjs'; diff --git a/test/es-module/test-esm-dynamic-import.js b/test/es-module/test-esm-dynamic-import.js index b271d43c80..ca9c99007b 100644 --- a/test/es-module/test-esm-dynamic-import.js +++ b/test/es-module/test-esm-dynamic-import.js @@ -1,4 +1,5 @@ // Flags: --experimental-modules + 'use strict'; const common = require('../common'); const assert = require('assert'); @@ -17,7 +18,7 @@ function expectErrorProperty(result, propertyKey, value) { } function expectMissingModuleError(result) { - expectErrorProperty(result, 'code', 'MODULE_NOT_FOUND'); + expectErrorProperty(result, 'code', 'ERR_MODULE_NOT_FOUND'); } function expectOkNamespace(result) { diff --git a/test/es-module/test-esm-encoded-path.mjs b/test/es-module/test-esm-encoded-path.mjs index 365a425afa..2cabfdacff 100644 --- a/test/es-module/test-esm-encoded-path.mjs +++ b/test/es-module/test-esm-encoded-path.mjs @@ -1,5 +1,6 @@ // Flags: --experimental-modules -import '../common'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; import assert from 'assert'; // ./test-esm-ok.mjs import ok from '../fixtures/es-modules/test-%65%73%6d-ok.mjs'; diff --git a/test/es-module/test-esm-error-cache.js b/test/es-module/test-esm-error-cache.js index 98244615ef..79f76357ec 100644 --- a/test/es-module/test-esm-error-cache.js +++ b/test/es-module/test-esm-error-cache.js @@ -1,11 +1,11 @@ -'use strict'; - // Flags: --experimental-modules +'use strict'; + require('../common'); const assert = require('assert'); -const file = '../fixtures/syntax/bad_syntax.js'; +const file = '../fixtures/syntax/bad_syntax.mjs'; let error; (async () => { diff --git a/test/es-module/test-esm-forbidden-globals.mjs b/test/es-module/test-esm-forbidden-globals.mjs index 4e777412a3..cf110ff290 100644 --- a/test/es-module/test-esm-forbidden-globals.mjs +++ b/test/es-module/test-esm-forbidden-globals.mjs @@ -1,5 +1,6 @@ // Flags: --experimental-modules -import '../common'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; // eslint-disable-next-line no-undef if (typeof arguments !== 'undefined') { diff --git a/test/es-module/test-esm-import-meta.mjs b/test/es-module/test-esm-import-meta.mjs index c17e0e20d4..4c34b337fb 100644 --- a/test/es-module/test-esm-import-meta.mjs +++ b/test/es-module/test-esm-import-meta.mjs @@ -1,6 +1,7 @@ // Flags: --experimental-modules +/* eslint-disable node-core/required-modules */ -import '../common'; +import '../common/index.mjs'; import assert from 'assert'; assert.strictEqual(Object.getPrototypeOf(import.meta), null); diff --git a/test/es-module/test-esm-json-cache.mjs b/test/es-module/test-esm-json-cache.mjs new file mode 100644 index 0000000000..ecd27c5488 --- /dev/null +++ b/test/es-module/test-esm-json-cache.mjs @@ -0,0 +1,26 @@ +// Flags: --experimental-modules --experimental-json-modules +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; + +import { strictEqual, deepStrictEqual } from 'assert'; + +import { createRequireFromPath as createRequire } from 'module'; +import { fileURLToPath as fromURL } from 'url'; + +import mod from '../fixtures/es-modules/json-cache/mod.cjs'; +import another from '../fixtures/es-modules/json-cache/another.cjs'; +import test from '../fixtures/es-modules/json-cache/test.json'; + +const require = createRequire(fromURL(import.meta.url)); + +const modCjs = require('../fixtures/es-modules/json-cache/mod.cjs'); +const anotherCjs = require('../fixtures/es-modules/json-cache/another.cjs'); +const testCjs = require('../fixtures/es-modules/json-cache/test.json'); + +strictEqual(mod.one, 1); +strictEqual(another.one, 'zalgo'); +strictEqual(test.one, 'it comes'); + +deepStrictEqual(mod, modCjs); +deepStrictEqual(another, anotherCjs); +deepStrictEqual(test, testCjs); diff --git a/test/es-module/test-esm-json.mjs b/test/es-module/test-esm-json.mjs index a7146d19a9..b140d031ca 100644 --- a/test/es-module/test-esm-json.mjs +++ b/test/es-module/test-esm-json.mjs @@ -1,8 +1,9 @@ -// Flags: --experimental-modules -import '../common'; -import assert from 'assert'; -import ok from '../fixtures/es-modules/test-esm-ok.mjs'; -import json from '../fixtures/es-modules/json.json'; +// Flags: --experimental-modules --experimental-json-modules +/* eslint-disable node-core/required-modules */ -assert(ok); -assert.strictEqual(json.val, 42); +import '../common/index.mjs'; +import { strictEqual } from 'assert'; + +import secret from '../fixtures/experimental.json'; + +strictEqual(secret.ofLife, 42); diff --git a/test/es-module/test-esm-live-binding.mjs b/test/es-module/test-esm-live-binding.mjs index d151e004df..880a6c389b 100644 --- a/test/es-module/test-esm-live-binding.mjs +++ b/test/es-module/test-esm-live-binding.mjs @@ -1,6 +1,7 @@ // Flags: --experimental-modules +/* eslint-disable node-core/required-modules */ -import '../common'; +import '../common/index.mjs'; import assert from 'assert'; import fs, { readFile, readFileSync } from 'fs'; diff --git a/test/es-module/test-esm-loader-invalid-format.mjs b/test/es-module/test-esm-loader-invalid-format.mjs index f8714d4aa1..c3f3a87407 100644 --- a/test/es-module/test-esm-loader-invalid-format.mjs +++ b/test/es-module/test-esm-loader-invalid-format.mjs @@ -1,5 +1,6 @@ // Flags: --experimental-modules --loader ./test/fixtures/es-module-loaders/loader-invalid-format.mjs -import { expectsError, mustCall } from '../common'; +/* eslint-disable node-core/required-modules */ +import { expectsError, mustCall } from '../common/index.mjs'; import assert from 'assert'; import('../fixtures/es-modules/test-esm-ok.mjs') diff --git a/test/es-module/test-esm-loader-invalid-url.mjs b/test/es-module/test-esm-loader-invalid-url.mjs index 43971a2e6e..9cf17b2478 100644 --- a/test/es-module/test-esm-loader-invalid-url.mjs +++ b/test/es-module/test-esm-loader-invalid-url.mjs @@ -1,5 +1,7 @@ // Flags: --experimental-modules --loader ./test/fixtures/es-module-loaders/loader-invalid-url.mjs -import { expectsError, mustCall } from '../common'; +/* eslint-disable node-core/required-modules */ + +import { expectsError, mustCall } from '../common/index.mjs'; import assert from 'assert'; import('../fixtures/es-modules/test-esm-ok.mjs') diff --git a/test/es-module/test-esm-loader-missing-dynamic-instantiate-hook.mjs b/test/es-module/test-esm-loader-missing-dynamic-instantiate-hook.mjs index f2b37f7e8a..ab2da7adce 100644 --- a/test/es-module/test-esm-loader-missing-dynamic-instantiate-hook.mjs +++ b/test/es-module/test-esm-loader-missing-dynamic-instantiate-hook.mjs @@ -1,6 +1,7 @@ // Flags: --experimental-modules --loader ./test/fixtures/es-module-loaders/missing-dynamic-instantiate-hook.mjs +/* eslint-disable node-core/required-modules */ -import { expectsError } from '../common'; +import { expectsError } from '../common/index.mjs'; import('test').catch(expectsError({ code: 'ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK', diff --git a/test/es-module/test-esm-loader-modulemap.js b/test/es-module/test-esm-loader-modulemap.js index 946d54ffaa..5493c6c47c 100644 --- a/test/es-module/test-esm-loader-modulemap.js +++ b/test/es-module/test-esm-loader-modulemap.js @@ -7,7 +7,7 @@ const common = require('../common'); const { URL } = require('url'); -const Loader = require('internal/modules/esm/loader'); +const { Loader } = require('internal/modules/esm/loader'); const ModuleMap = require('internal/modules/esm/module_map'); const ModuleJob = require('internal/modules/esm/module_job'); const createDynamicModule = require( diff --git a/test/es-module/test-esm-loader-search.js b/test/es-module/test-esm-loader-search.js index 0ca8990cb7..b5e0d8d656 100644 --- a/test/es-module/test-esm-loader-search.js +++ b/test/es-module/test-esm-loader-search.js @@ -5,13 +5,13 @@ const common = require('../common'); -const { search } = require('internal/modules/esm/default_resolve'); +const resolve = require('internal/modules/esm/default_resolve'); common.expectsError( - () => search('target', undefined), + () => resolve('target', undefined), { - code: 'ERR_MISSING_MODULE', + code: 'ERR_MODULE_NOT_FOUND', type: Error, - message: 'Cannot find module target' + message: /Cannot find package 'target'/ } ); diff --git a/test/es-module/test-esm-main-lookup.mjs b/test/es-module/test-esm-main-lookup.mjs index ca313a1d26..19c025beab 100644 --- a/test/es-module/test-esm-main-lookup.mjs +++ b/test/es-module/test-esm-main-lookup.mjs @@ -1,6 +1,26 @@ // Flags: --experimental-modules -import '../common'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; import assert from 'assert'; -import main from '../fixtures/es-modules/pjson-main'; -assert.strictEqual(main, 'main'); +async function main() { + let mod; + try { + mod = await import('../fixtures/es-modules/pjson-main'); + } catch (e) { + assert.strictEqual(e.code, 'ERR_MODULE_NOT_FOUND'); + } + + assert.strictEqual(mod, undefined); + + try { + mod = await import('../fixtures/es-modules/pjson-main/main.mjs'); + } catch (e) { + console.log(e); + assert.fail(); + } + + assert.strictEqual(mod.main, 'main'); +} + +main(); diff --git a/test/es-module/test-esm-named-exports.mjs b/test/es-module/test-esm-named-exports.mjs index 3aae9230de..e235f598cb 100644 --- a/test/es-module/test-esm-named-exports.mjs +++ b/test/es-module/test-esm-named-exports.mjs @@ -1,5 +1,6 @@ // Flags: --experimental-modules --loader ./test/fixtures/es-module-loaders/builtin-named-exports-loader.mjs -import '../common'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; import { readFile } from 'fs'; import assert from 'assert'; import ok from '../fixtures/es-modules/test-esm-ok.mjs'; diff --git a/test/es-module/test-esm-namespace.mjs b/test/es-module/test-esm-namespace.mjs index da1286d0f4..38b7ef12d5 100644 --- a/test/es-module/test-esm-namespace.mjs +++ b/test/es-module/test-esm-namespace.mjs @@ -1,5 +1,7 @@ // Flags: --experimental-modules -import '../common'; +/* eslint-disable node-core/required-modules */ + +import '../common/index.mjs'; import * as fs from 'fs'; import assert from 'assert'; import Module from 'module'; diff --git a/test/es-module/test-esm-no-extension.js b/test/es-module/test-esm-no-extension.js new file mode 100644 index 0000000000..3e9ffb2bbc --- /dev/null +++ b/test/es-module/test-esm-no-extension.js @@ -0,0 +1,35 @@ +'use strict'; + +const common = require('../common'); +const fixtures = require('../common/fixtures'); +const { spawn } = require('child_process'); +const assert = require('assert'); + +const entry = fixtures.path('/es-modules/noext-esm'); + +// Run a module that does not have extension +// This is to ensure the --entry-type works as expected + +const child = spawn(process.execPath, [ + '--experimental-modules', + '--entry-type=module', + entry +]); + +let stderr = ''; +child.stderr.setEncoding('utf8'); +child.stderr.on('data', (data) => { + stderr += data; +}); +let stdout = ''; +child.stdout.setEncoding('utf8'); +child.stdout.on('data', (data) => { + stdout += data; +}); +child.on('close', common.mustCall((code, signal) => { + assert.strictEqual(code, 0); + assert.strictEqual(signal, null); + assert.strictEqual(stdout, 'executed\n'); + assert.strictEqual(stderr, `(node:${child.pid}) ` + + 'ExperimentalWarning: The ESM module loader is experimental.\n'); +})); diff --git a/test/es-module/test-esm-preserve-symlinks-not-found.mjs b/test/es-module/test-esm-preserve-symlinks-not-found.mjs index 5119957bae..b5be2d7e63 100644 --- a/test/es-module/test-esm-preserve-symlinks-not-found.mjs +++ b/test/es-module/test-esm-preserve-symlinks-not-found.mjs @@ -1,3 +1,3 @@ // Flags: --experimental-modules --loader ./test/fixtures/es-module-loaders/not-found-assert-loader.mjs /* eslint-disable node-core/required-modules */ -import './not-found'; +import './not-found.mjs'; diff --git a/test/es-module/test-esm-process.mjs b/test/es-module/test-esm-process.mjs index ea9b4b4936..3a23573d33 100644 --- a/test/es-module/test-esm-process.mjs +++ b/test/es-module/test-esm-process.mjs @@ -1,5 +1,6 @@ // Flags: --experimental-modules -import '../common'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; import assert from 'assert'; import process from 'process'; diff --git a/test/es-module/test-esm-require-cache.mjs b/test/es-module/test-esm-require-cache.mjs index ff32cde36f..09030e0578 100644 --- a/test/es-module/test-esm-require-cache.mjs +++ b/test/es-module/test-esm-require-cache.mjs @@ -1,7 +1,12 @@ // Flags: --experimental-modules -import '../common'; -import '../fixtures/es-module-require-cache/preload.js'; -import '../fixtures/es-module-require-cache/counter.js'; +/* eslint-disable node-core/required-modules */ +import { createRequire } from '../common/index.mjs'; import assert from 'assert'; +// +const require = createRequire(import.meta.url); + +require('../fixtures/es-module-require-cache/preload.js'); +require('../fixtures/es-module-require-cache/counter.js'); + assert.strictEqual(global.counter, 1); delete global.counter; diff --git a/test/es-module/test-esm-shared-loader-dep.mjs b/test/es-module/test-esm-shared-loader-dep.mjs index 5c274d835c..b8953ab1ec 100644 --- a/test/es-module/test-esm-shared-loader-dep.mjs +++ b/test/es-module/test-esm-shared-loader-dep.mjs @@ -1,7 +1,11 @@ // Flags: --experimental-modules --loader ./test/fixtures/es-module-loaders/loader-shared-dep.mjs -import '../common'; +/* eslint-disable node-core/required-modules */ +import { createRequire } from '../common/index.mjs'; + import assert from 'assert'; import '../fixtures/es-modules/test-esm-ok.mjs'; -import dep from '../fixtures/es-module-loaders/loader-dep.js'; -assert.strictEqual(dep.format, 'esm'); +const require = createRequire(import.meta.url); +const dep = require('../fixtures/es-module-loaders/loader-dep.js'); + +assert.strictEqual(dep.format, 'module'); diff --git a/test/es-module/test-esm-shebang.mjs b/test/es-module/test-esm-shebang.mjs index d5faace479..486e04dade 100644 --- a/test/es-module/test-esm-shebang.mjs +++ b/test/es-module/test-esm-shebang.mjs @@ -1,6 +1,7 @@ #! }]) // isn't js // Flags: --experimental-modules -import '../common'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; const isJs = true; export default isJs; diff --git a/test/es-module/test-esm-snapshot.mjs b/test/es-module/test-esm-snapshot.mjs index 3d4b44bbdd..3997e24ed7 100644 --- a/test/es-module/test-esm-snapshot.mjs +++ b/test/es-module/test-esm-snapshot.mjs @@ -1,7 +1,8 @@ // Flags: --experimental-modules -import '../common'; -import '../fixtures/es-modules/esm-snapshot-mutator'; -import one from '../fixtures/es-modules/esm-snapshot'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; +import '../fixtures/es-modules/esm-snapshot-mutator.js'; +import one from '../fixtures/es-modules/esm-snapshot.js'; import assert from 'assert'; assert.strictEqual(one, 1); diff --git a/test/es-module/test-esm-specifiers.mjs b/test/es-module/test-esm-specifiers.mjs new file mode 100644 index 0000000000..b386dcb8e9 --- /dev/null +++ b/test/es-module/test-esm-specifiers.mjs @@ -0,0 +1,35 @@ +// Flags: --experimental-modules --es-module-specifier-resolution=node +import { mustNotCall } from '../common'; +import assert from 'assert'; + +// commonJS index.js +import commonjs from '../fixtures/es-module-specifiers/package-type-commonjs'; +// esm index.js +import module from '../fixtures/es-module-specifiers/package-type-module'; +// notice the trailing slash +import success, { explicit, implicit, implicitModule, getImplicitCommonjs } + from '../fixtures/es-module-specifiers/'; + +assert.strictEqual(commonjs, 'commonjs'); +assert.strictEqual(module, 'module'); +assert.strictEqual(success, 'success'); +assert.strictEqual(explicit, 'esm'); +assert.strictEqual(implicit, 'esm'); +assert.strictEqual(implicitModule, 'esm'); + +async function main() { + try { + await import('../fixtures/es-module-specifiers/do-not-exist.js'); + } catch (e) { + // Files that do not exist should throw + assert.strictEqual(e.name, 'Error'); + } + try { + await getImplicitCommonjs(); + } catch (e) { + // Legacy loader cannot resolve .mjs automatically from main + assert.strictEqual(e.name, 'Error'); + } +} + +main().catch(mustNotCall); diff --git a/test/es-module/test-esm-symlink-main.js b/test/es-module/test-esm-symlink-main.js index f7631ef2e5..871180f5cc 100644 --- a/test/es-module/test-esm-symlink-main.js +++ b/test/es-module/test-esm-symlink-main.js @@ -9,7 +9,7 @@ const fs = require('fs'); tmpdir.refresh(); const realPath = path.resolve(__dirname, '../fixtures/es-modules/symlink.mjs'); -const symlinkPath = path.resolve(tmpdir.path, 'symlink.js'); +const symlinkPath = path.resolve(tmpdir.path, 'symlink.mjs'); try { fs.symlinkSync(realPath, symlinkPath); diff --git a/test/es-module/test-esm-symlink-type.js b/test/es-module/test-esm-symlink-type.js new file mode 100644 index 0000000000..6159ebecd1 --- /dev/null +++ b/test/es-module/test-esm-symlink-type.js @@ -0,0 +1,77 @@ +'use strict'; +const common = require('../common'); +const fixtures = require('../common/fixtures'); +const path = require('path'); +const assert = require('assert'); +const exec = require('child_process').execFile; +const fs = require('fs'); + +const tmpdir = require('../common/tmpdir'); +tmpdir.refresh(); +const tmpDir = tmpdir.path; + +// Check that running the symlink executes the target as the correct type +const symlinks = [ + { + source: 'extensionless-symlink-to-mjs-file', + target: fixtures.path('es-modules/mjs-file.mjs'), + prints: '.mjs file', + errorsWithPreserveSymlinksMain: false + }, { + source: 'extensionless-symlink-to-cjs-file', + target: fixtures.path('es-modules/cjs-file.cjs'), + prints: '.cjs file', + errorsWithPreserveSymlinksMain: false + }, { + source: 'extensionless-symlink-to-file-in-module-scope', + target: fixtures.path('es-modules/package-type-module/index.js'), + prints: 'package-type-module', + // The package scope of the symlinks' sources is commonjs, and this + // symlink's target is a .js file in a module scope, so when the scope + // is evaluated based on the source (commonjs) this esm file should error + errorsWithPreserveSymlinksMain: true + }, { + source: 'extensionless-symlink-to-file-in-explicit-commonjs-scope', + target: fixtures.path('es-modules/package-type-commonjs/index.js'), + prints: 'package-type-commonjs', + errorsWithPreserveSymlinksMain: false + }, { + source: 'extensionless-symlink-to-file-in-implicit-commonjs-scope', + target: fixtures.path('es-modules/package-without-type/index.js'), + prints: 'package-without-type', + errorsWithPreserveSymlinksMain: false + } +]; + +symlinks.forEach((symlink) => { + const mainPath = path.join(tmpDir, symlink.source); + fs.symlinkSync(symlink.target, mainPath); + + const flags = [ + '--experimental-modules', + '--experimental-modules --preserve-symlinks-main' + ]; + flags.forEach((nodeOptions) => { + const opts = { + env: Object.assign({}, process.env, { NODE_OPTIONS: nodeOptions }) + }; + exec(process.execPath, [mainPath], opts, common.mustCall( + (err, stdout) => { + if (nodeOptions.includes('--preserve-symlinks-main')) { + if (symlink.errorsWithPreserveSymlinksMain && + err.toString().includes('Error')) return; + else if (!symlink.errorsWithPreserveSymlinksMain && + stdout.includes(symlink.prints)) return; + assert.fail(`For ${JSON.stringify(symlink)}, ${ + (symlink.errorsWithPreserveSymlinksMain) ? + 'failed to error' : 'errored unexpectedly' + } with --preserve-symlinks-main`); + } else { + if (stdout.includes(symlink.prints)) return; + assert.fail(`For ${JSON.stringify(symlink)}, failed to find ` + + `${symlink.prints} in: <\n${stdout}\n>`); + } + } + )); + }); +}); diff --git a/test/es-module/test-esm-symlink.js b/test/es-module/test-esm-symlink.js index 232925a52e..9b9eb98cd9 100644 --- a/test/es-module/test-esm-symlink.js +++ b/test/es-module/test-esm-symlink.js @@ -12,8 +12,8 @@ const tmpDir = tmpdir.path; const entry = path.join(tmpDir, 'entry.mjs'); const real = path.join(tmpDir, 'index.mjs'); -const link_absolute_path = path.join(tmpDir, 'absolute'); -const link_relative_path = path.join(tmpDir, 'relative'); +const link_absolute_path = path.join(tmpDir, 'absolute.mjs'); +const link_relative_path = path.join(tmpDir, 'relative.mjs'); const link_ignore_extension = path.join(tmpDir, 'ignore_extension.json'); const link_directory = path.join(tmpDir, 'directory'); @@ -22,15 +22,13 @@ fs.writeFileSync(real, 'export default [];'); fs.writeFileSync(entry, ` import assert from 'assert'; import real from './index.mjs'; -import absolute from './absolute'; -import relative from './relative'; +import absolute from './absolute.mjs'; +import relative from './relative.mjs'; import ignoreExtension from './ignore_extension.json'; -import directory from './directory'; assert.strictEqual(absolute, real); assert.strictEqual(relative, real); assert.strictEqual(ignoreExtension, real); -assert.strictEqual(directory, real); `); try { diff --git a/test/es-module/test-esm-throw-undefined.mjs b/test/es-module/test-esm-throw-undefined.mjs index 541127eee5..97e917da5e 100644 --- a/test/es-module/test-esm-throw-undefined.mjs +++ b/test/es-module/test-esm-throw-undefined.mjs @@ -1,11 +1,13 @@ // Flags: --experimental-modules -import '../common'; +/* eslint-disable node-core/required-modules */ + +import '../common/index.mjs'; import assert from 'assert'; async function doTest() { await assert.rejects( async () => { - await import('../fixtures/es-module-loaders/throw-undefined'); + await import('../fixtures/es-module-loaders/throw-undefined.mjs'); }, (e) => e === undefined ); diff --git a/test/es-module/test-esm-type-flag-errors.js b/test/es-module/test-esm-type-flag-errors.js new file mode 100644 index 0000000000..bbdd140482 --- /dev/null +++ b/test/es-module/test-esm-type-flag-errors.js @@ -0,0 +1,53 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const exec = require('child_process').execFile; + +const mjsFile = require.resolve('../fixtures/es-modules/mjs-file.mjs'); +const cjsFile = require.resolve('../fixtures/es-modules/cjs-file.cjs'); +const packageWithoutTypeMain = + require.resolve('../fixtures/es-modules/package-without-type/index.js'); +const packageTypeCommonJsMain = + require.resolve('../fixtures/es-modules/package-type-commonjs/index.js'); +const packageTypeModuleMain = + require.resolve('../fixtures/es-modules/package-type-module/index.js'); + +// Check that running `node` without options works +expect('', mjsFile, '.mjs file'); +expect('', cjsFile, '.cjs file'); +expect('', packageTypeModuleMain, 'package-type-module'); +expect('', packageTypeCommonJsMain, 'package-type-commonjs'); +expect('', packageWithoutTypeMain, 'package-without-type'); + +// Check that running with --entry-type and no package.json "type" works +expect('--entry-type=commonjs', packageWithoutTypeMain, 'package-without-type'); +expect('--entry-type=module', packageWithoutTypeMain, 'package-without-type'); + +// Check that running with conflicting --entry-type flags throws errors +expect('--entry-type=commonjs', mjsFile, 'ERR_TYPE_MISMATCH', true); +expect('--entry-type=module', cjsFile, 'ERR_TYPE_MISMATCH', true); +expect('--entry-type=commonjs', packageTypeModuleMain, + 'ERR_TYPE_MISMATCH', true); +expect('--entry-type=module', packageTypeCommonJsMain, + 'ERR_TYPE_MISMATCH', true); + +function expect(opt = '', inputFile, want, wantsError = false) { + // TODO: Remove when --experimental-modules is unflagged + opt = `--experimental-modules ${opt}`; + const argv = [inputFile]; + const opts = { + env: Object.assign({}, process.env, { NODE_OPTIONS: opt }), + maxBuffer: 1e6, + }; + exec(process.execPath, argv, opts, common.mustCall((err, stdout, stderr) => { + if (wantsError) { + stdout = stderr; + } else { + assert.ifError(err); + } + if (stdout.includes(want)) return; + + const o = JSON.stringify(opt); + assert.fail(`For ${o}, failed to find ${want} in: <\n${stdout}\n>`); + })); +} diff --git a/test/es-module/test-esm-type-flag.mjs b/test/es-module/test-esm-type-flag.mjs new file mode 100644 index 0000000000..2f5d0b626a --- /dev/null +++ b/test/es-module/test-esm-type-flag.mjs @@ -0,0 +1,11 @@ +// Flags: --experimental-modules --entry-type=module +/* eslint-disable node-core/required-modules */ +import cjs from '../fixtures/baz.js'; +import '../common/index.mjs'; +import { message } from '../fixtures/es-modules/message.mjs'; +import assert from 'assert'; + +// Assert we loaded esm dependency as ".js" in this mode +assert.strictEqual(message, 'A message'); +// Assert we loaded CommonJS dependency +assert.strictEqual(cjs, 'perhaps I work'); diff --git a/test/fixtures/es-module-loaders/example-loader.mjs b/test/fixtures/es-module-loaders/example-loader.mjs index a7cf276d4a..d8e0ddcba3 100644 --- a/test/fixtures/es-module-loaders/example-loader.mjs +++ b/test/fixtures/es-module-loaders/example-loader.mjs @@ -29,6 +29,6 @@ export function resolve(specifier, parentModuleURL = baseURL /*, defaultResolve } return { url: resolved.href, - format: 'esm' + format: 'module' }; } diff --git a/test/fixtures/es-module-loaders/js-loader.mjs b/test/fixtures/es-module-loaders/js-loader.mjs index 2ac959a464..4b8a0fc365 100644 --- a/test/fixtures/es-module-loaders/js-loader.mjs +++ b/test/fixtures/es-module-loaders/js-loader.mjs @@ -15,6 +15,6 @@ export function resolve (specifier, base = baseURL) { const url = new URL(specifier, base).href; return { url, - format: 'esm' + format: 'module' }; } diff --git a/test/fixtures/es-module-loaders/loader-dep.js b/test/fixtures/es-module-loaders/loader-dep.js index cf821afec1..c8154ac5db 100644 --- a/test/fixtures/es-module-loaders/loader-dep.js +++ b/test/fixtures/es-module-loaders/loader-dep.js @@ -1 +1 @@ -exports.format = 'esm'; +exports.format = 'module'; diff --git a/test/fixtures/es-module-loaders/loader-invalid-url.mjs b/test/fixtures/es-module-loaders/loader-invalid-url.mjs index 12efbb5021..f653155899 100644 --- a/test/fixtures/es-module-loaders/loader-invalid-url.mjs +++ b/test/fixtures/es-module-loaders/loader-invalid-url.mjs @@ -1,3 +1,4 @@ +/* eslint-disable node-core/required-modules */ export async function resolve(specifier, parentModuleURL, defaultResolve) { if (parentModuleURL && specifier === '../fixtures/es-modules/test-esm-ok.mjs') { return { diff --git a/test/fixtures/es-module-loaders/loader-shared-dep.mjs b/test/fixtures/es-module-loaders/loader-shared-dep.mjs index 1a19e4c892..3acafcce1e 100644 --- a/test/fixtures/es-module-loaders/loader-shared-dep.mjs +++ b/test/fixtures/es-module-loaders/loader-shared-dep.mjs @@ -1,7 +1,11 @@ -import dep from './loader-dep.js'; import assert from 'assert'; +import {createRequire} from '../../common/index.mjs'; + +const require = createRequire(import.meta.url); +const dep = require('./loader-dep.js'); + export function resolve(specifier, base, defaultResolve) { - assert.strictEqual(dep.format, 'esm'); + assert.strictEqual(dep.format, 'module'); return defaultResolve(specifier, base); } diff --git a/test/fixtures/es-module-loaders/loader-with-dep.mjs b/test/fixtures/es-module-loaders/loader-with-dep.mjs index 944e6e438c..5afd3b2e21 100644 --- a/test/fixtures/es-module-loaders/loader-with-dep.mjs +++ b/test/fixtures/es-module-loaders/loader-with-dep.mjs @@ -1,4 +1,8 @@ -import dep from './loader-dep.js'; +import {createRequire} from '../../common/index.mjs'; + +const require = createRequire(import.meta.url); +const dep = require('./loader-dep.js'); + export function resolve (specifier, base, defaultResolve) { return { url: defaultResolve(specifier, base).url, diff --git a/test/fixtures/es-module-loaders/not-found-assert-loader.mjs b/test/fixtures/es-module-loaders/not-found-assert-loader.mjs index d15f294fe6..d3eebcd47e 100644 --- a/test/fixtures/es-module-loaders/not-found-assert-loader.mjs +++ b/test/fixtures/es-module-loaders/not-found-assert-loader.mjs @@ -12,11 +12,11 @@ export async function resolve (specifier, base, defaultResolve) { await defaultResolve(specifier, base); } catch (e) { - assert.strictEqual(e.code, 'MODULE_NOT_FOUND'); + assert.strictEqual(e.code, 'ERR_MODULE_NOT_FOUND'); return { format: 'builtin', url: 'fs' }; } - assert.fail(`Module resolution for ${specifier} should be throw MODULE_NOT_FOUND`); + assert.fail(`Module resolution for ${specifier} should be throw ERR_MODULE_NOT_FOUND`); } diff --git a/test/fixtures/es-module-loaders/syntax-error-import.mjs b/test/fixtures/es-module-loaders/syntax-error-import.mjs index 9cad68c7ce..3a6bc5effc 100644 --- a/test/fixtures/es-module-loaders/syntax-error-import.mjs +++ b/test/fixtures/es-module-loaders/syntax-error-import.mjs @@ -1 +1 @@ -import { foo, notfound } from './module-named-exports'; +import { foo, notfound } from './module-named-exports.mjs'; diff --git a/test/fixtures/es-module-loaders/throw-undefined.mjs b/test/fixtures/es-module-loaders/throw-undefined.mjs index f062276767..0349ae112d 100644 --- a/test/fixtures/es-module-loaders/throw-undefined.mjs +++ b/test/fixtures/es-module-loaders/throw-undefined.mjs @@ -1,3 +1,4 @@ 'use strict'; +/* eslint-disable node-core/required-modules */ throw undefined; diff --git a/test/fixtures/es-module-specifiers/index.mjs b/test/fixtures/es-module-specifiers/index.mjs new file mode 100644 index 0000000000..2be7048513 --- /dev/null +++ b/test/fixtures/es-module-specifiers/index.mjs @@ -0,0 +1,10 @@ +import explicit from 'explicit-main'; +import implicit from 'implicit-main'; +import implicitModule from 'implicit-main-type-module'; + +function getImplicitCommonjs () { + return import('implicit-main-type-commonjs'); +} + +export {explicit, implicit, implicitModule, getImplicitCommonjs}; +export default 'success'; diff --git a/test/fixtures/es-module-specifiers/node_modules/explicit-main/entry.mjs b/test/fixtures/es-module-specifiers/node_modules/explicit-main/entry.mjs new file mode 100644 index 0000000000..914e3a97d5 --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/explicit-main/entry.mjs @@ -0,0 +1 @@ +export default 'esm'; diff --git a/test/fixtures/es-module-specifiers/node_modules/explicit-main/package.json b/test/fixtures/es-module-specifiers/node_modules/explicit-main/package.json new file mode 100644 index 0000000000..e9457582ac --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/explicit-main/package.json @@ -0,0 +1,3 @@ +{ + "main": "entry.mjs" +} \ No newline at end of file diff --git a/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-commonjs/entry.mjs b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-commonjs/entry.mjs new file mode 100644 index 0000000000..914e3a97d5 --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-commonjs/entry.mjs @@ -0,0 +1 @@ +export default 'esm'; diff --git a/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-commonjs/package.json b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-commonjs/package.json new file mode 100644 index 0000000000..663dad4f46 --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-commonjs/package.json @@ -0,0 +1,4 @@ +{ + "main": "entry", + "type": "commonjs" +} \ No newline at end of file diff --git a/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-module/entry.js b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-module/entry.js new file mode 100644 index 0000000000..5d7af588fd --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-module/entry.js @@ -0,0 +1 @@ +export default 'nope'; diff --git a/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-module/entry.mjs b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-module/entry.mjs new file mode 100644 index 0000000000..914e3a97d5 --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-module/entry.mjs @@ -0,0 +1 @@ +export default 'esm'; diff --git a/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-module/package.json b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-module/package.json new file mode 100644 index 0000000000..c34ab42042 --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/implicit-main-type-module/package.json @@ -0,0 +1,4 @@ +{ + "main": "entry", + "type": "module" +} \ No newline at end of file diff --git a/test/fixtures/es-module-specifiers/node_modules/implicit-main/entry.js b/test/fixtures/es-module-specifiers/node_modules/implicit-main/entry.js new file mode 100644 index 0000000000..b2825bd3c9 --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/implicit-main/entry.js @@ -0,0 +1 @@ +module.exports = 'cjs'; diff --git a/test/fixtures/es-module-specifiers/node_modules/implicit-main/entry.mjs b/test/fixtures/es-module-specifiers/node_modules/implicit-main/entry.mjs new file mode 100644 index 0000000000..914e3a97d5 --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/implicit-main/entry.mjs @@ -0,0 +1 @@ +export default 'esm'; diff --git a/test/fixtures/es-module-specifiers/node_modules/implicit-main/package.json b/test/fixtures/es-module-specifiers/node_modules/implicit-main/package.json new file mode 100644 index 0000000000..bf2e35593b --- /dev/null +++ b/test/fixtures/es-module-specifiers/node_modules/implicit-main/package.json @@ -0,0 +1,3 @@ +{ + "main": "entry" +} \ No newline at end of file diff --git a/test/fixtures/es-module-specifiers/package-type-commonjs/a.js b/test/fixtures/es-module-specifiers/package-type-commonjs/a.js new file mode 100644 index 0000000000..2e7700bc63 --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-commonjs/a.js @@ -0,0 +1 @@ +module.exports = 'a'; diff --git a/test/fixtures/es-module-specifiers/package-type-commonjs/b.mjs b/test/fixtures/es-module-specifiers/package-type-commonjs/b.mjs new file mode 100644 index 0000000000..137b8ce642 --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-commonjs/b.mjs @@ -0,0 +1 @@ +export const b = 'b'; diff --git a/test/fixtures/es-module-specifiers/package-type-commonjs/c.cjs b/test/fixtures/es-module-specifiers/package-type-commonjs/c.cjs new file mode 100644 index 0000000000..2d5312952f --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-commonjs/c.cjs @@ -0,0 +1,5 @@ +module.exports = { + one: 1, + two: 2, + three: 3 +}; diff --git a/test/fixtures/es-module-specifiers/package-type-commonjs/index.mjs b/test/fixtures/es-module-specifiers/package-type-commonjs/index.mjs new file mode 100644 index 0000000000..ef2b30b19b --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-commonjs/index.mjs @@ -0,0 +1,21 @@ +// js file that is common.js +import a from './a.js'; +// ESM with named export +import {b} from './b.mjs'; +// import 'c.cjs'; +import cjs from './c.cjs'; +// proves cross boundary fun bits +import jsAsEsm from '../package-type-module/a.js'; + +// named export from core +import {strictEqual, deepStrictEqual} from 'assert'; + +strictEqual(a, jsAsEsm); +strictEqual(b, 'b'); +deepStrictEqual(cjs, { + one: 1, + two: 2, + three: 3 +}); + +export default 'commonjs'; diff --git a/test/fixtures/es-module-specifiers/package-type-commonjs/package.json b/test/fixtures/es-module-specifiers/package-type-commonjs/package.json new file mode 100644 index 0000000000..5bbefffbab --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-commonjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/test/fixtures/es-module-specifiers/package-type-module/a.js b/test/fixtures/es-module-specifiers/package-type-module/a.js new file mode 100644 index 0000000000..90bd54cd7f --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-module/a.js @@ -0,0 +1 @@ +export default 'a' diff --git a/test/fixtures/es-module-specifiers/package-type-module/b.mjs b/test/fixtures/es-module-specifiers/package-type-module/b.mjs new file mode 100644 index 0000000000..137b8ce642 --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-module/b.mjs @@ -0,0 +1 @@ +export const b = 'b'; diff --git a/test/fixtures/es-module-specifiers/package-type-module/c.cjs b/test/fixtures/es-module-specifiers/package-type-module/c.cjs new file mode 100644 index 0000000000..2d5312952f --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-module/c.cjs @@ -0,0 +1,5 @@ +module.exports = { + one: 1, + two: 2, + three: 3 +}; diff --git a/test/fixtures/es-module-specifiers/package-type-module/index.js b/test/fixtures/es-module-specifiers/package-type-module/index.js new file mode 100644 index 0000000000..a8baacb7c9 --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-module/index.js @@ -0,0 +1,21 @@ +// ESM with only default +import a from './a.js'; +// ESM with named export +import {b} from './b.mjs'; +// import 'c.cjs'; +import cjs from './c.cjs'; +// import across boundaries +import jsAsCjs from '../package-type-commonjs/a.js' + +// named export from core +import {strictEqual, deepStrictEqual} from 'assert'; + +strictEqual(a, jsAsCjs); +strictEqual(b, 'b'); +deepStrictEqual(cjs, { + one: 1, + two: 2, + three: 3 +}); + +export default 'module'; diff --git a/test/fixtures/es-module-specifiers/package-type-module/package.json b/test/fixtures/es-module-specifiers/package-type-module/package.json new file mode 100644 index 0000000000..3dbc1ca591 --- /dev/null +++ b/test/fixtures/es-module-specifiers/package-type-module/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/test/fixtures/es-module-specifiers/package.json b/test/fixtures/es-module-specifiers/package.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/test/fixtures/es-module-specifiers/package.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/test/fixtures/es-modules/cjs-file.cjs b/test/fixtures/es-modules/cjs-file.cjs new file mode 100644 index 0000000000..3d0637686e --- /dev/null +++ b/test/fixtures/es-modules/cjs-file.cjs @@ -0,0 +1 @@ +console.log('.cjs file'); diff --git a/test/fixtures/es-modules/json-cache/another.cjs b/test/fixtures/es-modules/json-cache/another.cjs new file mode 100644 index 0000000000..8c8e9f1c0f --- /dev/null +++ b/test/fixtures/es-modules/json-cache/another.cjs @@ -0,0 +1,7 @@ +const test = require('./test.json'); + +module.exports = { + ...test +}; + +test.one = 'it comes'; diff --git a/test/fixtures/es-modules/json-cache/mod.cjs b/test/fixtures/es-modules/json-cache/mod.cjs new file mode 100644 index 0000000000..047cfb24a4 --- /dev/null +++ b/test/fixtures/es-modules/json-cache/mod.cjs @@ -0,0 +1,7 @@ +const test = require('./test.json'); + +module.exports = { + ...test +}; + +test.one = 'zalgo'; diff --git a/test/fixtures/es-modules/json-cache/test.json b/test/fixtures/es-modules/json-cache/test.json new file mode 100644 index 0000000000..120cbb2840 --- /dev/null +++ b/test/fixtures/es-modules/json-cache/test.json @@ -0,0 +1,5 @@ +{ + "one": 1, + "two": 2, + "three": 3 +} diff --git a/test/fixtures/es-modules/json.json b/test/fixtures/es-modules/json.json deleted file mode 100644 index 8288d42e2b..0000000000 --- a/test/fixtures/es-modules/json.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "val": 42 -} diff --git a/test/fixtures/es-modules/loop.mjs b/test/fixtures/es-modules/loop.mjs index 1b5cab10ed..3d2ddd2eb7 100644 --- a/test/fixtures/es-modules/loop.mjs +++ b/test/fixtures/es-modules/loop.mjs @@ -1,4 +1,4 @@ -import { message } from './message'; +import { message } from './message.mjs'; var t = 1; var k = 1; diff --git a/test/fixtures/es-modules/mjs-file.mjs b/test/fixtures/es-modules/mjs-file.mjs new file mode 100644 index 0000000000..489d4ab570 --- /dev/null +++ b/test/fixtures/es-modules/mjs-file.mjs @@ -0,0 +1 @@ +console.log('.mjs file'); diff --git a/test/fixtures/es-modules/noext-esm b/test/fixtures/es-modules/noext-esm new file mode 100644 index 0000000000..251d6e538a --- /dev/null +++ b/test/fixtures/es-modules/noext-esm @@ -0,0 +1,2 @@ +export default 'module'; +console.log('executed'); diff --git a/test/fixtures/es-modules/package-type-commonjs/index.js b/test/fixtures/es-modules/package-type-commonjs/index.js new file mode 100644 index 0000000000..009431d851 --- /dev/null +++ b/test/fixtures/es-modules/package-type-commonjs/index.js @@ -0,0 +1,3 @@ +const identifier = 'package-type-commonjs'; +console.log(identifier); +module.exports = identifier; diff --git a/test/fixtures/es-modules/package-type-commonjs/package.json b/test/fixtures/es-modules/package-type-commonjs/package.json new file mode 100644 index 0000000000..4aaa4a2388 --- /dev/null +++ b/test/fixtures/es-modules/package-type-commonjs/package.json @@ -0,0 +1,4 @@ +{ + "type": "commonjs", + "main": "index.js" +} diff --git a/test/fixtures/es-modules/package-type-module/index.js b/test/fixtures/es-modules/package-type-module/index.js new file mode 100644 index 0000000000..12aba970ef --- /dev/null +++ b/test/fixtures/es-modules/package-type-module/index.js @@ -0,0 +1,3 @@ +const identifier = 'package-type-module'; +console.log(identifier); +export default identifier; diff --git a/test/fixtures/es-modules/package-type-module/package.json b/test/fixtures/es-modules/package-type-module/package.json new file mode 100644 index 0000000000..07aec65d5a --- /dev/null +++ b/test/fixtures/es-modules/package-type-module/package.json @@ -0,0 +1,4 @@ +{ + "type": "module", + "main": "index.js" +} diff --git a/test/fixtures/es-modules/package-without-type/index.js b/test/fixtures/es-modules/package-without-type/index.js new file mode 100644 index 0000000000..a547216cb0 --- /dev/null +++ b/test/fixtures/es-modules/package-without-type/index.js @@ -0,0 +1,3 @@ +const identifier = 'package-without-type'; +console.log(identifier); +module.exports = identifier; diff --git a/test/fixtures/es-modules/package-without-type/package.json b/test/fixtures/es-modules/package-without-type/package.json new file mode 100644 index 0000000000..14ab704d8f --- /dev/null +++ b/test/fixtures/es-modules/package-without-type/package.json @@ -0,0 +1,3 @@ +{ + "main": "index.js" +} diff --git a/test/fixtures/es-modules/pjson-main/main.js b/test/fixtures/es-modules/pjson-main/main.js deleted file mode 100644 index dfdd47b877..0000000000 --- a/test/fixtures/es-modules/pjson-main/main.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'main'; diff --git a/test/fixtures/es-modules/pjson-main/main.mjs b/test/fixtures/es-modules/pjson-main/main.mjs new file mode 100644 index 0000000000..9eb0aade18 --- /dev/null +++ b/test/fixtures/es-modules/pjson-main/main.mjs @@ -0,0 +1 @@ +export const main = 'main' diff --git a/test/fixtures/es-modules/pjson-main/package.json b/test/fixtures/es-modules/pjson-main/package.json index c13b8cf6ac..ea9b784692 100644 --- a/test/fixtures/es-modules/pjson-main/package.json +++ b/test/fixtures/es-modules/pjson-main/package.json @@ -1,3 +1,3 @@ { - "main": "main.js" + "main": "main.mjs" } diff --git a/test/fixtures/es-modules/test-esm-double-encoding-native%20.js b/test/fixtures/es-modules/test-esm-double-encoding-native%20.mjs similarity index 86% rename from test/fixtures/es-modules/test-esm-double-encoding-native%20.js rename to test/fixtures/es-modules/test-esm-double-encoding-native%20.mjs index ea1caa81be..a3bfe972e5 100644 --- a/test/fixtures/es-modules/test-esm-double-encoding-native%20.js +++ b/test/fixtures/es-modules/test-esm-double-encoding-native%20.mjs @@ -3,4 +3,4 @@ // Trivial test to assert we can load files with `%` in their pathname. // Imported by `test-esm-double-encoding.mjs`. -module.exports = 42; +export default 42; diff --git a/test/fixtures/experimental.json b/test/fixtures/experimental.json new file mode 100644 index 0000000000..12611d2385 --- /dev/null +++ b/test/fixtures/experimental.json @@ -0,0 +1,3 @@ +{ + "ofLife": 42 +} diff --git a/test/fixtures/syntax/bad_syntax.mjs b/test/fixtures/syntax/bad_syntax.mjs new file mode 100644 index 0000000000..c2cd118b23 --- /dev/null +++ b/test/fixtures/syntax/bad_syntax.mjs @@ -0,0 +1 @@ +var foo bar; diff --git a/test/js-native-api/test_error/test.js b/test/js-native-api/test_error/test.js index d4b1d8a971..e7e0ded476 100644 --- a/test/js-native-api/test_error/test.js +++ b/test/js-native-api/test_error/test.js @@ -118,18 +118,18 @@ error = test_error.createErrorCode(); assert.ok(error instanceof Error, 'expected error to be an instance of Error'); assert.strictEqual(error.code, 'ERR_TEST_CODE'); assert.strictEqual(error.message, 'Error [error]'); -assert.strictEqual(error.name, 'Error [ERR_TEST_CODE]'); +assert.strictEqual(error.name, 'Error'); error = test_error.createRangeErrorCode(); assert.ok(error instanceof RangeError, 'expected error to be an instance of RangeError'); assert.strictEqual(error.message, 'RangeError [range error]'); assert.strictEqual(error.code, 'ERR_TEST_CODE'); -assert.strictEqual(error.name, 'RangeError [ERR_TEST_CODE]'); +assert.strictEqual(error.name, 'RangeError'); error = test_error.createTypeErrorCode(); assert.ok(error instanceof TypeError, 'expected error to be an instance of TypeError'); assert.strictEqual(error.message, 'TypeError [type error]'); assert.strictEqual(error.code, 'ERR_TEST_CODE'); -assert.strictEqual(error.name, 'TypeError [ERR_TEST_CODE]'); +assert.strictEqual(error.name, 'TypeError'); diff --git a/test/message/esm_display_syntax_error.out b/test/message/esm_display_syntax_error.out index 1c68ecb952..5e82a1e1ee 100644 --- a/test/message/esm_display_syntax_error.out +++ b/test/message/esm_display_syntax_error.out @@ -2,6 +2,7 @@ file:///*/test/message/esm_display_syntax_error.mjs:3 await async () => 0; ^^^^^ + SyntaxError: Unexpected reserved word - at internal/modules/esm/translators.js:*:* + at Loader.moduleStrategy (internal/modules/esm/translators.js:*:*) at async link (internal/modules/esm/module_job.js:*:*) diff --git a/test/message/esm_display_syntax_error_import.mjs b/test/message/esm_display_syntax_error_import.mjs index 87cedf1d4e..12d10270e9 100644 --- a/test/message/esm_display_syntax_error_import.mjs +++ b/test/message/esm_display_syntax_error_import.mjs @@ -1,7 +1,7 @@ // Flags: --experimental-modules -/* eslint-disable no-unused-vars */ -import '../common'; +/* eslint-disable no-unused-vars, node-core/required-modules */ +import '../common/index.mjs'; import { foo, notfound -} from '../fixtures/es-module-loaders/module-named-exports'; +} from '../fixtures/es-module-loaders/module-named-exports.mjs'; diff --git a/test/message/esm_display_syntax_error_import.out b/test/message/esm_display_syntax_error_import.out index edbbde9f2d..a3601d6cb4 100644 --- a/test/message/esm_display_syntax_error_import.out +++ b/test/message/esm_display_syntax_error_import.out @@ -2,7 +2,7 @@ file:///*/test/message/esm_display_syntax_error_import.mjs:6 notfound ^^^^^^^^ -SyntaxError: The requested module '../fixtures/es-module-loaders/module-named-exports' does not provide an export named 'notfound' +SyntaxError: The requested module '../fixtures/es-module-loaders/module-named-exports.mjs' does not provide an export named 'notfound' at ModuleJob._instantiate (internal/modules/esm/module_job.js:*:*) at async ModuleJob.run (internal/modules/esm/module_job.js:*:*) at async Loader.import (internal/modules/esm/loader.js:*:*) diff --git a/test/message/esm_display_syntax_error_import_module.mjs b/test/message/esm_display_syntax_error_import_module.mjs index 32c0edb350..a53bbbcd19 100644 --- a/test/message/esm_display_syntax_error_import_module.mjs +++ b/test/message/esm_display_syntax_error_import_module.mjs @@ -1,3 +1,4 @@ // Flags: --experimental-modules -import '../common'; -import '../fixtures/es-module-loaders/syntax-error-import'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; +import '../fixtures/es-module-loaders/syntax-error-import.mjs'; diff --git a/test/message/esm_display_syntax_error_import_module.out b/test/message/esm_display_syntax_error_import_module.out index 0512a9ac77..0daaeff5b9 100644 --- a/test/message/esm_display_syntax_error_import_module.out +++ b/test/message/esm_display_syntax_error_import_module.out @@ -1,8 +1,8 @@ (node:*) ExperimentalWarning: The ESM module loader is experimental. file:///*/test/fixtures/es-module-loaders/syntax-error-import.mjs:1 -import { foo, notfound } from './module-named-exports'; +import { foo, notfound } from './module-named-exports.mjs'; ^^^^^^^^ -SyntaxError: The requested module './module-named-exports' does not provide an export named 'notfound' +SyntaxError: The requested module './module-named-exports.mjs' does not provide an export named 'notfound' at ModuleJob._instantiate (internal/modules/esm/module_job.js:*:*) at async ModuleJob.run (internal/modules/esm/module_job.js:*:*) at async Loader.import (internal/modules/esm/loader.js:*:*) diff --git a/test/message/esm_display_syntax_error_module.mjs b/test/message/esm_display_syntax_error_module.mjs index e74b70bec8..5905d2a954 100644 --- a/test/message/esm_display_syntax_error_module.mjs +++ b/test/message/esm_display_syntax_error_module.mjs @@ -1,3 +1,4 @@ // Flags: --experimental-modules -import '../common'; -import '../fixtures/es-module-loaders/syntax-error'; +/* eslint-disable node-core/required-modules */ +import '../common/index.mjs'; +import '../fixtures/es-module-loaders/syntax-error.mjs'; diff --git a/test/message/esm_display_syntax_error_module.out b/test/message/esm_display_syntax_error_module.out index 4e4cbf2ea3..a1498f72c9 100644 --- a/test/message/esm_display_syntax_error_module.out +++ b/test/message/esm_display_syntax_error_module.out @@ -2,5 +2,6 @@ file:///*/test/fixtures/es-module-loaders/syntax-error.mjs:2 await async () => 0; ^^^^^ + SyntaxError: Unexpected reserved word - at internal/modules/esm/translators.js:*:* + at Loader.moduleStrategy (internal/modules/esm/translators.js:*:*) \ No newline at end of file diff --git a/test/parallel/test-assert-async.js b/test/parallel/test-assert-async.js index f148c7e3d8..c2b4220617 100644 --- a/test/parallel/test-assert-async.js +++ b/test/parallel/test-assert-async.js @@ -13,7 +13,7 @@ const promises = []; const rejectingFn = async () => assert.fail(); const errObj = { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: 'Failed' }; // `assert.rejects` accepts a function or a promise as first argument. @@ -38,7 +38,7 @@ const promises = []; promise = assert.rejects(() => {}, common.mustNotCall()); promises.push(assert.rejects(promise, { - name: 'TypeError [ERR_INVALID_RETURN_VALUE]', + name: 'TypeError', code: 'ERR_INVALID_RETURN_VALUE', message: 'Expected instance of Promise to be returned ' + 'from the "promiseFn" function but got type undefined.' @@ -75,7 +75,7 @@ promises.push(assert.rejects( message: 'Expected instance of Promise to be returned ' + 'from the "promiseFn" function but got instance of Map.', code: 'ERR_INVALID_RETURN_VALUE', - name: 'TypeError [ERR_INVALID_RETURN_VALUE]' + name: 'TypeError' })); promises.push(assert.doesNotReject(async () => {})); promises.push(assert.doesNotReject(Promise.resolve())); diff --git a/test/parallel/test-assert-deep.js b/test/parallel/test-assert-deep.js index 407334d0ca..5b71173478 100644 --- a/test/parallel/test-assert-deep.js +++ b/test/parallel/test-assert-deep.js @@ -778,7 +778,7 @@ assert.throws( assert.throws( () => assert.notDeepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14)), { - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: 'Expected "actual" not to be strictly deep-equal to: ' + util.inspect(new Date(2000, 3, 14)) } @@ -790,35 +790,35 @@ assert.throws( () => assert.deepStrictEqual(/ab/, /a/), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${defaultMsgStartFull}\n\n+ /ab/\n- /a/` }); assert.throws( () => assert.deepStrictEqual(/a/g, /a/), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${defaultMsgStartFull}\n\n+ /a/g\n- /a/` }); assert.throws( () => assert.deepStrictEqual(/a/i, /a/), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${defaultMsgStartFull}\n\n+ /a/i\n- /a/` }); assert.throws( () => assert.deepStrictEqual(/a/m, /a/), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${defaultMsgStartFull}\n\n+ /a/m\n- /a/` }); assert.throws( () => assert.deepStrictEqual(/a/igm, /a/im), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${defaultMsgStartFull}\n\n+ /a/gim\n- /a/im\n ^` }); @@ -844,14 +844,14 @@ assert.deepStrictEqual({ a: 4, b: '2' }, { a: 4, b: '2' }); assert.throws(() => assert.deepStrictEqual([4], ['4']), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${defaultMsgStartFull}\n\n [\n+ 4\n- '4'\n ]` }); assert.throws( () => assert.deepStrictEqual({ a: 4 }, { a: 4, b: true }), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${defaultMsgStartFull}\n\n ` + '{\n a: 4,\n- b: true\n }' }); @@ -859,7 +859,7 @@ assert.throws( () => assert.deepStrictEqual(['a'], { 0: 'a' }), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${defaultMsgStartFull}\n\n` + "+ [\n+ 'a'\n+ ]\n- {\n- '0': 'a'\n- }" }); @@ -953,7 +953,7 @@ assert.deepStrictEqual(obj1, obj2); () => assert.deepStrictEqual(a, b), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: /\.\.\./g } ); @@ -977,7 +977,7 @@ assert.throws( () => assert.deepStrictEqual([1, 2, 3], [1, 2]), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${defaultMsgStartFull}\n\n` + ' [\n' + ' 1,\n' + @@ -1063,7 +1063,7 @@ assert.throws( () => assert.deepStrictEqual(a, b), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: /a: \[Getter: 5]\n- a: \[Getter: 6]\n / } ); diff --git a/test/parallel/test-assert-fail-deprecation.js b/test/parallel/test-assert-fail-deprecation.js index 97cba760e0..5f51d27e3c 100644 --- a/test/parallel/test-assert-fail-deprecation.js +++ b/test/parallel/test-assert-fail-deprecation.js @@ -15,7 +15,7 @@ assert.throws(() => { assert.fail('first', 'second'); }, { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: '\'first\' != \'second\'', operator: '!=', actual: 'first', @@ -28,7 +28,7 @@ assert.throws(() => { assert.fail('ignored', 'ignored', 'another custom message'); }, { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: 'another custom message', operator: 'fail', actual: 'ignored', @@ -49,7 +49,7 @@ assert.throws(() => { assert.fail('first', 'second', undefined, 'operator'); }, { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: '\'first\' operator \'second\'', operator: 'operator', actual: 'first', diff --git a/test/parallel/test-assert-fail.js b/test/parallel/test-assert-fail.js index 4410cc8544..51c69372dd 100644 --- a/test/parallel/test-assert-fail.js +++ b/test/parallel/test-assert-fail.js @@ -8,7 +8,7 @@ assert.throws( () => { assert.fail(); }, { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: 'Failed', operator: 'fail', actual: undefined, @@ -22,7 +22,7 @@ assert.throws(() => { assert.fail('custom message'); }, { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: 'custom message', operator: 'fail', actual: undefined, diff --git a/test/parallel/test-assert-first-line.js b/test/parallel/test-assert-first-line.js index 32eadbf741..f9d4a8b06c 100644 --- a/test/parallel/test-assert-first-line.js +++ b/test/parallel/test-assert-first-line.js @@ -9,7 +9,7 @@ const { path } = require('../common/fixtures'); assert.throws( () => require(path('assert-first-line')), { - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: "The expression evaluated to a falsy value:\n\n ässört.ok('')\n" } ); @@ -17,7 +17,7 @@ assert.throws( assert.throws( () => require(path('assert-long-line')), { - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: "The expression evaluated to a falsy value:\n\n assert.ok('')\n" } ); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 5bca70a01d..4c2b1f978d 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -73,7 +73,7 @@ assert.throws( () => a.notStrictEqual(2, 2), { message: 'Expected "actual" to be strictly unequal to: 2', - name: 'AssertionError [ERR_ASSERTION]' + name: 'AssertionError' } ); @@ -82,7 +82,7 @@ assert.throws( { message: 'Expected "actual" to be strictly unequal to: ' + `'${'a '.repeat(30)}'`, - name: 'AssertionError [ERR_ASSERTION]' + name: 'AssertionError' } ); @@ -141,7 +141,7 @@ assert.throws(() => thrower(TypeError)); assert.throws( () => a.doesNotThrow(() => thrower(Error), 'user message'), { - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', code: 'ERR_ASSERTION', operator: 'doesNotThrow', message: 'Got unwanted exception: user message\n' + @@ -400,7 +400,7 @@ assert.throws(() => { () => new assert.AssertionError(input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "options" argument must be of type Object. ' + `Received type ${typeof input}` }); @@ -411,7 +411,7 @@ assert.throws( () => assert.strictEqual(new Error('foo'), new Error('foobar')), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: 'Expected "actual" to be reference-equal to "expected":\n' + '+ actual - expected\n\n' + '+ [Error: foo]\n- [Error: foobar]' @@ -438,7 +438,7 @@ assert.throws( () => assert(...[]), { message: 'No value argument passed to `assert.ok()`', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', generatedMessage: true } ); @@ -446,7 +446,7 @@ assert.throws( () => a(), { message: 'No value argument passed to `assert.ok()`', - name: 'AssertionError [ERR_ASSERTION]' + name: 'AssertionError' } ); @@ -886,7 +886,7 @@ common.expectsError( () => assert.throws(errFn, errObj), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${start}\n${actExp}\n\n` + ' Comparison {\n' + ' code: 404,\n' + @@ -903,7 +903,7 @@ common.expectsError( () => assert.throws(errFn, errObj), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: `${start}\n${actExp}\n\n` + ' Comparison {\n' + '+ code: 404,\n' + @@ -938,7 +938,7 @@ common.expectsError( assert.throws( () => assert.throws(() => { throw new TypeError('e'); }, new Error('e')), { - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', code: 'ERR_ASSERTION', message: `${start}\n${actExp}\n\n` + ' Comparison {\n' + @@ -951,7 +951,7 @@ common.expectsError( assert.throws( () => assert.throws(() => { throw new Error('foo'); }, new Error('')), { - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', code: 'ERR_ASSERTION', generatedMessage: true, message: `${start}\n${actExp}\n\n` + @@ -969,7 +969,7 @@ common.expectsError( // eslint-disable-next-line no-throw-literal () => a.doesNotThrow(() => { throw undefined; }), { - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', code: 'ERR_ASSERTION', message: 'Got unwanted exception.\nActual message: "undefined"' } @@ -1102,7 +1102,7 @@ assert.throws( () => assert.strictEqual('test test', 'test foobar'), { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: strictEqualMessageStart + '+ actual - expected\n\n' + "+ 'test test'\n" + @@ -1119,7 +1119,7 @@ assert.throws( }, { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: 'Expected "actual" not to be reference-equal to "expected": {}' } ); @@ -1131,7 +1131,7 @@ assert.throws( }, { code: 'ERR_ASSERTION', - name: 'AssertionError [ERR_ASSERTION]', + name: 'AssertionError', message: 'Expected "actual" not to be reference-equal to "expected":\n\n' + '{\n a: true\n}\n' } diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index cc5692b24b..ddf2edd896 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -967,12 +967,12 @@ common.expectsError( }); assert.throws(() => Buffer.from(), { - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The first argument must be one of type string, Buffer, ' + 'ArrayBuffer, Array, or Array-like Object. Received type undefined' }); assert.throws(() => Buffer.from(null), { - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The first argument must be one of type string, Buffer, ' + 'ArrayBuffer, Array, or Array-like Object. Received type object' }); diff --git a/test/parallel/test-buffer-arraybuffer.js b/test/parallel/test-buffer-arraybuffer.js index 2a1ce14107..699d13e955 100644 --- a/test/parallel/test-buffer-arraybuffer.js +++ b/test/parallel/test-buffer-arraybuffer.js @@ -42,7 +42,7 @@ assert.throws(function() { Buffer.from(new AB()); }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The first argument must be one of type string, Buffer,' + ' ArrayBuffer, Array, or Array-like Object. Received type object' }); @@ -65,12 +65,12 @@ assert.throws(function() { assert.throws(() => Buffer.from(ab.buffer, 6), { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: '"offset" is outside of buffer bounds' }); assert.throws(() => Buffer.from(ab.buffer, 3, 6), { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: '"length" is outside of buffer bounds' }); } @@ -93,12 +93,12 @@ assert.throws(function() { assert.throws(() => Buffer(ab.buffer, 6), { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: '"offset" is outside of buffer bounds' }); assert.throws(() => Buffer(ab.buffer, 3, 6), { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: '"length" is outside of buffer bounds' }); } @@ -120,7 +120,7 @@ assert.throws(function() { Buffer.from(ab, Infinity); }, { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: '"offset" is outside of buffer bounds' }); } @@ -142,7 +142,7 @@ assert.throws(function() { Buffer.from(ab, 0, Infinity); }, { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: '"length" is outside of buffer bounds' }); } diff --git a/test/parallel/test-buffer-read.js b/test/parallel/test-buffer-read.js index 7b3b9eb8e2..7ab04d3eb3 100644 --- a/test/parallel/test-buffer-read.js +++ b/test/parallel/test-buffer-read.js @@ -54,12 +54,12 @@ read(buf, 'readUIntLE', [2, 2], 0xea48); // Error name and message const OOR_ERROR = { - name: 'RangeError [ERR_OUT_OF_RANGE]' + name: 'RangeError' }; const OOB_ERROR = { - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: 'Attempt to write outside buffer bounds' }; diff --git a/test/parallel/test-buffer-readdouble.js b/test/parallel/test-buffer-readdouble.js index a61ab352c1..09556dc640 100644 --- a/test/parallel/test-buffer-readdouble.js +++ b/test/parallel/test-buffer-readdouble.js @@ -116,7 +116,7 @@ assert.strictEqual(buffer.readDoubleLE(0), -Infinity); () => buffer[fn](offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be >= 0 and <= 0. Received ${offset}` }); @@ -126,7 +126,7 @@ assert.strictEqual(buffer.readDoubleLE(0), -Infinity); () => Buffer.alloc(1)[fn](1), { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: 'Attempt to write outside buffer bounds' }); @@ -135,7 +135,7 @@ assert.strictEqual(buffer.readDoubleLE(0), -Infinity); () => buffer[fn](offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); diff --git a/test/parallel/test-buffer-readfloat.js b/test/parallel/test-buffer-readfloat.js index e6bb779804..720b16462a 100644 --- a/test/parallel/test-buffer-readfloat.js +++ b/test/parallel/test-buffer-readfloat.js @@ -79,7 +79,7 @@ assert.strictEqual(buffer.readFloatLE(0), -Infinity); () => buffer[fn](offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be >= 0 and <= 0. Received ${offset}` }); @@ -89,7 +89,7 @@ assert.strictEqual(buffer.readFloatLE(0), -Infinity); () => Buffer.alloc(1)[fn](1), { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: 'Attempt to write outside buffer bounds' }); @@ -98,7 +98,7 @@ assert.strictEqual(buffer.readFloatLE(0), -Infinity); () => buffer[fn](offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); diff --git a/test/parallel/test-buffer-readint.js b/test/parallel/test-buffer-readint.js index 971dd3bb95..8758652b28 100644 --- a/test/parallel/test-buffer-readint.js +++ b/test/parallel/test-buffer-readint.js @@ -18,7 +18,7 @@ const assert = require('assert'); () => buffer[`read${fn}`](o), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' }); }); @@ -27,7 +27,7 @@ const assert = require('assert'); () => buffer[`read${fn}`](offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]' + name: 'RangeError' }); }); @@ -36,7 +36,7 @@ const assert = require('assert'); () => buffer[`read${fn}`](offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); @@ -152,7 +152,7 @@ const assert = require('assert'); () => buffer[fn](0, byteLength), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "byteLength" is out of range. ' + `It must be an integer. Received ${byteLength}` }); @@ -167,7 +167,7 @@ const assert = require('assert'); () => buffer[fn](o, i), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' }); }); @@ -176,7 +176,7 @@ const assert = require('assert'); () => buffer[fn](offset, i), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be >= 0 and <= ${8 - i}. Received ${offset}` }); @@ -187,7 +187,7 @@ const assert = require('assert'); () => buffer[fn](offset, i), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); diff --git a/test/parallel/test-buffer-readuint.js b/test/parallel/test-buffer-readuint.js index f532febd0f..31e32bc3df 100644 --- a/test/parallel/test-buffer-readuint.js +++ b/test/parallel/test-buffer-readuint.js @@ -18,7 +18,7 @@ const assert = require('assert'); () => buffer[`read${fn}`](o), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' }); }); @@ -27,7 +27,7 @@ const assert = require('assert'); () => buffer[`read${fn}`](offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]' + name: 'RangeError' }); }); @@ -36,7 +36,7 @@ const assert = require('assert'); () => buffer[`read${fn}`](offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); @@ -120,7 +120,7 @@ const assert = require('assert'); () => buffer[fn](0, byteLength), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "byteLength" is out of range. ' + `It must be an integer. Received ${byteLength}` }); @@ -135,7 +135,7 @@ const assert = require('assert'); () => buffer[fn](o, i), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' }); }); @@ -144,7 +144,7 @@ const assert = require('assert'); () => buffer[fn](offset, i), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be >= 0 and <= ${8 - i}. Received ${offset}` }); @@ -155,7 +155,7 @@ const assert = require('assert'); () => buffer[fn](offset, i), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); diff --git a/test/parallel/test-buffer-slow.js b/test/parallel/test-buffer-slow.js index c9f5f17841..1dbc217bda 100644 --- a/test/parallel/test-buffer-slow.js +++ b/test/parallel/test-buffer-slow.js @@ -42,7 +42,7 @@ try { // Should throw with invalid length type const bufferInvalidTypeMsg = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: /^The "size" argument must be of type number/, }; assert.throws(() => SlowBuffer(), bufferInvalidTypeMsg); @@ -53,7 +53,7 @@ assert.throws(() => SlowBuffer(true), bufferInvalidTypeMsg); // Should throw with invalid length value const bufferMaxSizeMsg = { code: 'ERR_INVALID_OPT_VALUE', - name: 'RangeError [ERR_INVALID_OPT_VALUE]', + name: 'RangeError', message: /^The value "[^"]*" is invalid for option "size"$/ }; assert.throws(() => SlowBuffer(NaN), bufferMaxSizeMsg); diff --git a/test/parallel/test-buffer-writedouble.js b/test/parallel/test-buffer-writedouble.js index 8a17d53690..4bb7fe7e56 100644 --- a/test/parallel/test-buffer-writedouble.js +++ b/test/parallel/test-buffer-writedouble.js @@ -98,7 +98,7 @@ assert.ok(Number.isNaN(buffer.readDoubleLE(8))); () => small[fn](11.11, 0), { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: 'Attempt to write outside buffer bounds' }); @@ -113,7 +113,7 @@ assert.ok(Number.isNaN(buffer.readDoubleLE(8))); () => buffer[fn](23, offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be >= 0 and <= 8. Received ${offset}` }); @@ -124,7 +124,7 @@ assert.ok(Number.isNaN(buffer.readDoubleLE(8))); () => buffer[fn](42, offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); diff --git a/test/parallel/test-buffer-writefloat.js b/test/parallel/test-buffer-writefloat.js index 4c2c7539ea..cd198b01ef 100644 --- a/test/parallel/test-buffer-writefloat.js +++ b/test/parallel/test-buffer-writefloat.js @@ -80,7 +80,7 @@ assert.ok(Number.isNaN(buffer.readFloatLE(4))); () => small[fn](11.11, 0), { code: 'ERR_BUFFER_OUT_OF_BOUNDS', - name: 'RangeError [ERR_BUFFER_OUT_OF_BOUNDS]', + name: 'RangeError', message: 'Attempt to write outside buffer bounds' }); @@ -96,7 +96,7 @@ assert.ok(Number.isNaN(buffer.readFloatLE(4))); () => buffer[fn](23, offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be >= 0 and <= 4. Received ${offset}` } @@ -108,7 +108,7 @@ assert.ok(Number.isNaN(buffer.readFloatLE(4))); () => buffer[fn](42, offset), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); diff --git a/test/parallel/test-buffer-writeint.js b/test/parallel/test-buffer-writeint.js index 0e5b4960ab..7dba14211c 100644 --- a/test/parallel/test-buffer-writeint.js +++ b/test/parallel/test-buffer-writeint.js @@ -205,7 +205,7 @@ const errorOutOfBounds = common.expectsError({ () => data[fn](42, 0, byteLength), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "byteLength" is out of range. ' + `It must be an integer. Received ${byteLength}` }); @@ -223,7 +223,7 @@ const errorOutOfBounds = common.expectsError({ data[fn](val, 0, i); }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "value" is out of range. ' + `It must be >= ${min} and <= ${max}. Received ${val}` }); @@ -234,7 +234,7 @@ const errorOutOfBounds = common.expectsError({ () => data[fn](min, o, i), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' }); }); @@ -243,7 +243,7 @@ const errorOutOfBounds = common.expectsError({ () => data[fn](min, offset, i), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be >= 0 and <= ${8 - i}. Received ${offset}` }); @@ -254,7 +254,7 @@ const errorOutOfBounds = common.expectsError({ () => data[fn](max, offset, i), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); diff --git a/test/parallel/test-buffer-writeuint.js b/test/parallel/test-buffer-writeuint.js index 387aafd335..cd50000442 100644 --- a/test/parallel/test-buffer-writeuint.js +++ b/test/parallel/test-buffer-writeuint.js @@ -162,7 +162,7 @@ const assert = require('assert'); () => data[fn](42, 0, byteLength), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "byteLength" is out of range. ' + `It must be an integer. Received ${byteLength}` }); @@ -176,7 +176,7 @@ const assert = require('assert'); data[fn](val, 0, i); }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "value" is out of range. ' + `It must be >= 0 and <= ${val - 1}. Received ${val}` }); @@ -186,7 +186,7 @@ const assert = require('assert'); () => data[fn](23, o, i), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' }); }); @@ -195,7 +195,7 @@ const assert = require('assert'); () => data[fn](val - 1, offset, i), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be >= 0 and <= ${8 - i}. Received ${offset}` }); @@ -206,7 +206,7 @@ const assert = require('assert'); () => data[fn](val - 1, offset, i), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be an integer. Received ${offset}` }); diff --git a/test/parallel/test-child-process-fork.js b/test/parallel/test-child-process-fork.js index 5fee2892f3..44d22ab211 100644 --- a/test/parallel/test-child-process-fork.js +++ b/test/parallel/test-child-process-fork.js @@ -39,18 +39,18 @@ n.on('message', (m) => { // https://github.com/joyent/node/issues/2355 - JSON.stringify(undefined) // returns "undefined" but JSON.parse() cannot parse that... assert.throws(() => n.send(undefined), { - name: 'TypeError [ERR_MISSING_ARGS]', + name: 'TypeError', message: 'The "message" argument must be specified', code: 'ERR_MISSING_ARGS' }); assert.throws(() => n.send(), { - name: 'TypeError [ERR_MISSING_ARGS]', + name: 'TypeError', message: 'The "message" argument must be specified', code: 'ERR_MISSING_ARGS' }); assert.throws(() => n.send(Symbol()), { - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "message" argument must be one of type string,' + ' object, number, or boolean. Received type symbol', code: 'ERR_INVALID_ARG_TYPE' diff --git a/test/parallel/test-cli-syntax-piped-bad.js b/test/parallel/test-cli-syntax-piped-bad.js index 4fb24b24f3..f342a7834f 100644 --- a/test/parallel/test-cli-syntax-piped-bad.js +++ b/test/parallel/test-cli-syntax-piped-bad.js @@ -8,24 +8,45 @@ const node = process.execPath; // Test both sets of arguments that check syntax const syntaxArgs = [ - ['-c'], - ['--check'] + '-c', + '--check' ]; // Match on the name of the `Error` but not the message as it is different // depending on the JavaScript engine. -const syntaxErrorRE = /^SyntaxError: \b/m; +const syntaxErrorRE = /^SyntaxError: Unexpected identifier\b/m; // Should throw if code piped from stdin with --check has bad syntax // loop each possible option, `-c` or `--check` -syntaxArgs.forEach(function(args) { +syntaxArgs.forEach(function(arg) { const stdin = 'var foo bar;'; - const c = spawnSync(node, args, { encoding: 'utf8', input: stdin }); + const c = spawnSync(node, [arg], { encoding: 'utf8', input: stdin }); // stderr should include '[stdin]' as the filename assert(c.stderr.startsWith('[stdin]'), `${c.stderr} starts with ${stdin}`); - // No stdout or stderr should be produced + // no stdout should be produced + assert.strictEqual(c.stdout, ''); + + // stderr should have a syntax error message + assert(syntaxErrorRE.test(c.stderr), `${syntaxErrorRE} === ${c.stderr}`); + + assert.strictEqual(c.status, 1); +}); + +// Check --entry-type=module +syntaxArgs.forEach(function(arg) { + const stdin = 'export var p = 5; var foo bar;'; + const c = spawnSync( + node, + ['--experimental-modules', '--entry-type=module', '--no-warnings', arg], + { encoding: 'utf8', input: stdin } + ); + + // stderr should include '[stdin]' as the filename + assert(c.stderr.startsWith('[stdin]'), `${c.stderr} starts with ${stdin}`); + + // no stdout should be produced assert.strictEqual(c.stdout, ''); // stderr should have a syntax error message diff --git a/test/parallel/test-cli-syntax-piped-good.js b/test/parallel/test-cli-syntax-piped-good.js index cdadf449d8..b2b02172cb 100644 --- a/test/parallel/test-cli-syntax-piped-good.js +++ b/test/parallel/test-cli-syntax-piped-good.js @@ -8,15 +8,31 @@ const node = process.execPath; // Test both sets of arguments that check syntax const syntaxArgs = [ - ['-c'], - ['--check'] + '-c', + '--check' ]; // Should not execute code piped from stdin with --check. // Loop each possible option, `-c` or `--check`. -syntaxArgs.forEach(function(args) { +syntaxArgs.forEach(function(arg) { const stdin = 'throw new Error("should not get run");'; - const c = spawnSync(node, args, { encoding: 'utf8', input: stdin }); + const c = spawnSync(node, [arg], { encoding: 'utf8', input: stdin }); + + // No stdout or stderr should be produced + assert.strictEqual(c.stdout, ''); + assert.strictEqual(c.stderr, ''); + + assert.strictEqual(c.status, 0); +}); + +// Check --entry-type=module +syntaxArgs.forEach(function(arg) { + const stdin = 'export var p = 5; throw new Error("should not get run");'; + const c = spawnSync( + node, + ['--experimental-modules', '--no-warnings', '--entry-type=module', arg], + { encoding: 'utf8', input: stdin } + ); // No stdout or stderr should be produced assert.strictEqual(c.stdout, ''); diff --git a/test/parallel/test-console.js b/test/parallel/test-console.js index 87ee8ad1ff..65e1645f7b 100644 --- a/test/parallel/test-console.js +++ b/test/parallel/test-console.js @@ -193,6 +193,9 @@ console.assert(false, '%s should', 'console.assert', 'not throw'); assert.strictEqual(errStrings[errStrings.length - 1], 'Assertion failed: console.assert should not throw\n'); +console.assert(false); +assert.strictEqual(errStrings[errStrings.length - 1], 'Assertion failed\n'); + console.assert(true, 'this should not throw'); console.assert(true); diff --git a/test/parallel/test-crypto-pbkdf2.js b/test/parallel/test-crypto-pbkdf2.js index db12cf14fc..4e3c4f64f0 100644 --- a/test/parallel/test-crypto-pbkdf2.js +++ b/test/parallel/test-crypto-pbkdf2.js @@ -64,7 +64,7 @@ assert.throws( () => crypto.pbkdf2('password', 'salt', 1, 20, null), { code: 'ERR_INVALID_CALLBACK', - name: 'TypeError [ERR_INVALID_CALLBACK]' + name: 'TypeError' } ); @@ -72,7 +72,7 @@ assert.throws( () => crypto.pbkdf2Sync('password', 'salt', -1, 20, 'sha1'), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "iterations" is out of range. ' + 'It must be >= 0 && < 4294967296. Received -1' } @@ -84,7 +84,7 @@ assert.throws( crypto.pbkdf2Sync('password', 'salt', 1, notNumber, 'sha256'); }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "keylen" argument must be of type number. ' + `Received type ${typeof notNumber}` }); @@ -97,7 +97,7 @@ assert.throws( common.mustNotCall()); }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "keylen" is out of range. It ' + `must be an integer. Received ${input}` }); @@ -110,7 +110,7 @@ assert.throws( common.mustNotCall()); }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "keylen" is out of range. It ' + `must be >= 0 && < 4294967296. Received ${input}` }); @@ -124,7 +124,7 @@ assert.throws( () => crypto.pbkdf2('password', 'salt', 8, 8, common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "digest" argument must be one of type string or null. ' + 'Received type undefined' }); @@ -133,7 +133,7 @@ assert.throws( () => crypto.pbkdf2Sync('password', 'salt', 8, 8), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "digest" argument must be one of type string or null. ' + 'Received type undefined' }); @@ -145,7 +145,7 @@ assert.throws( () => crypto.pbkdf2(input, 'salt', 8, 8, 'sha256', common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "password" argument must be one of type string, ${msgPart2}` } ); @@ -154,7 +154,7 @@ assert.throws( () => crypto.pbkdf2('pass', input, 8, 8, 'sha256', common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "salt" argument must be one of type string, ${msgPart2}` } ); @@ -163,7 +163,7 @@ assert.throws( () => crypto.pbkdf2Sync(input, 'salt', 8, 8, 'sha256'), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "password" argument must be one of type string, ${msgPart2}` } ); @@ -172,7 +172,7 @@ assert.throws( () => crypto.pbkdf2Sync('pass', input, 8, 8, 'sha256'), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "salt" argument must be one of type string, ${msgPart2}` } ); @@ -184,7 +184,7 @@ assert.throws( () => crypto.pbkdf2('pass', 'salt', i, 8, 'sha256', common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "iterations" argument must be of type number. ${received}` } ); @@ -193,7 +193,7 @@ assert.throws( () => crypto.pbkdf2Sync('pass', 'salt', i, 8, 'sha256'), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "iterations" argument must be of type number. ${received}` } ); @@ -226,7 +226,7 @@ assert.throws( () => crypto.pbkdf2('pass', 'salt', 8, 8, 'md55', common.mustNotCall()), { code: 'ERR_CRYPTO_INVALID_DIGEST', - name: 'TypeError [ERR_CRYPTO_INVALID_DIGEST]', + name: 'TypeError', message: 'Invalid digest: md55' } ); @@ -235,7 +235,7 @@ assert.throws( () => crypto.pbkdf2Sync('pass', 'salt', 8, 8, 'md55'), { code: 'ERR_CRYPTO_INVALID_DIGEST', - name: 'TypeError [ERR_CRYPTO_INVALID_DIGEST]', + name: 'TypeError', message: 'Invalid digest: md55' } ); diff --git a/test/parallel/test-crypto-random.js b/test/parallel/test-crypto-random.js index deacb45e8f..668607b439 100644 --- a/test/parallel/test-crypto-random.js +++ b/test/parallel/test-crypto-random.js @@ -44,7 +44,7 @@ common.expectWarning('DeprecationWarning', [undefined, null, false, true, {}, []].forEach((value) => { const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "size" argument must be of type number. ' + `Received type ${typeof value}` }; @@ -55,7 +55,7 @@ common.expectWarning('DeprecationWarning', [-1, NaN, 2 ** 32].forEach((value) => { const errObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "size" is out of range. It must be >= 0 && <= ' + `${kMaxPossibleLength}. Received ${value}` }; @@ -199,7 +199,7 @@ common.expectWarning('DeprecationWarning', const typeErrObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "offset" argument must be of type number. ' + 'Received type string' }; @@ -222,7 +222,7 @@ common.expectWarning('DeprecationWarning', [NaN, kMaxPossibleLength + 1, -10, (-1 >>> 0) + 1].forEach((offsetSize) => { const errObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + `It must be >= 0 && <= 10. Received ${offsetSize}` }; @@ -245,7 +245,7 @@ common.expectWarning('DeprecationWarning', const rangeErrObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "size + offset" is out of range. ' + 'It must be <= 10. Received 11' }; @@ -265,7 +265,7 @@ assert.throws( () => crypto.randomBytes((-1 >>> 0) + 1), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "size" is out of range. ' + `It must be >= 0 && <= ${kMaxPossibleLength}. Received 4294967296` } diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index da4e8aa331..ca7f2986e1 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -323,7 +323,7 @@ common.expectsError( const type = typeof input; const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "algorithm" argument must be of type string. ' + `Received type ${type}` }; @@ -350,7 +350,7 @@ common.expectsError( const type = typeof input; const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "key" argument must be one of type string, Buffer, ' + `TypedArray, DataView, or KeyObject. Received type ${type}` }; diff --git a/test/parallel/test-dgram-send-address-types.js b/test/parallel/test-dgram-send-address-types.js index 0d208cfdc8..7f4bcf53eb 100644 --- a/test/parallel/test-dgram-send-address-types.js +++ b/test/parallel/test-dgram-send-address-types.js @@ -25,7 +25,7 @@ const client = dgram.createSocket('udp4').bind(0, () => { [[], 1, true].forEach((invalidInput) => { const expectedError = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "address" argument must be one of type string or falsy. ' + `Received type ${typeof invalidInput}` }; diff --git a/test/parallel/test-dgram-sendto.js b/test/parallel/test-dgram-sendto.js index 3922ccbb64..6eea4894b1 100644 --- a/test/parallel/test-dgram-sendto.js +++ b/test/parallel/test-dgram-sendto.js @@ -6,7 +6,7 @@ const socket = dgram.createSocket('udp4'); const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "offset" argument must be of type number. Received type ' + 'undefined' }; diff --git a/test/parallel/test-dns-setservers-type-check.js b/test/parallel/test-dns-setservers-type-check.js index 256c029427..bdf52a32e0 100644 --- a/test/parallel/test-dns-setservers-type-check.js +++ b/test/parallel/test-dns-setservers-type-check.js @@ -19,7 +19,7 @@ const promiseResolver = new dns.promises.Resolver(); ].forEach((val) => { const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "servers" argument must be of type Array. Received type ' + typeof val }; @@ -59,7 +59,7 @@ const promiseResolver = new dns.promises.Resolver(); ].forEach((val) => { const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "servers[0]" argument must be of type string. ' + `Received type ${typeof val[0]}` }; diff --git a/test/parallel/test-dns.js b/test/parallel/test-dns.js index b96055ba4d..f974c2afa6 100644 --- a/test/parallel/test-dns.js +++ b/test/parallel/test-dns.js @@ -81,7 +81,7 @@ assert(existing.length > 0); dns.setServers([serv]); }, { - name: 'TypeError [ERR_INVALID_IP_ADDRESS]', + name: 'TypeError', code: 'ERR_INVALID_IP_ADDRESS' } ); diff --git a/test/parallel/test-error-serdes.js b/test/parallel/test-error-serdes.js index e9d91e5736..908e81977b 100644 --- a/test/parallel/test-error-serdes.js +++ b/test/parallel/test-error-serdes.js @@ -41,6 +41,6 @@ assert.strictEqual(cycle(Function), '[Function: Function]'); { const err = new ERR_INVALID_ARG_TYPE('object', 'Object', 42); assert(/^TypeError \[ERR_INVALID_ARG_TYPE\]:/.test(err)); - assert.strictEqual(err.name, 'TypeError [ERR_INVALID_ARG_TYPE]'); + assert.strictEqual(err.name, 'TypeError'); assert.strictEqual(err.code, 'ERR_INVALID_ARG_TYPE'); } diff --git a/test/parallel/test-errors-systemerror.js b/test/parallel/test-errors-systemerror.js index 0b5f9b9a10..e801871f40 100644 --- a/test/parallel/test-errors-systemerror.js +++ b/test/parallel/test-errors-systemerror.js @@ -6,7 +6,7 @@ const assert = require('assert'); const { E, SystemError, codes } = require('internal/errors'); assert.throws( - () => { throw new SystemError(); }, + () => { new SystemError(); }, { name: 'TypeError', message: 'Cannot read property \'match\' of undefined' @@ -29,7 +29,7 @@ const { ERR_TEST } = codes; () => { throw new ERR_TEST(ctx); }, { code: 'ERR_TEST', - name: 'SystemError [ERR_TEST]', + name: 'SystemError', message: 'custom message: syscall_test returned ETEST (code message)' + ' /str => /str2', info: ctx @@ -49,7 +49,7 @@ const { ERR_TEST } = codes; () => { throw new ERR_TEST(ctx); }, { code: 'ERR_TEST', - name: 'SystemError [ERR_TEST]', + name: 'SystemError', message: 'custom message: syscall_test returned ETEST (code message)' + ' /buf => /str2', info: ctx @@ -69,7 +69,7 @@ const { ERR_TEST } = codes; () => { throw new ERR_TEST(ctx); }, { code: 'ERR_TEST', - name: 'SystemError [ERR_TEST]', + name: 'SystemError', message: 'custom message: syscall_test returned ETEST (code message)' + ' /buf => /buf2', info: ctx @@ -121,12 +121,12 @@ const { ERR_TEST } = codes; assert.throws( () => { const err = new ERR_TEST(ctx); - err.name = 'SystemError [CUSTOM_ERR_TEST]'; + err.name = 'Foobar'; throw err; }, { code: 'ERR_TEST', - name: 'SystemError [CUSTOM_ERR_TEST]', + name: 'Foobar', message: 'custom message: syscall_test returned ERR_TEST ' + '(Error occurred)', info: ctx diff --git a/test/parallel/test-fs-chmod.js b/test/parallel/test-fs-chmod.js index 81a117f771..cc8caf86fd 100644 --- a/test/parallel/test-fs-chmod.js +++ b/test/parallel/test-fs-chmod.js @@ -150,7 +150,7 @@ if (fs.lchmod) { [false, 1, {}, [], null, undefined].forEach((input) => { const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "path" argument must be one of type string, Buffer, or URL.' + ` Received type ${typeof input}` }; diff --git a/test/parallel/test-fs-close-errors.js b/test/parallel/test-fs-close-errors.js index 48af5eb485..42d990410f 100644 --- a/test/parallel/test-fs-close-errors.js +++ b/test/parallel/test-fs-close-errors.js @@ -10,7 +10,7 @@ const fs = require('fs'); ['', false, null, undefined, {}, []].forEach((input) => { const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "fd" argument must be of type number. ' + `Received type ${typeof input}` }; diff --git a/test/parallel/test-fs-fchmod.js b/test/parallel/test-fs-fchmod.js index 06f4c0b272..ebbc2792e1 100644 --- a/test/parallel/test-fs-fchmod.js +++ b/test/parallel/test-fs-fchmod.js @@ -11,7 +11,7 @@ const fs = require('fs'); [false, null, undefined, {}, [], ''].forEach((input) => { const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "fd" argument must be of type number. Received type ' + typeof input }; @@ -23,7 +23,7 @@ const fs = require('fs'); [false, null, undefined, {}, [], '', '123x'].forEach((input) => { const errObj = { code: 'ERR_INVALID_ARG_VALUE', - name: 'TypeError [ERR_INVALID_ARG_VALUE]', + name: 'TypeError', message: 'The argument \'mode\' must be a 32-bit unsigned integer or an ' + `octal string. Received ${util.inspect(input)}` }; @@ -34,7 +34,7 @@ const fs = require('fs'); [-1, 2 ** 32].forEach((input) => { const errObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "fd" is out of range. It must be >= 0 && <= ' + `2147483647. Received ${input}` }; @@ -45,7 +45,7 @@ const fs = require('fs'); [-1, 2 ** 32].forEach((input) => { const errObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "mode" is out of range. It must be >= 0 && <= ' + `4294967295. Received ${input}` }; @@ -57,7 +57,7 @@ const fs = require('fs'); [NaN, Infinity].forEach((input) => { const errObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "fd" is out of range. It must be an integer. ' + `Received ${input}` }; @@ -71,7 +71,7 @@ const fs = require('fs'); [1.5].forEach((input) => { const errObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "fd" is out of range. It must be an integer. ' + `Received ${input}` }; diff --git a/test/parallel/test-fs-fchown.js b/test/parallel/test-fs-fchown.js index 500c06a47c..832dd071ea 100644 --- a/test/parallel/test-fs-fchown.js +++ b/test/parallel/test-fs-fchown.js @@ -18,7 +18,7 @@ function test(input, errObj) { ['', false, null, undefined, {}, []].forEach((input) => { const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "fd" argument must be of type number. Received type ' + typeof input }; @@ -28,7 +28,7 @@ function test(input, errObj) { [Infinity, NaN].forEach((input) => { const errObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "fd" is out of range. It must be an integer. ' + `Received ${input}` }; @@ -38,7 +38,7 @@ function test(input, errObj) { [-1, 2 ** 32].forEach((input) => { const errObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "fd" is out of range. It must be ' + `>= 0 && < 4294967296. Received ${input}` }; diff --git a/test/parallel/test-fs-fsync.js b/test/parallel/test-fs-fsync.js index 4d96091f34..cf80f46bd0 100644 --- a/test/parallel/test-fs-fsync.js +++ b/test/parallel/test-fs-fsync.js @@ -53,7 +53,7 @@ fs.open(fileTemp, 'a', 0o777, common.mustCall(function(err, fd) { ['', false, null, undefined, {}, []].forEach((input) => { const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "fd" argument must be of type number. Received type ' + typeof input }; diff --git a/test/parallel/test-fs-lchmod.js b/test/parallel/test-fs-lchmod.js index e84fa08aac..3b5a51becd 100644 --- a/test/parallel/test-fs-lchmod.js +++ b/test/parallel/test-fs-lchmod.js @@ -41,7 +41,7 @@ assert.throws(() => fs.lchmod(f, {}), { code: 'ERR_INVALID_CALLBACK' }); [false, null, undefined, {}, [], '', '123x'].forEach((input) => { const errObj = { code: 'ERR_INVALID_ARG_VALUE', - name: 'TypeError [ERR_INVALID_ARG_VALUE]', + name: 'TypeError', message: 'The argument \'mode\' must be a 32-bit unsigned integer or an ' + `octal string. Received ${util.inspect(input)}` }; @@ -53,7 +53,7 @@ assert.throws(() => fs.lchmod(f, {}), { code: 'ERR_INVALID_CALLBACK' }); [-1, 2 ** 32].forEach((input) => { const errObj = { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "mode" is out of range. It must be >= 0 && <= ' + `4294967295. Received ${input}` }; diff --git a/test/parallel/test-fs-open.js b/test/parallel/test-fs-open.js index 79b78ff2ef..51cd9ecf31 100644 --- a/test/parallel/test-fs-open.js +++ b/test/parallel/test-fs-open.js @@ -102,7 +102,7 @@ for (const extra of [[], ['r'], ['r', 0], ['r', 0, 'bad callback']]) { fs.promises.open(i, 'r'), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' } ); }); diff --git a/test/parallel/test-fs-promises.js b/test/parallel/test-fs-promises.js index 97b5f8326e..2e6ba0e8a2 100644 --- a/test/parallel/test-fs-promises.js +++ b/test/parallel/test-fs-promises.js @@ -164,7 +164,7 @@ async function getHandle(dest) { }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "gid" is out of range. ' + 'It must be >= 0 && < 4294967296. Received -1' }); @@ -175,7 +175,7 @@ async function getHandle(dest) { }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "gid" is out of range. ' + 'It must be >= 0 && < 4294967296. Received -1' }); @@ -336,7 +336,7 @@ async function getHandle(dest) { async () => mkdir(dir, { recursive }), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "recursive" argument must be of type boolean. ' + `Received type ${typeof recursive}` } @@ -352,7 +352,7 @@ async function getHandle(dest) { async () => mkdtemp(1), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' } ); } diff --git a/test/parallel/test-fs-read-type.js b/test/parallel/test-fs-read-type.js index d75464ce0a..b51df51589 100644 --- a/test/parallel/test-fs-read-type.js +++ b/test/parallel/test-fs-read-type.js @@ -14,7 +14,7 @@ assert.throws( () => fs.read(fd, expected.length, 0, 'utf-8', common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "buffer" argument must be one of type Buffer, TypedArray, ' + 'or DataView. Received type number' } @@ -30,7 +30,7 @@ assert.throws( common.mustNotCall()); }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "fd" argument must be of type number. ' + `Received type ${typeof value}` }); @@ -45,7 +45,7 @@ assert.throws(() => { common.mustNotCall()); }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. It must be >= 0 && <= 4. ' + 'Received -1' }); @@ -59,7 +59,7 @@ assert.throws(() => { common.mustNotCall()); }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "length" is out of range. ' + 'It must be >= 0 && <= 4. Received -1' }); @@ -69,7 +69,7 @@ assert.throws( () => fs.readSync(fd, expected.length, 0, 'utf-8'), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "buffer" argument must be one of type Buffer, TypedArray, ' + 'or DataView. Received type number' } @@ -84,7 +84,7 @@ assert.throws( 0); }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "fd" argument must be of type number. ' + `Received type ${typeof value}` }); @@ -98,7 +98,7 @@ assert.throws(() => { 0); }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "offset" is out of range. ' + 'It must be >= 0 && <= 4. Received -1' }); @@ -111,7 +111,7 @@ assert.throws(() => { 0); }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "length" is out of range. ' + 'It must be >= 0 && <= 4. Received -1' }); diff --git a/test/parallel/test-fs-readfile-error.js b/test/parallel/test-fs-readfile-error.js index 719c0061c4..3b245058ff 100644 --- a/test/parallel/test-fs-readfile-error.js +++ b/test/parallel/test-fs-readfile-error.js @@ -38,12 +38,12 @@ function test(env, cb) { const filename = fixtures.path('test-fs-readfile-error.js'); const execPath = `"${process.execPath}" "${filename}"`; const options = { env: Object.assign({}, process.env, env) }; - exec(execPath, options, common.mustCall((err, stdout, stderr) => { + exec(execPath, options, (err, stdout, stderr) => { assert(err); assert.strictEqual(stdout, ''); assert.notStrictEqual(stderr, ''); cb(String(stderr)); - })); + }); } test({ NODE_DEBUG: '' }, common.mustCall((data) => { diff --git a/test/parallel/test-fs-rename-type-check.js b/test/parallel/test-fs-rename-type-check.js index b8f0549f0c..bc1277740f 100644 --- a/test/parallel/test-fs-rename-type-check.js +++ b/test/parallel/test-fs-rename-type-check.js @@ -10,7 +10,7 @@ const fs = require('fs'); () => fs.rename(input, 'does-not-exist', common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "oldPath" argument must be one ${type}` } ); @@ -18,7 +18,7 @@ const fs = require('fs'); () => fs.rename('does-not-exist', input, common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "newPath" argument must be one ${type}` } ); @@ -26,7 +26,7 @@ const fs = require('fs'); () => fs.renameSync(input, 'does-not-exist'), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "oldPath" argument must be one ${type}` } ); @@ -34,7 +34,7 @@ const fs = require('fs'); () => fs.renameSync('does-not-exist', input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: `The "newPath" argument must be one ${type}` } ); diff --git a/test/parallel/test-fs-stat.js b/test/parallel/test-fs-stat.js index a44e2ce3a7..40a0640724 100644 --- a/test/parallel/test-fs-stat.js +++ b/test/parallel/test-fs-stat.js @@ -134,7 +134,7 @@ fs.stat(__filename, common.mustCall(function(err, s) { () => fs[fnName](input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "fd" argument must be of type number. ' + `Received type ${typeof input}` } @@ -147,28 +147,28 @@ fs.stat(__filename, common.mustCall(function(err, s) { () => fs.lstat(input, common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' } ); assert.throws( () => fs.lstatSync(input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' } ); assert.throws( () => fs.stat(input, common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' } ); assert.throws( () => fs.statSync(input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' } ); }); diff --git a/test/parallel/test-fs-symlink.js b/test/parallel/test-fs-symlink.js index ddcf7a63ff..a600110319 100644 --- a/test/parallel/test-fs-symlink.js +++ b/test/parallel/test-fs-symlink.js @@ -61,7 +61,7 @@ fs.symlink(linkData, linkPath, common.mustCall(function(err) { [false, 1, {}, [], null, undefined].forEach((input) => { const errObj = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "target" argument must be one of type string, Buffer, or ' + `URL. Received type ${typeof input}` }; @@ -75,7 +75,7 @@ fs.symlink(linkData, linkPath, common.mustCall(function(err) { const errObj = { code: 'ERR_FS_INVALID_SYMLINK_TYPE', - name: 'Error [ERR_FS_INVALID_SYMLINK_TYPE]', + name: 'Error', message: 'Symlink type must be one of "dir", "file", or "junction". Received "🍏"' }; diff --git a/test/parallel/test-fs-truncate.js b/test/parallel/test-fs-truncate.js index d1d743eb57..95036dc9f5 100644 --- a/test/parallel/test-fs-truncate.js +++ b/test/parallel/test-fs-truncate.js @@ -183,7 +183,7 @@ function testFtruncate(cb) { () => fs.truncate(file5, input, common.mustNotCall()), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "len" argument must be of type number. ' + `Received type ${typeof input}` } @@ -193,7 +193,7 @@ function testFtruncate(cb) { () => fs.ftruncate(fd, input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "len" argument must be of type number. ' + `Received type ${typeof input}` } @@ -205,7 +205,7 @@ function testFtruncate(cb) { () => fs.truncate(file5, input), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "len" is out of range. It must be ' + `an integer. Received ${input}` } @@ -215,7 +215,7 @@ function testFtruncate(cb) { () => fs.ftruncate(fd, input), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "len" is out of range. It must be ' + `an integer. Received ${input}` } @@ -267,7 +267,7 @@ function testFtruncate(cb) { () => fs.truncate('/foo/bar', input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "len" argument must be of type number. ' + `Received type ${typeof input}` } @@ -280,7 +280,7 @@ function testFtruncate(cb) { () => fs[fnName](input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "fd" argument must be of type number. ' + `Received type ${typeof input}` } diff --git a/test/parallel/test-http-res-write-end-dont-take-array.js b/test/parallel/test-http-res-write-end-dont-take-array.js index f801da246e..d7000f6fd2 100644 --- a/test/parallel/test-http-res-write-end-dont-take-array.js +++ b/test/parallel/test-http-res-write-end-dont-take-array.js @@ -37,7 +37,7 @@ server.once('request', common.mustCall((req, res) => { const expectedError = { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', }; // Write should not accept an Array diff --git a/test/parallel/test-http2-altsvc.js b/test/parallel/test-http2-altsvc.js index 8b2e5b4690..3a1a1cf629 100644 --- a/test/parallel/test-http2-altsvc.js +++ b/test/parallel/test-http2-altsvc.js @@ -33,7 +33,7 @@ server.on('session', common.mustCall((session) => { () => session.altsvc('h2=":8000"', input), { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "originOrStream" is out of ' + `range. It must be > 0 && < 4294967296. Received ${input}` } @@ -46,7 +46,7 @@ server.on('session', common.mustCall((session) => { () => session.altsvc(input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' } ); }); @@ -56,7 +56,7 @@ server.on('session', common.mustCall((session) => { () => session.altsvc(input), { code: 'ERR_INVALID_CHAR', - name: 'TypeError [ERR_INVALID_CHAR]', + name: 'TypeError', message: 'Invalid character in alt' } ); @@ -67,7 +67,7 @@ server.on('session', common.mustCall((session) => { () => session.altsvc('clear', input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' } ); }); @@ -82,7 +82,7 @@ server.on('session', common.mustCall((session) => { () => session.altsvc('h2=":8000', input), { code: 'ERR_HTTP2_ALTSVC_INVALID_ORIGIN', - name: 'TypeError [ERR_HTTP2_ALTSVC_INVALID_ORIGIN]', + name: 'TypeError', message: 'HTTP/2 ALTSVC frames require a valid origin' } ); @@ -96,7 +96,7 @@ server.on('session', common.mustCall((session) => { }, { code: 'ERR_HTTP2_ALTSVC_LENGTH', - name: 'TypeError [ERR_HTTP2_ALTSVC_LENGTH]', + name: 'TypeError', message: 'HTTP/2 ALTSVC frames are limited to 16382 bytes' } ); diff --git a/test/parallel/test-http2-client-http1-server.js b/test/parallel/test-http2-client-http1-server.js index c7535adcef..2728033d19 100644 --- a/test/parallel/test-http2-client-http1-server.js +++ b/test/parallel/test-http2-client-http1-server.js @@ -27,7 +27,7 @@ server.listen(0, common.mustCall(() => { client.on('error', common.expectsError({ code: 'ERR_HTTP2_ERROR', type: NghttpError, - name: 'Error [ERR_HTTP2_ERROR]', + name: 'Error', message: 'Protocol error' })); diff --git a/test/parallel/test-http2-client-onconnect-errors.js b/test/parallel/test-http2-client-onconnect-errors.js index 5c08478784..b00c050724 100644 --- a/test/parallel/test-http2-client-onconnect-errors.js +++ b/test/parallel/test-http2-client-onconnect-errors.js @@ -55,7 +55,7 @@ const genericTests = Object.getOwnPropertyNames(constants) error: { code: 'ERR_HTTP2_ERROR', type: NghttpError, - name: 'Error [ERR_HTTP2_ERROR]', + name: 'Error', message: nghttp2ErrorString(constants[key]) }, type: 'session' diff --git a/test/parallel/test-http2-client-rststream-before-connect.js b/test/parallel/test-http2-client-rststream-before-connect.js index 33e22130aa..8c3eb9bec3 100644 --- a/test/parallel/test-http2-client-rststream-before-connect.js +++ b/test/parallel/test-http2-client-rststream-before-connect.js @@ -21,7 +21,7 @@ server.listen(0, common.mustCall(() => { assert.throws( () => req.close(2 ** 32), { - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', code: 'ERR_OUT_OF_RANGE', message: 'The value of "code" is out of range. It must be ' + '>= 0 && <= 4294967295. Received 4294967296' diff --git a/test/parallel/test-http2-compat-serverrequest-headers.js b/test/parallel/test-http2-compat-serverrequest-headers.js index bd46b71900..8b38ab147f 100644 --- a/test/parallel/test-http2-compat-serverrequest-headers.js +++ b/test/parallel/test-http2-compat-serverrequest-headers.js @@ -49,7 +49,7 @@ server.listen(0, common.mustCall(function() { () => request.method = ' ', { code: 'ERR_INVALID_ARG_VALUE', - name: 'TypeError [ERR_INVALID_ARG_VALUE]', + name: 'TypeError', message: "The argument 'method' is invalid. Received ' '" } ); @@ -57,7 +57,7 @@ server.listen(0, common.mustCall(function() { () => request.method = true, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "method" argument must be of type string. ' + 'Received type boolean' } diff --git a/test/parallel/test-http2-compat-serverresponse-headers.js b/test/parallel/test-http2-compat-serverresponse-headers.js index 94f1d19373..c47de48b6a 100644 --- a/test/parallel/test-http2-compat-serverresponse-headers.js +++ b/test/parallel/test-http2-compat-serverresponse-headers.js @@ -46,7 +46,7 @@ server.listen(0, common.mustCall(function() { () => response[fnName](), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "name" argument must be of type string. Received ' + 'type undefined' } diff --git a/test/parallel/test-http2-createsecureserver-nooptions.js b/test/parallel/test-http2-createsecureserver-nooptions.js index 767797febc..22a7562388 100644 --- a/test/parallel/test-http2-createsecureserver-nooptions.js +++ b/test/parallel/test-http2-createsecureserver-nooptions.js @@ -13,7 +13,7 @@ invalidOptions.forEach((invalidOption) => { assert.throws( () => http2.createSecureServer(invalidOption), { - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', code: 'ERR_INVALID_ARG_TYPE', message: 'The "options" argument must be of type Object. Received ' + `type ${typeof invalidOption}` diff --git a/test/parallel/test-http2-info-headers-errors.js b/test/parallel/test-http2-info-headers-errors.js index a55e9df026..a2e17abd74 100644 --- a/test/parallel/test-http2-info-headers-errors.js +++ b/test/parallel/test-http2-info-headers-errors.js @@ -28,7 +28,7 @@ const genericTests = Object.getOwnPropertyNames(constants) error: { code: 'ERR_HTTP2_ERROR', type: NghttpError, - name: 'Error [ERR_HTTP2_ERROR]', + name: 'Error', message: nghttp2ErrorString(constants[key]) }, type: 'stream' diff --git a/test/parallel/test-http2-origin.js b/test/parallel/test-http2-origin.js index b06d371e29..d0d8c81f80 100644 --- a/test/parallel/test-http2-origin.js +++ b/test/parallel/test-http2-origin.js @@ -46,7 +46,7 @@ const ca = readKey('fake-startcom-root-cert.pem', 'binary'); () => session.origin(input), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]' + name: 'TypeError' } ); }); @@ -56,7 +56,7 @@ const ca = readKey('fake-startcom-root-cert.pem', 'binary'); () => session.origin(input), { code: 'ERR_HTTP2_INVALID_ORIGIN', - name: 'TypeError [ERR_HTTP2_INVALID_ORIGIN]' + name: 'TypeError' } ); }); @@ -66,7 +66,7 @@ const ca = readKey('fake-startcom-root-cert.pem', 'binary'); () => session.origin(input), { code: 'ERR_INVALID_URL', - name: 'TypeError [ERR_INVALID_URL]' + name: 'TypeError' } ); }); @@ -75,7 +75,7 @@ const ca = readKey('fake-startcom-root-cert.pem', 'binary'); () => session.origin(longInput), { code: 'ERR_HTTP2_ORIGIN_LENGTH', - name: 'TypeError [ERR_HTTP2_ORIGIN_LENGTH]' + name: 'TypeError' } ); })); diff --git a/test/parallel/test-http2-respond-nghttperrors.js b/test/parallel/test-http2-respond-nghttperrors.js index 3bdfbffeec..30d20d4b81 100644 --- a/test/parallel/test-http2-respond-nghttperrors.js +++ b/test/parallel/test-http2-respond-nghttperrors.js @@ -29,7 +29,7 @@ const genericTests = Object.getOwnPropertyNames(constants) error: { code: 'ERR_HTTP2_ERROR', type: NghttpError, - name: 'Error [ERR_HTTP2_ERROR]', + name: 'Error', message: nghttp2ErrorString(constants[key]) }, type: 'stream' diff --git a/test/parallel/test-http2-respond-with-fd-errors.js b/test/parallel/test-http2-respond-with-fd-errors.js index 4e876c532f..00ed777df5 100644 --- a/test/parallel/test-http2-respond-with-fd-errors.js +++ b/test/parallel/test-http2-respond-with-fd-errors.js @@ -36,7 +36,7 @@ const genericTests = Object.getOwnPropertyNames(constants) error: { code: 'ERR_HTTP2_ERROR', type: NghttpError, - name: 'Error [ERR_HTTP2_ERROR]', + name: 'Error', message: nghttp2ErrorString(constants[key]) }, type: 'stream' diff --git a/test/parallel/test-http2-server-push-stream-errors-args.js b/test/parallel/test-http2-server-push-stream-errors-args.js index 24f7c9fcef..0c3b9dcfcc 100644 --- a/test/parallel/test-http2-server-push-stream-errors-args.js +++ b/test/parallel/test-http2-server-push-stream-errors-args.js @@ -31,7 +31,7 @@ server.on('stream', common.mustCall((stream, headers) => { () => stream.pushStream({ 'connection': 'test' }, {}, () => {}), { code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', - name: 'TypeError [ERR_HTTP2_INVALID_CONNECTION_HEADERS]', + name: 'TypeError', message: 'HTTP/1 Connection specific headers are forbidden: "connection"' } ); diff --git a/test/parallel/test-http2-server-push-stream-errors.js b/test/parallel/test-http2-server-push-stream-errors.js index 35d8b796e4..b1c5421310 100644 --- a/test/parallel/test-http2-server-push-stream-errors.js +++ b/test/parallel/test-http2-server-push-stream-errors.js @@ -53,7 +53,7 @@ const genericTests = Object.getOwnPropertyNames(constants) error: { code: 'ERR_HTTP2_ERROR', type: NghttpError, - name: 'Error [ERR_HTTP2_ERROR]', + name: 'Error', message: nghttp2ErrorString(constants[key]) }, type: 'stream' diff --git a/test/parallel/test-http2-util-headers-list.js b/test/parallel/test-http2-util-headers-list.js index 2814613df2..5045263b15 100644 --- a/test/parallel/test-http2-util-headers-list.js +++ b/test/parallel/test-http2-util-headers-list.js @@ -283,7 +283,7 @@ const { ].forEach((name) => { common.expectsError(() => mapToHeaders({ [name]: 'abc' }), { code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', - name: 'TypeError [ERR_HTTP2_INVALID_CONNECTION_HEADERS]', + name: 'TypeError', message: 'HTTP/1 Connection specific headers are forbidden: ' + `"${name.toLowerCase()}"` }); @@ -291,7 +291,7 @@ const { common.expectsError(() => mapToHeaders({ [HTTP2_HEADER_TE]: ['abc'] }), { code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', - name: 'TypeError [ERR_HTTP2_INVALID_CONNECTION_HEADERS]', + name: 'TypeError', message: 'HTTP/1 Connection specific headers are forbidden: ' + `"${HTTP2_HEADER_TE}"` }); @@ -299,7 +299,7 @@ common.expectsError(() => mapToHeaders({ [HTTP2_HEADER_TE]: ['abc'] }), { common.expectsError( () => mapToHeaders({ [HTTP2_HEADER_TE]: ['abc', 'trailers'] }), { code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', - name: 'TypeError [ERR_HTTP2_INVALID_CONNECTION_HEADERS]', + name: 'TypeError', message: 'HTTP/1 Connection specific headers are forbidden: ' + `"${HTTP2_HEADER_TE}"` }); diff --git a/test/parallel/test-https-options-boolean-check.js b/test/parallel/test-https-options-boolean-check.js index bed5fb0325..295082e1ce 100644 --- a/test/parallel/test-https-options-boolean-check.js +++ b/test/parallel/test-https-options-boolean-check.js @@ -87,7 +87,7 @@ const caArrDataView = toDataView(caCert); https.createServer({ key, cert }); }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "options.key" property must be one of type string, Buffer, ' + `TypedArray, or DataView. Received type ${type}` }); @@ -112,7 +112,7 @@ const caArrDataView = toDataView(caCert); https.createServer({ key, cert }); }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "options.cert" property must be one of type string, Buffer,' + ` TypedArray, or DataView. Received type ${type}` }); @@ -146,7 +146,7 @@ const caArrDataView = toDataView(caCert); https.createServer({ key, cert, ca }); }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "options.ca" property must be one of type string, Buffer, ' + `TypedArray, or DataView. Received type ${type}` }); diff --git a/test/parallel/test-internal-error-original-names.js b/test/parallel/test-internal-error-original-names.js index 195e39b199..e00221b1a6 100644 --- a/test/parallel/test-internal-error-original-names.js +++ b/test/parallel/test-internal-error-original-names.js @@ -17,7 +17,7 @@ errors.E('TEST_ERROR_1', 'Error for testing purposes: %s', { const err = new errors.codes.TEST_ERROR_1('test'); assert(err instanceof Error); - assert.strictEqual(err.name, 'Error [TEST_ERROR_1]'); + assert.strictEqual(err.name, 'Error'); } { @@ -31,5 +31,5 @@ errors.E('TEST_ERROR_1', 'Error for testing purposes: %s', errors.useOriginalName = false; const err = new errors.codes.TEST_ERROR_1('test'); assert(err instanceof Error); - assert.strictEqual(err.name, 'Error [TEST_ERROR_1]'); + assert.strictEqual(err.name, 'Error'); } diff --git a/test/parallel/test-internal-errors.js b/test/parallel/test-internal-errors.js index bf1983f3b3..53fbf06c77 100644 --- a/test/parallel/test-internal-errors.js +++ b/test/parallel/test-internal-errors.js @@ -20,7 +20,7 @@ errors.E('TEST_ERROR_2', (a, b) => `${a} ${b}`, Error); { const err = new errors.codes.TEST_ERROR_1('test'); assert(err instanceof Error); - assert.strictEqual(err.name, 'Error [TEST_ERROR_1]'); + assert.strictEqual(err.name, 'Error'); assert.strictEqual(err.message, 'Error for testing purposes: test'); assert.strictEqual(err.code, 'TEST_ERROR_1'); } @@ -28,7 +28,7 @@ errors.E('TEST_ERROR_2', (a, b) => `${a} ${b}`, Error); { const err = new errors.codes.TEST_ERROR_1.TypeError('test'); assert(err instanceof TypeError); - assert.strictEqual(err.name, 'TypeError [TEST_ERROR_1]'); + assert.strictEqual(err.name, 'TypeError'); assert.strictEqual(err.message, 'Error for testing purposes: test'); assert.strictEqual(err.code, 'TEST_ERROR_1'); } @@ -36,7 +36,7 @@ errors.E('TEST_ERROR_2', (a, b) => `${a} ${b}`, Error); { const err = new errors.codes.TEST_ERROR_1.RangeError('test'); assert(err instanceof RangeError); - assert.strictEqual(err.name, 'RangeError [TEST_ERROR_1]'); + assert.strictEqual(err.name, 'RangeError'); assert.strictEqual(err.message, 'Error for testing purposes: test'); assert.strictEqual(err.code, 'TEST_ERROR_1'); } @@ -44,7 +44,7 @@ errors.E('TEST_ERROR_2', (a, b) => `${a} ${b}`, Error); { const err = new errors.codes.TEST_ERROR_2('abc', 'xyz'); assert(err instanceof Error); - assert.strictEqual(err.name, 'Error [TEST_ERROR_2]'); + assert.strictEqual(err.name, 'Error'); assert.strictEqual(err.message, 'abc xyz'); assert.strictEqual(err.code, 'TEST_ERROR_2'); } @@ -79,27 +79,6 @@ common.expectsError(() => { message: 'Error for testing purposes: a' }); -common.expectsError(() => { - common.expectsError(() => { - throw new errors.codes.TEST_ERROR_1.TypeError('a'); - }, { code: 'TEST_ERROR_1', type: RangeError }); -}, { - code: 'ERR_ASSERTION', - message: /\+ type: \[Function: TypeError]\n- type: \[Function: RangeError]/ -}); - -common.expectsError(() => { - common.expectsError(() => { - throw new errors.codes.TEST_ERROR_1.TypeError('a'); - }, { code: 'TEST_ERROR_1', - type: TypeError, - message: /^Error for testing 2/ }); -}, { - code: 'ERR_ASSERTION', - type: assert.AssertionError, - message: /\+ message: 'Error for testing purposes: a',\n- message: \/\^Error/ -}); - // Test that `code` property is mutable and that changing it does not change the // name. { @@ -113,7 +92,7 @@ common.expectsError(() => { assert.strictEqual(myError.code, 'FHQWHGADS'); assert.strictEqual(myError.name, initialName); assert.deepStrictEqual(Object.keys(myError), ['code']); - assert.ok(myError.name.includes('TEST_ERROR_1')); + assert.ok(!myError.name.includes('TEST_ERROR_1')); assert.ok(!myError.name.includes('FHQWHGADS')); } diff --git a/test/parallel/test-loaders-unknown-builtin-module.mjs b/test/parallel/test-loaders-unknown-builtin-module.mjs index db3cfa3582..5f47f191f5 100644 --- a/test/parallel/test-loaders-unknown-builtin-module.mjs +++ b/test/parallel/test-loaders-unknown-builtin-module.mjs @@ -1,5 +1,6 @@ // Flags: --experimental-modules --loader ./test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs -import { expectsError, mustCall } from '../common'; +/* eslint-disable node-core/required-modules */ +import { expectsError, mustCall } from '../common/index.mjs'; import assert from 'assert'; const unknownBuiltinModule = 'unknown-builtin-module'; diff --git a/test/parallel/test-module-main-extension-lookup.js b/test/parallel/test-module-main-extension-lookup.js index 3d20316647..9e7eab295e 100644 --- a/test/parallel/test-module-main-extension-lookup.js +++ b/test/parallel/test-module-main-extension-lookup.js @@ -6,6 +6,6 @@ const { execFileSync } = require('child_process'); const node = process.argv[0]; execFileSync(node, ['--experimental-modules', - fixtures.path('es-modules', 'test-esm-ok')]); + fixtures.path('es-modules', 'test-esm-ok.mjs')]); execFileSync(node, ['--experimental-modules', fixtures.path('es-modules', 'noext')]); diff --git a/test/parallel/test-next-tick-errors.js b/test/parallel/test-next-tick-errors.js index acb7c49727..51ed2524a0 100644 --- a/test/parallel/test-next-tick-errors.js +++ b/test/parallel/test-next-tick-errors.js @@ -48,7 +48,7 @@ function testNextTickWith(val) { }, { code: 'ERR_INVALID_CALLBACK', - name: 'TypeError [ERR_INVALID_CALLBACK]', + name: 'TypeError', type: TypeError } ); diff --git a/test/parallel/test-process-cpuUsage.js b/test/parallel/test-process-cpuUsage.js index 0b1d53978c..76e0702b9e 100644 --- a/test/parallel/test-process-cpuUsage.js +++ b/test/parallel/test-process-cpuUsage.js @@ -37,7 +37,7 @@ assert.throws( () => process.cpuUsage(1), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "prevValue" argument must be of type object. ' + 'Received type number' } @@ -53,7 +53,7 @@ assert.throws( () => process.cpuUsage(value), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "prevValue.user" property must be of type number. ' + `Received type ${typeof value.user}` } @@ -68,7 +68,7 @@ assert.throws( () => process.cpuUsage(value), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "prevValue.system" property must be of type number. ' + `Received type ${typeof value.system}` } @@ -84,7 +84,7 @@ assert.throws( () => process.cpuUsage(value), { code: 'ERR_INVALID_OPT_VALUE', - name: 'RangeError [ERR_INVALID_OPT_VALUE]', + name: 'RangeError', message: `The value "${value.user}" is invalid ` + 'for option "prevValue.user"' } @@ -99,7 +99,7 @@ assert.throws( () => process.cpuUsage(value), { code: 'ERR_INVALID_OPT_VALUE', - name: 'RangeError [ERR_INVALID_OPT_VALUE]', + name: 'RangeError', message: `The value "${value.system}" is invalid ` + 'for option "prevValue.system"' } diff --git a/test/parallel/test-process-initgroups.js b/test/parallel/test-process-initgroups.js index f5e839b1d2..0cc0760d76 100644 --- a/test/parallel/test-process-initgroups.js +++ b/test/parallel/test-process-initgroups.js @@ -17,7 +17,7 @@ if (!common.isMainThread) }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "user" argument must be ' + 'one of type number or string. ' + @@ -33,7 +33,7 @@ if (!common.isMainThread) }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "extraGroup" argument must be ' + 'one of type number or string. ' + diff --git a/test/parallel/test-process-kill-pid.js b/test/parallel/test-process-kill-pid.js index c299ceabaa..698fa4cf62 100644 --- a/test/parallel/test-process-kill-pid.js +++ b/test/parallel/test-process-kill-pid.js @@ -41,7 +41,7 @@ const assert = require('assert'); ['SIGTERM', null, undefined, NaN, Infinity, -Infinity].forEach((val) => { assert.throws(() => process.kill(val), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "pid" argument must be of type number. ' + `Received type ${typeof val}` }); diff --git a/test/parallel/test-process-setgroups.js b/test/parallel/test-process-setgroups.js index 74de3e7a25..31e56a2da3 100644 --- a/test/parallel/test-process-setgroups.js +++ b/test/parallel/test-process-setgroups.js @@ -16,7 +16,7 @@ assert.throws( }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "groups" argument must be of type Array. ' + 'Received type undefined' } @@ -28,7 +28,7 @@ assert.throws( }, { code: 'ERR_OUT_OF_RANGE', - name: 'RangeError [ERR_OUT_OF_RANGE]', + name: 'RangeError', message: 'The value of "groups[1]" is out of range. ' + 'It must be >= 0 && < 4294967296. Received -1' } @@ -41,7 +41,7 @@ assert.throws( }, { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "groups[0]" argument must be ' + 'one of type number or string. ' + `Received type ${typeof val}` diff --git a/test/parallel/test-stream-finished.js b/test/parallel/test-stream-finished.js index fe87f24632..e06017920c 100644 --- a/test/parallel/test-stream-finished.js +++ b/test/parallel/test-stream-finished.js @@ -129,21 +129,21 @@ const { promisify } = require('util'); assert.throws( () => finished(rs, 'foo'), { - name: /ERR_INVALID_ARG_TYPE/, + code: 'ERR_INVALID_ARG_TYPE', message: /callback/ } ); assert.throws( () => finished(rs, 'foo', () => {}), { - name: /ERR_INVALID_ARG_TYPE/, + code: 'ERR_INVALID_ARG_TYPE', message: /opts/ } ); assert.throws( () => finished(rs, {}, 'foo'), { - name: /ERR_INVALID_ARG_TYPE/, + code: 'ERR_INVALID_ARG_TYPE', message: /callback/ } ); diff --git a/test/parallel/test-timers-max-duration-warning.js b/test/parallel/test-timers-max-duration-warning.js index c978cf29c3..a104c1700d 100644 --- a/test/parallel/test-timers-max-duration-warning.js +++ b/test/parallel/test-timers-max-duration-warning.js @@ -19,7 +19,7 @@ process.on('warning', common.mustCall((warning) => { assert.strictEqual(lines[0], `${OVERFLOW} does not fit into a 32-bit signed` + ' integer.'); assert.strictEqual(lines.length, 2); -}, 5)); +}, 6)); { diff --git a/test/parallel/test-ttywrap-invalid-fd.js b/test/parallel/test-ttywrap-invalid-fd.js index 30c3cd2bc4..ea2e0f276d 100644 --- a/test/parallel/test-ttywrap-invalid-fd.js +++ b/test/parallel/test-ttywrap-invalid-fd.js @@ -14,7 +14,7 @@ assert.throws( () => new tty.WriteStream(-1), { code: 'ERR_INVALID_FD', - name: 'RangeError [ERR_INVALID_FD]', + name: 'RangeError', message: '"fd" must be a positive integer: -1' } ); @@ -38,7 +38,7 @@ assert.throws( }); }, { code: 'ERR_TTY_INIT_FAILED', - name: 'SystemError [ERR_TTY_INIT_FAILED]', + name: 'SystemError', message, info } @@ -51,7 +51,7 @@ assert.throws( }); }, { code: 'ERR_TTY_INIT_FAILED', - name: 'SystemError [ERR_TTY_INIT_FAILED]', + name: 'SystemError', message, info }); @@ -61,7 +61,7 @@ assert.throws( () => new tty.ReadStream(-1), { code: 'ERR_INVALID_FD', - name: 'RangeError [ERR_INVALID_FD]', + name: 'RangeError', message: '"fd" must be a positive integer: -1' } ); diff --git a/test/parallel/test-url-format-whatwg.js b/test/parallel/test-url-format-whatwg.js index e5c3e369e8..95332e3f09 100644 --- a/test/parallel/test-url-format-whatwg.js +++ b/test/parallel/test-url-format-whatwg.js @@ -26,7 +26,7 @@ assert.strictEqual( () => url.format(myURL, value), { code: 'ERR_INVALID_ARG_TYPE', - name: 'TypeError [ERR_INVALID_ARG_TYPE]', + name: 'TypeError', message: 'The "options" argument must be of type Object. ' + `Received type ${typeof value}` } diff --git a/test/parallel/test-whatwg-url-custom-parsing.js b/test/parallel/test-whatwg-url-custom-parsing.js index 34d9062087..e83cc00536 100644 --- a/test/parallel/test-whatwg-url-custom-parsing.js +++ b/test/parallel/test-whatwg-url-custom-parsing.js @@ -56,15 +56,13 @@ for (const test of failureTests) { assert.throws( () => new URL(test.input, test.base), (error) => { - if (!expectedError(error)) - return false; + expectedError(error); // The input could be processed, so we don't do strict matching here - const match = (`${error}`).match(/Invalid URL: (.*)$/); - if (!match) { - return false; - } - return error.input === match[1]; + let match; + assert(match = (`${error}`).match(/Invalid URL: (.*)$/)); + assert.strictEqual(error.input, match[1]); + return true; }); } diff --git a/test/pummel/test-tls-session-timeout.js b/test/sequential/test-tls-session-timeout.js similarity index 89% rename from test/pummel/test-tls-session-timeout.js rename to test/sequential/test-tls-session-timeout.js index 338e7dd16b..4e430b7135 100644 --- a/test/pummel/test-tls-session-timeout.js +++ b/test/sequential/test-tls-session-timeout.js @@ -29,6 +29,7 @@ if (!common.hasCrypto) common.skip('missing crypto'); const tmpdir = require('../common/tmpdir'); +tmpdir.refresh(); doTest(); @@ -56,7 +57,8 @@ function doTest() { key: key, cert: cert, ca: [cert], - sessionTimeout: SESSION_TIMEOUT + sessionTimeout: SESSION_TIMEOUT, + maxVersion: 'TLSv1.2', }; // We need to store a sample session ticket in the fixtures directory because @@ -79,17 +81,17 @@ function doTest() { 's_client', '-connect', `localhost:${common.PORT}`, '-sess_in', sessionFileName, - '-sess_out', sessionFileName + '-sess_out', sessionFileName, ]; const client = spawn(common.opensslCli, flags, { stdio: ['ignore', 'pipe', 'ignore'] }); let clientOutput = ''; - client.stdout.on('data', function(data) { + client.stdout.on('data', (data) => { clientOutput += data.toString(); }); - client.on('exit', function(code) { + client.on('exit', (code) => { let connectionType; const grepConnectionType = (line) => { const matches = line.match(/(New|Reused), /); @@ -102,25 +104,26 @@ function doTest() { if (!lines.some(grepConnectionType)) { throw new Error('unexpected output from openssl client'); } + assert.strictEqual(code, 0); cb(connectionType); }); } - const server = tls.createServer(options, function(cleartext) { - cleartext.on('error', function(er) { + const server = tls.createServer(options, (cleartext) => { + cleartext.on('error', (er) => { if (er.code !== 'ECONNRESET') throw er; }); cleartext.end(); }); - server.listen(common.PORT, function() { - Client(function(connectionType) { + server.listen(common.PORT, () => { + Client((connectionType) => { assert.strictEqual(connectionType, 'New'); - Client(function(connectionType) { + Client((connectionType) => { assert.strictEqual(connectionType, 'Reused'); - setTimeout(function() { - Client(function(connectionType) { + setTimeout(() => { + Client((connectionType) => { assert.strictEqual(connectionType, 'New'); server.close(); });