vfs: integrate with CJS and ESM module loaders

Co-authored-by: James M Snell <jasnell@gmail.com>
Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/63653
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Matteo CollinaandJames M Snell authored and Antoine du Hamel committed 2026-09-15 10:49:20 +02:00
1 parent a19912ee8f
commit 5198142c59
70 files changed
+3305 -675

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
'use strict';
const path = require('path');
const { pathToFileURL } = require('url');
const common = require('../common.js');
const bench = common.createBenchmark(main, {
type: ['cjs', 'esm'],
files: [1e2, 1e3],
n: [10],
}, { flags: ['--experimental-vfs', '--no-warnings'] });
// Builds a module graph of `files` packages, each with its own package.json,
// an index requiring a package-local file and a shared root module, and an
// entry point that pulls in every package.
function buildGraph(layer, files, type) {
const entryRequires = [];
if (type === 'esm') {
layer.writeFileSync('/package.json', '{"type":"module"}');
}
layer.writeFileSync('/shared.js',
type === 'cjs' ? 'module.exports = 0;' : 'export default 0;');
for (let i = 0; i < files; i++) {
layer.mkdirSync(`/${i}`, { recursive: true });
if (type === 'cjs') {
layer.writeFileSync(`/${i}/package.json`, '{"main":"index.js"}');
layer.writeFileSync(`/${i}/lib.js`, 'module.exports = 1;');
layer.writeFileSync(
`/${i}/index.js`,
'require("./lib.js"); require("../shared.js"); module.exports = __filename;');
entryRequires.push(`require('./${i}/');`);
} else {
layer.writeFileSync(`/${i}/package.json`, '{"type":"module"}');
layer.writeFileSync(`/${i}/lib.js`, 'export default 1;');
layer.writeFileSync(
`/${i}/index.js`,
'import "./lib.js"; import "../shared.js"; export default import.meta.url;');
entryRequires.push(`import './${i}/index.js';`);
}
}
layer.writeFileSync('/entry.js', entryRequires.join('\n'));
}
async function main({ n, type, files }) {
const vfs = require('node:vfs');
const layer = vfs.create();
buildGraph(layer, files, type);
bench.start();
for (let i = 0; i < n; i++) {
const mountPoint = layer.mount();
const entry = path.join(mountPoint, 'entry.js');
if (type === 'cjs') {
require(entry);
} else {
await import(pathToFileURL(entry).href);
}
// Unmounting purges the module caches for the mount prefix, so every
// iteration is a cold load of the full graph.
layer.unmount();
}
bench.end(n * files);
}
+234
View File
@@ -61,6 +61,11 @@ callback-based, and promise-based file system methods that mirror the
shape of the [`node:fs`][] API. All paths are POSIX-style and absolute
(starting with `/`).
By default, the file tree is private to the VFS instance. To expose
it through the global `node:fs` module, `require()`, and `import`,
call [`vfs.mount()`][]; call [`vfs.unmount()`][] (or rely on a
`using` declaration) to detach again.
## `vfs.create([provider][, options])`
<!-- YAML
@@ -107,6 +112,124 @@ added: v26.4.0
* `emitExperimentalWarning` {boolean} Whether to emit the experimental
warning. **Default:** `true`.
### `vfs.mount()`
<!-- YAML
added: REPLACEME
-->
* Returns: {string} The absolute mount point.
Mounts the virtual file system and returns the resulting mount point.
After mounting, files in the VFS can be accessed through the
`node:fs` module and resolved through `require()` and `import`
using paths under the returned mount point.
Mount points always live inside a reserved namespace that cannot have child file system entries,
so virtual paths never conflate with (or shadow) real paths. The virtual path scheme is subject to
change and users should not manually construct them based on assumptions. Instead, obtain
them from what `vfs.mount()` returns or `vfs.mountPoint`.
```cjs
const vfs = require('node:vfs');
const fs = require('node:fs');
const myVfs = vfs.create();
myVfs.writeFileSync('/data.txt', 'Hello');
const mountPoint = myVfs.mount();
// e.g. '/dev/null/vfs/0'
fs.readFileSync(`${mountPoint}/data.txt`, 'utf8'); // 'Hello'
```
Each `VirtualFileSystem` instance may be mounted at most once at a
time. Attempting to mount an already-mounted instance throws
`ERR_INVALID_STATE`. Because each instance mounts inside its own
per-layer namespace, mounts from different instances can never
overlap.
The VFS supports the [Explicit Resource Management][] proposal. Use
a `using` declaration to unmount automatically when leaving scope:
```cjs
const vfs = require('node:vfs');
const fs = require('node:fs');
let mountPoint;
{
using myVfs = vfs.create();
myVfs.writeFileSync('/data.txt', 'Hello');
mountPoint = myVfs.mount();
fs.readFileSync(`${mountPoint}/data.txt`, 'utf8'); // 'Hello'
} // VFS is automatically unmounted here
fs.existsSync(`${mountPoint}/data.txt`); // false
```
### `vfs.unmount()`
<!-- YAML
added: REPLACEME
-->
Unmounts the virtual file system. After unmounting, virtual files
are no longer reachable through `node:fs`, `require()`, or `import`.
The same instance may be mounted again by calling `mount()`.
This method is idempotent: calling `unmount()` on a VFS that is not
currently mounted has no effect.
### `vfs.mounted`
<!-- YAML
added: REPLACEME
-->
* {boolean}
`true` while the VFS is mounted; `false` otherwise.
### `vfs.mountPoint`
<!-- YAML
added: REPLACEME
-->
* {string | null}
The current mount point as an absolute string (the value returned by
the last [`vfs.mount()`][] call), or `null` when the VFS is not
mounted.
### `vfs.mountPointURL`
<!-- YAML
added: REPLACEME
-->
* {string | null}
The current mount point as a `file:` URL string (the [`vfs.mountPoint`][]
path converted with [`url.pathToFileURL()`][]), or `null` when the VFS
is not mounted.
This is a convenience for addressing mounted files with URL-based
APIs such as dynamic `import()`:
```mjs
import vfs from 'node:vfs';
const myVfs = vfs.create();
myVfs.writeFileSync('/mod.mjs', 'export const value = 42;');
myVfs.mount();
const { value } = await import(`${myVfs.mountPointURL}/mod.mjs`);
console.log(value); // 42
myVfs.unmount();
```
### `vfs.provider`
<!-- YAML
@@ -196,6 +319,104 @@ The promise namespace mirrors `fs.promises` and includes `readFile`,
`access`, `rm`, `truncate`, `link`, `mkdtemp`, `chmod`, `chown`, `lchown`,
`utimes`, `lutimes`, `open`, `lchmod`, and `watch`.
## Module loader integration
Once a `VirtualFileSystem` is mounted, paths under the mount point
participate in module resolution and loading. The [CommonJS
resolution algorithm][] used by [`require()`][] and
[`require.resolve()`][] and the [ES modules resolution algorithm][]
used by `import` and [`import.meta.resolve()`][] are unchanged;
instead, every file system operation those algorithms perform is
dispatched on the path being probed: paths under a mount point are
served by the owning VFS, and all other paths are served by the real
file system. Files served from the VFS therefore behave as
first-class modules.
Because mounted paths live in a reserved namespace that cannot exist
on disk, any given path is served either by exactly one VFS or by
the real file system, never both. There is no search order or
fallback between the two: if a path under a mount point does not
exist in the VFS, resolution fails with `ENOENT` without consulting
the disk, and a mounted layer never shadows a real directory.
For resolution purposes the mount point behaves as a file system
root: `package.json` scope lookups and [loading from `node_modules`
folders][] stop at the mount point. For example, when
`${mountPoint}/foo/bar/main.cjs` calls `require('baz')`, the lookup
goes through:
* `${mountPoint}/foo/bar/node_modules/baz`
* `${mountPoint}/foo/node_modules/baz`
* `${mountPoint}/node_modules/baz`
* If `$NODE_PATH` is set, the folders listed in `$NODE_PATH`
* `$HOME/.node_modules/baz`
* `$HOME/.node_libraries/baz`
* `$PREFIX/lib/node/baz`
The last four entries are [the global folders][], which are legacy
CommonJS behavior and do not apply to `import`. Absolute specifiers
may cross the boundary in either direction: a module on the real
file system can `require()` a mounted path, and a virtual module can
`require()` a real one.
```cjs
const vfs = require('node:vfs');
const myVfs = vfs.create();
myVfs.mkdirSync('/lib');
myVfs.writeFileSync('/lib/greet.js', 'module.exports = () => "hi";');
myVfs.writeFileSync(
'/lib/package.json', '{"main": "./greet.js"}');
const mountPoint = myVfs.mount();
const greet = require(`${mountPoint}/lib`);
console.log(greet()); // 'hi'
myVfs.unmount();
```
For ECMAScript modules, use `file:` URLs when passing mounted paths
to dynamic `import()`. [`vfs.mountPointURL`][] provides the mount
point in that form; this keeps VFS imports portable on Windows,
where mounted paths use Windows path syntax.
```mjs
import vfs from 'node:vfs';
const myVfs = vfs.create();
myVfs.writeFileSync('/mod.mjs', 'export const value = 42;');
myVfs.mount();
const { value } = await import(`${myVfs.mountPointURL}/mod.mjs`);
console.log(value); // 42
myVfs.unmount();
```
CommonJS modules loaded from a mounted VFS are identified by their VFS paths
that start with the mount point. This is reflected in, for example, `__filename` and
`__dirname` in the module, or the errors stack traces involving functions from
the VFS modules. ES modules in the VFS are similarly identified by the `file:` URL of
their VFS paths and this is reflected in e.g. `import.meta.url`.
Like modules loaded from the real file system, modules loaded from the VFS are
cached on the first load. When `require()` or `import()` is used to load an absolute
path or URL that falls under the mounted VFS multiple times, the module is only loaded
once and subsequent calls return the same instance.
Calling [`vfs.unmount()`][] invalidates the modules that were loaded
from the mount point: a subsequent `require()` or `import` of a path
under a re-created mount re-reads the file from the newly mounted
VFS rather than returning a stale module. Modules loaded from other
VFS instances or from the real file system are unaffected.
Mounting and unmounting do not stop any module execution that is
already started, or invalidate any objects materialized from VFS
modules that are already executed. As with modules in the real file
system, the callers are responsible for avoiding removal or
invalidation of modules in the virtual file system while they are
being loaded.
## Class: `VirtualProvider`
<!-- YAML
@@ -316,10 +537,23 @@ fields use synthetic but stable values:
* `blocks` is `Math.ceil(size / 512)`.
* Times default to the moment the entry was created/last modified.
[CommonJS resolution algorithm]: modules.md#all-together
[ES modules resolution algorithm]: esm.md#resolution-algorithm
[Explicit Resource Management]: https://github.com/tc39/proposal-explicit-resource-management
[`MemoryProvider`]: #class-memoryprovider
[`RealFSProvider`]: #class-realfsprovider
[`VirtualFileSystem`]: #class-virtualfilesystem
[`VirtualProvider`]: #class-virtualprovider
[`fs.BigIntStats`]: fs.md#class-fsstats
[`fs.Stats`]: fs.md#class-fsstats
[`import.meta.resolve()`]: esm.md#importmetaresolvespecifier
[`node:fs`]: fs.md
[`require()`]: modules.md#requireid
[`require.resolve()`]: modules.md#requireresolverequest-options
[`url.pathToFileURL()`]: url.md#urlpathtofileurlpath-options
[`vfs.mount()`]: #vfsmount
[`vfs.mountPointURL`]: #vfsmountpointurl
[`vfs.mountPoint`]: #vfsmountpoint
[`vfs.unmount()`]: #vfsunmount
[loading from `node_modules` folders]: modules.md#loading-from-node_modules-folders
[the global folders]: modules.md#loading-from-the-global-folders
+14 -4
View File
@@ -2128,8 +2128,13 @@ function fstatSync(fd, options = { __proto__: null, bigint: false }) {
function lstatSync(path, options = { __proto__: null, bigint: false, throwIfNoEntry: true }) {
const h = vfsState.handlers;
if (h !== null) {
const result = h.lstatSync(path, options);
if (result !== undefined) return result;
try {
const result = h.lstatSync(path, options);
if (result !== undefined) return result;
} catch (err) {
if (err?.code === 'ENOENT' && options?.throwIfNoEntry === false) return;
throw err;
}
}
path = getValidatedPath(path);
if (permission.isEnabled() && !permission.has('fs.read', path)) {
@@ -2162,8 +2167,13 @@ function lstatSync(path, options = { __proto__: null, bigint: false, throwIfNoEn
function statSync(path, options = { __proto__: null, bigint: false, throwIfNoEntry: true }) {
const h = vfsState.handlers;
if (h !== null) {
const result = h.statSync(path, options);
if (result !== undefined) return result;
try {
const result = h.statSync(path, options);
if (result !== undefined) return result;
} catch (err) {
if (err?.code === 'ENOENT' && options?.throwIfNoEntry === false) return undefined;
throw err;
}
}
const stats = binding.stat(
getValidatedPath(path),
+40 -8
View File
@@ -113,6 +113,7 @@ const kFormat = Symbol('kFormat');
// Set first due to cycle with ESM loader functions.
module.exports = {
purgeModuleCachesForPrefix,
kModuleSource,
kModuleExport,
kModuleExportNames,
@@ -155,19 +156,18 @@ const {
} = internalBinding('contextify');
const assert = require('internal/assert');
const fs = require('fs');
const path = require('path');
const internalFsBinding = internalBinding('fs');
const { safeGetenv } = internalBinding('credentials');
const {
cleanForVfsPrefix,
getCjsConditions,
getCjsConditionsArray,
initializeCjsConditions,
loaderMethods,
loadBuiltinModule,
makeRequireFunction,
setHasStartedUserCJSExecution,
stripBOM,
toRealPath,
getRequireStack,
} = require('internal/modules/helpers');
const {
@@ -278,7 +278,7 @@ function stat(filename) {
const result = statCache.get(filename);
if (result !== undefined) { return result; }
}
const result = internalFsBinding.internalModuleStat(filename);
const result = loaderMethods.internalModuleStat(filename);
if (statCache !== null && result >= 0) {
// Only set cache when `internalModuleStat(filename)` succeeds.
statCache.set(filename, result);
@@ -286,6 +286,22 @@ function stat(filename) {
return result;
}
/**
* Drop every module-loader cache entry (Module._cache,
* Module._pathCache, the stat cache) whose filename lives under
* `mountPoint`. Called by internal/vfs/setup.js when a VFS is
* unmounted. VFS mount points live in a reserved namespace that
* cannot collide with real paths, so a prefix scan is exact:
* real-fs entries and other-VFS entries never match.
* @param {string} mountPoint Absolute mount-point path
*/
function purgeModuleCachesForPrefix(mountPoint) {
cleanForVfsPrefix(Module._cache, mountPoint);
// Module._pathCache keys are `request\0parent` tokens; match on value.
cleanForVfsPrefix(Module._pathCache, mountPoint, true);
if (statCache !== null) { cleanForVfsPrefix(statCache, mountPoint); }
}
let _stat = stat;
ObjectDefineProperty(Module, '_stat', {
__proto__: null,
@@ -585,7 +601,7 @@ function tryFile(requestPath, isMain) {
if (getOptionValue(isMain ? '--preserve-symlinks-main' : '--preserve-symlinks')) {
return path.resolve(requestPath);
}
return toRealPath(requestPath);
return loaderMethods.realpathSync(requestPath);
}
/**
@@ -829,7 +845,7 @@ Module._findPath = function(request, paths, isMain, conditions = getCjsCondition
if (getOptionValue('--preserve-symlinks')) {
filename = path.resolve(basePath);
} else {
filename = toRealPath(basePath);
filename = loaderMethods.realpathSync(basePath);
}
} else if (getOptionValue('--preserve-symlinks-main')) {
// For the main module, we use the --preserve-symlinks-main flag instead
@@ -842,7 +858,7 @@ Module._findPath = function(request, paths, isMain, conditions = getCjsCondition
// is needed.
filename = path.resolve(basePath);
} else {
filename = toRealPath(basePath);
filename = loaderMethods.realpathSync(basePath);
}
}
@@ -903,6 +919,11 @@ if (isWindows) {
return [from + 'node_modules'];
}
// The walk stops at the resolution root (e.g. a VFS mount point)
// instead of continuing to the file system root.
const resolutionRoot = loaderMethods.getResolutionRoot(from);
const stopLen = resolutionRoot === undefined ? -1 : resolutionRoot.length;
/** @type {string[]} */
const paths = [];
for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
@@ -921,6 +942,9 @@ if (isWindows) {
StringPrototypeSlice(from, 0, last) + '\\node_modules',
);
}
if (last === stopLen) {
return paths;
}
last = i;
p = 0;
} else if (p !== -1) {
@@ -949,6 +973,11 @@ if (isWindows) {
return ['/node_modules'];
}
// The walk stops at the resolution root (e.g. a VFS mount point)
// instead of continuing to the file system root.
const resolutionRoot = loaderMethods.getResolutionRoot(from);
const stopLen = resolutionRoot === undefined ? -1 : resolutionRoot.length;
// note: this approach *only* works when the path is guaranteed
// to be absolute. Doing a fully-edge-case-correct path.split
// that works on both Windows and Posix is non-trivial.
@@ -963,6 +992,9 @@ if (isWindows) {
StringPrototypeSlice(from, 0, last) + '/node_modules',
);
}
if (last === stopLen) {
return paths;
}
last = i;
p = 0;
} else if (p !== -1) {
@@ -1235,7 +1267,7 @@ function defaultLoadImpl(filename, format) {
case 'module-typescript':
case 'commonjs-typescript':
case 'typescript': {
return fs.readFileSync(filename, 'utf8');
return loaderMethods.readFileSync(filename, 'utf8');
}
case 'builtin':
return null;
+2 -2
View File
@@ -10,7 +10,6 @@ const {
} = primordials;
const { getOptionValue } = require('internal/options');
const { getValidatedPath } = require('internal/fs/utils');
const fsBindings = internalBinding('fs');
const { internal: internalConstants } = internalBinding('constants');
const extensionFormatMap = {
@@ -66,7 +65,8 @@ function mimeToFormat(mime) {
*/
function getFormatOfExtensionlessFile(url) {
const path = getValidatedPath(url);
switch (fsBindings.getFormatOfExtensionlessFile(path)) {
const { loaderMethods } = require('internal/modules/helpers');
switch (loaderMethods.getFormatOfExtensionlessFile(path)) {
case internalConstants.EXTENSIONLESS_FORMAT_WASM:
return 'wasm';
default:
+2 -2
View File
@@ -9,7 +9,7 @@ const {
const { defaultGetFormat } = require('internal/modules/esm/get_format');
const { validateAttributes, emitImportAssertionWarning } = require('internal/modules/esm/assert');
const fs = require('fs');
const { loaderMethods } = require('internal/modules/helpers');
const { Buffer: { from: BufferFrom } } = require('buffer');
@@ -35,7 +35,7 @@ function getSourceSync(url, context) {
// behavior - DO NOT depend on the patchability in new code: Node.js
// internals may stop going through the JavaScript fs module entirely.
// Prefer module.registerHooks() or other more formal fs hooks released in the future.
source = fs.readFileSync(url);
source = loaderMethods.readFileSync(url);
} else if (protocol === 'data:') {
const { dataURLProcessor } = require('internal/data_url'); // Only for data: URLs.
const result = dataURLProcessor(url);
+8 -41
View File
@@ -9,7 +9,6 @@ const {
ObjectPrototypeHasOwnProperty,
RegExpPrototypeExec,
RegExpPrototypeSymbolReplace,
SafeMap,
SafeSet,
String,
StringPrototypeEndsWith,
@@ -23,16 +22,13 @@ const {
encodeURIComponent,
} = primordials;
const assert = require('internal/assert');
const internalFS = require('internal/fs/utils');
const { BuiltinModule } = require('internal/bootstrap/realm');
const fs = require('fs');
const { getOptionValue } = require('internal/options');
// Do not eagerly grab .manifest, it may be in TDZ
const { sep, posix: { relative: relativePosixPath }, resolve, join } = require('path');
const { URL, pathToFileURL, fileURLToPath, isURL, URLParse } = require('internal/url');
const { getCWDURL, setOwnProperty, kEmptyObject } = require('internal/util');
const { canParse: URLCanParse } = internalBinding('url');
const { legacyMainResolve: FSLegacyMainResolve } = internalBinding('fs');
const {
ERR_INPUT_TYPE_NOT_ALLOWED,
ERR_INVALID_ARG_TYPE,
@@ -49,7 +45,11 @@ const {
const { defaultGetFormatWithoutErrors } = require('internal/modules/esm/get_format');
const { getConditionsSet } = require('internal/modules/esm/utils');
const packageJsonReader = require('internal/modules/package_json_reader');
const internalFsBinding = internalBinding('fs');
const {
legacyMainResolveExtensions,
legacyMainResolveExtensionsIndexes,
loaderMethods,
} = require('internal/modules/helpers');
/**
* @typedef {import('internal/modules/esm/package_config.js').PackageConfig} PackageConfig
@@ -150,37 +150,6 @@ function emitLegacyIndexDeprecation(url, path, pkgPath, base, main) {
}
}
const realpathCache = new SafeMap();
const legacyMainResolveExtensions = [
'',
'.js',
'.json',
'.node',
'/index.js',
'/index.json',
'/index.node',
'./index.js',
'./index.json',
'./index.node',
];
const legacyMainResolveExtensionsIndexes = {
// 0-6: when packageConfig.main is defined
kResolvedByMain: 0,
kResolvedByMainJs: 1,
kResolvedByMainJson: 2,
kResolvedByMainNode: 3,
kResolvedByMainIndexJs: 4,
kResolvedByMainIndexJson: 5,
kResolvedByMainIndexNode: 6,
// 7-9: when packageConfig.main is NOT defined,
// or when the previous case didn't found the file
kResolvedByPackageAndJs: 7,
kResolvedByPackageAndJson: 8,
kResolvedByPackageAndNode: 9,
};
/**
* Legacy CommonJS main resolution:
* 1. let M = pkg_url + (json main field)
@@ -199,7 +168,7 @@ function legacyMainResolve(packageJSONUrl, packageConfig, base) {
const baseStringified = isURL(base) ? base.href : base;
const resolvedOption = FSLegacyMainResolve(pkgPath, packageConfig.main, baseStringified);
const resolvedOption = loaderMethods.legacyMainResolve(pkgPath, packageConfig.main, baseStringified);
const maybeMain = resolvedOption <= legacyMainResolveExtensionsIndexes.kResolvedByMainIndexNode ?
packageConfig.main || './' : '';
@@ -245,7 +214,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
throw err;
}
const stats = internalFsBinding.internalModuleStat(
const stats = loaderMethods.internalModuleStat(
StringPrototypeEndsWith(path, '/') ? StringPrototypeSlice(path, -1) : path,
);
@@ -278,9 +247,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
// behavior - DO NOT depend on the patchability in new code: Node.js
// internals may stop going through the JavaScript fs module entirely.
// Prefer module.registerHooks() or other more formal fs hooks released in the future.
const real = fs.realpathSync(path, {
[internalFS.realpathCacheKey]: realpathCache,
});
const real = loaderMethods.realpathSync(path);
const { search, hash } = resolved;
resolved =
pathToFileURL(real + (StringPrototypeEndsWith(path, sep) ? '/' : ''));
+167 -11
View File
@@ -3,15 +3,20 @@
const {
ArrayPrototypeForEach,
ArrayPrototypePush,
MapPrototypeForEach,
MapPrototypeGet,
ObjectDefineProperty,
ObjectFreeze,
ObjectKeys,
ObjectPrototypeHasOwnProperty,
ReflectApply,
SafeMap,
SafeSet,
StringPrototypeCharCodeAt,
StringPrototypeIncludes,
StringPrototypeSlice,
StringPrototypeStartsWith,
Symbol,
} = primordials;
const {
ERR_INVALID_ARG_TYPE,
@@ -28,7 +33,7 @@ const { pathToFileURL, fileURLToPath, URL } = require('internal/url');
const assert = require('internal/assert');
const { getOptionValue } = require('internal/options');
const { setOwnProperty, getLazy } = require('internal/util');
const { kEmptyObject, setOwnProperty, getLazy } = require('internal/util');
const { inspect } = require('internal/util/inspect');
const { emitWarningSync } = require('internal/process/warning');
const {
@@ -39,13 +44,15 @@ const {
const lazyTmpdir = getLazy(() => require('os').tmpdir());
const { join } = path;
const internalFsBinding = internalBinding('fs');
const { canParse: URLCanParse } = internalBinding('url');
const modulesBinding = internalBinding('modules');
const {
enableCompileCache: _enableCompileCache,
getCompileCacheDir: _getCompileCacheDir,
compileCacheStatus: _compileCacheStatus,
flushCompileCache,
} = internalBinding('modules');
} = modulesBinding;
const lazyCJSLoader = getLazy(() => require('internal/modules/cjs/loader'));
let debug = require('internal/util/debuglog').debuglog('module', (fn) => {
@@ -61,15 +68,128 @@ let debug = require('internal/util/debuglog').debuglog('module', (fn) => {
* @type {Map<string, string>}
*/
const realpathCache = new SafeMap();
/**
* Resolves the path of a given `require` specifier, following symlinks.
* @param {string} requestPath The `require` specifier
* @returns {string}
*/
function toRealPath(requestPath) {
return fs.realpathSync(requestPath, {
// Toggleable loader hooks for VFS support. Overrides that return
// `undefined` fall through to the pinned native implementation.
const nativeLoaderMethods = {
internalModuleStat: (filename) => internalFsBinding.internalModuleStat(filename),
readFileSync: (filename, options) => fs.readFileSync(filename, options),
realpathSync: (requestPath) => fs.realpathSync(requestPath, {
[internalFS.realpathCacheKey]: realpathCache,
});
}),
legacyMainResolve: (pkgPath, main, base) =>
internalFsBinding.legacyMainResolve(pkgPath, main, base),
getFormatOfExtensionlessFile: (filePath) =>
internalFsBinding.getFormatOfExtensionlessFile(filePath),
readPackageJSON: (jsonPath, isESM, base, specifier) =>
modulesBinding.readPackageJSON(jsonPath, isESM, base, specifier),
getNearestParentPackageJSON: (checkPath) =>
modulesBinding.getNearestParentPackageJSON(checkPath),
getPackageScopeConfig: (resolved) =>
modulesBinding.getPackageScopeConfig(resolved),
getPackageType: (url) => modulesBinding.getPackageType(url),
// Synthetic hook with no native counterpart: returns the directory at
// which upward walks (node_modules lookups) must stop for `path`, or
// undefined to walk to the file system root.
getResolutionRoot: () => undefined,
};
const loaderMethodKeys = ObjectKeys(nativeLoaderMethods);
// Overrides use this sentinel when they handled a request but their method's
// meaningful result is `undefined`. A plain `undefined` means fall through to
// the native implementation.
const kLoaderOverrideNoResult = Symbol('kLoaderOverrideNoResult');
const loaderOverrides = new SafeMap();
let hasLoaderOverrides = false;
/**
* @param {string} key Name of the wrapped method in `nativeLoaderMethods`.
* @param {Function} originalFn Native fallback pinned at load time.
* @returns {Function} Wrapper that consults `loaderOverrides` and falls
* through to `originalFn` when no override is set or when the
* override returns `undefined`.
*/
function wrapLoaderMethod(key, originalFn) {
return function loaderMethodWrapper(...args) {
if (hasLoaderOverrides) {
const override = MapPrototypeGet(loaderOverrides, key);
if (override !== undefined) {
const result = ReflectApply(override, undefined, args);
if (result === kLoaderOverrideNoResult) { return undefined; }
if (result !== undefined) { return result; }
}
}
return ReflectApply(originalFn, undefined, args);
};
}
/**
* Toggleable versions of the loader's fs and package.json methods, keyed
* like `nativeLoaderMethods`. The module loader calls these instead of the
* native implementations so that VFS overrides can be consulted first.
*/
const loaderMethods = { __proto__: null };
for (let i = 0; i < loaderMethodKeys.length; i++) {
const key = loaderMethodKeys[i];
loaderMethods[key] = wrapLoaderMethod(key, nativeLoaderMethods[key]);
}
/**
* Set override functions for the module loader's fs and package.json
* operations. Fields are keyed like `nativeLoaderMethods`; missing or
* nullish fields disable that hook (fast-path restored).
* @param {Record<string, Function|undefined>} overrides
*/
function setLoaderOverrides(overrides = kEmptyObject) {
for (let i = 0; i < loaderMethodKeys.length; i++) {
const key = loaderMethodKeys[i];
const override = overrides[key];
if (override) {
loaderOverrides.set(key, override);
} else {
loaderOverrides.delete(key);
}
}
hasLoaderOverrides = loaderOverrides.size > 0;
}
/**
* Delete every entry in `cache` whose owned string is under
* `mountPoint`. `cache` is either a plain object (Module._cache,
* Module._pathCache) or a SafeMap (statCache, realpathCache,
* the package.json caches). By default the entry KEY is tested;
* pass `byValue: true` to test the entry value instead (used for
* Module._pathCache whose keys are `request\0parent` tokens and
* whose values are the resolved filenames).
*
* Mount points live in the reserved VFS namespace so a prefix scan
* on strings is exact - real-fs entries never match.
* @param {object|Map<string, *>} cache
* @param {string} mountPoint Absolute mount-point path
* @param {boolean} [byValue] Test the entry value instead of the key
*/
function cleanForVfsPrefix(cache, mountPoint, byValue = false) {
const prefix = mountPoint + path.sep;
const owns = (s) =>
typeof s === 'string' &&
(s === mountPoint || StringPrototypeStartsWith(s, prefix));
if (typeof cache.forEach === 'function') {
MapPrototypeForEach(cache, (v, k) => {
if (owns(byValue ? v : k)) { cache.delete(k); }
});
} else {
ArrayPrototypeForEach(ObjectKeys(cache), (k) => {
if (owns(byValue ? cache[k] : k)) { delete cache[k]; }
});
}
}
/**
* Drop realpath-cache entries under an unmounted VFS mount point.
* Called by internal/vfs/setup.js.
* @param {string} mountPoint Absolute mount-point path
*/
function purgeRealpathCacheForPrefix(mountPoint) {
cleanForVfsPrefix(realpathCache, mountPoint);
}
/** @type {Set<string>} */
@@ -532,9 +652,41 @@ function getRequireStack(parent) {
return requireStack;
}
// Suffixes tried by legacy CommonJS `main` resolution; indexes match
// the values returned by the `legacyMainResolve` C++ binding.
const legacyMainResolveExtensions = [
'',
'.js',
'.json',
'.node',
'/index.js',
'/index.json',
'/index.node',
'./index.js',
'./index.json',
'./index.node',
];
const legacyMainResolveExtensionsIndexes = {
// 0-6: when packageConfig.main is defined
kResolvedByMain: 0,
kResolvedByMainJs: 1,
kResolvedByMainJson: 2,
kResolvedByMainNode: 3,
kResolvedByMainIndexJs: 4,
kResolvedByMainIndexJson: 5,
kResolvedByMainIndexNode: 6,
// 7-9: when packageConfig.main is not defined
kResolvedByPackageAndJs: 7,
kResolvedByPackageAndJson: 8,
kResolvedByPackageAndNode: 9,
};
module.exports = {
addBuiltinLibsToObject,
assertBufferSource,
cleanForVfsPrefix,
purgeRealpathCacheForPrefix,
constants,
enableCompileCache,
flushCompileCache,
@@ -543,13 +695,17 @@ module.exports = {
getCjsConditionsArray,
getCompileCacheDir,
initializeCjsConditions,
legacyMainResolveExtensions,
legacyMainResolveExtensionsIndexes,
kLoaderOverrideNoResult,
loaderMethods,
loadBuiltinModuleForEmbedder,
loadBuiltinModule,
makeRequireFunction,
normalizeReferrerURL,
setLoaderOverrides,
stringify,
stripBOM,
toRealPath,
hasStartedUserCJSExecution() {
return _hasStartedUserCJSExecution;
},
+34 -7
View File
@@ -8,6 +8,7 @@ const {
SafeMap,
StringPrototypeIndexOf,
StringPrototypeSlice,
StringPrototypeStartsWith,
} = primordials;
const {
fileURLToPath,
@@ -25,10 +26,12 @@ const {
} = require('internal/errors');
const { kEmptyObject, isWindows } = require('internal/util');
const permission = require('internal/process/permission');
const modulesBinding = internalBinding('modules');
const path = require('path');
const { validateString } = require('internal/validators');
const internalFsBinding = internalBinding('fs');
const {
cleanForVfsPrefix,
loaderMethods,
} = require('internal/modules/helpers');
/**
@@ -123,7 +126,7 @@ const requiresJSONParse = (value) => (value !== undefined && (value[0] === '[' |
function read(jsonPath, { base, specifier, isESM } = kEmptyObject) {
// This function will be called by both CJS and ESM, so we need to make sure
// non-null attributes are converted to strings.
const parsed = modulesBinding.readPackageJSON(
const parsed = loaderMethods.readPackageJSON(
jsonPath,
isESM,
base == null ? undefined : `${base}`,
@@ -194,7 +197,7 @@ function getNearestParentPackageJSON(checkPath) {
const key = permissionEnabled ? checkPath : getTraversalStartDirectory(checkPath);
let parentPackageJSONPath = cache.get(key);
if (parentPackageJSONPath === undefined) {
const result = modulesBinding.getNearestParentPackageJSON(checkPath);
const result = loaderMethods.getNearestParentPackageJSON(checkPath);
if (result === undefined) {
parentPackageJSONPath = null;
} else {
@@ -220,7 +223,7 @@ function getNearestParentPackageJSON(checkPath) {
* @returns {import('typings/internalBinding/modules').PackageConfig} - The package configuration.
*/
function getPackageScopeConfig(resolved) {
const result = modulesBinding.getPackageScopeConfig(`${resolved}`);
const result = loaderMethods.getPackageScopeConfig(`${resolved}`);
if (ArrayIsArray(result)) {
const { data, exists, path } = deserializePackageJSON(`${resolved}`, result);
@@ -249,7 +252,7 @@ function getPackageScopeConfig(resolved) {
* @returns {string}
*/
function getPackageType(url) {
const type = modulesBinding.getPackageType(`${url}`);
const type = loaderMethods.getPackageType(`${url}`);
return type ?? 'none';
}
@@ -308,9 +311,14 @@ function getPackageJSONURL(specifier, base) {
let packageJSONUrl = new URL(`./node_modules/${packageName}/package.json`, base);
let packageJSONPath = fileURLToPath(packageJSONUrl);
// The walk stops at the resolution root (e.g. a VFS mount point)
// instead of continuing to the file system root.
const resolutionRoot = loaderMethods.getResolutionRoot(packageJSONPath);
const resolutionRootPrefix =
resolutionRoot === undefined ? undefined : resolutionRoot + path.sep;
let lastPath;
do {
const stat = internalFsBinding.internalModuleStat(
const stat = loaderMethods.internalModuleStat(
StringPrototypeSlice(packageJSONPath, 0, packageJSONPath.length - 13),
);
// Check for !stat.isDirectory()
@@ -321,6 +329,10 @@ function getPackageJSONURL(specifier, base) {
packageJSONUrl,
);
packageJSONPath = fileURLToPath(packageJSONUrl);
if (resolutionRootPrefix !== undefined &&
!StringPrototypeStartsWith(packageJSONPath, resolutionRootPrefix)) {
break;
}
continue;
}
@@ -383,6 +395,20 @@ function findPackageJSON(specifier, base = 'data:') {
return pkg?.path;
}
/**
* Drop package.json-cache entries under an unmounted VFS mount point.
* Called by internal/vfs/setup.js. A module path and its owning
* package.json path always live in the same mount (the pjson search
* walks up from the module and stops at the mount root), so a single
* key test on each map is exact.
* @param {string} mountPoint Absolute mount-point path
*/
function purgePackageJSONCacheForPrefix(mountPoint) {
cleanForVfsPrefix(directoryToParentPackageJSONPathCache, mountPoint);
cleanForVfsPrefix(moduleToParentPackageJSONCache, mountPoint);
cleanForVfsPrefix(deserializedPackageJSONCache, mountPoint);
}
module.exports = {
read,
getNearestParentPackageJSON,
@@ -390,4 +416,5 @@ module.exports = {
getPackageType,
getPackageJSONURL,
findPackageJSON,
purgePackageJSONCacheForPrefix,
};
+2 -2
View File
@@ -37,8 +37,8 @@ function resolveMainPath(main) {
const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
if (!preserveSymlinksMain) {
const { toRealPath } = require('internal/modules/helpers');
mainPath = toRealPath(mainPath);
const { loaderMethods } = require('internal/modules/helpers');
mainPath = loaderMethods.realpathSync(mainPath);
}
return mainPath;
+71 -50
View File
@@ -3,6 +3,7 @@
const {
MathRandom,
ObjectFreeze,
StringPrototypeStartsWith,
Symbol,
SymbolDispose,
} = primordials;
@@ -15,10 +16,10 @@ const {
const { validateBoolean } = require('internal/validators');
const { MemoryProvider } = require('internal/vfs/providers/memory');
const path = require('path');
const { posix: pathPosix, isAbsolute, resolve: resolvePath } = path;
const { posix: pathPosix, resolve: resolvePath, sep, toNamespacedPath } = path;
const { join: joinPath } = pathPosix;
const {
isUnderMountPoint,
getLayerRoot,
getRelativePath,
} = require('internal/vfs/router');
const {
@@ -38,13 +39,30 @@ let debug = require('internal/util/debuglog').debuglog('vfs', (fn) => {
debug = fn;
});
// Private symbols
const kProvider = Symbol('kProvider');
const kMountPoint = Symbol('kMountPoint');
// Cached normalizeMountedPath(kMountPoint) so the hot dispatch path
// does not recompute toNamespacedPath(resolve(...)) on every fs call.
const kNormalizedMountPoint = Symbol('kNormalizedMountPoint');
const kMounted = Symbol('kMounted');
const kPromises = Symbol('kPromises');
const kLayerId = Symbol('kLayerId');
let nextLayerId = 0;
/**
* Normalizes paths for mount-point comparisons. On Windows, `path.resolve('/x')`
* yields `C:\x`, while loader internals often pass namespaced paths like
* `\\?\C:\x`. Compare using a single canonical representation so POSIX-style
* rooted test paths, drive-absolute paths, and namespaced paths all route to the
* same VFS mount.
* @param {string} inputPath
* @returns {string}
*/
function normalizeMountedPath(inputPath) {
return toNamespacedPath(resolvePath(inputPath));
}
// Lazy-loaded VFS setup
let registerVFS;
let deregisterVFS;
@@ -68,15 +86,11 @@ class VirtualFileSystem {
* @param {boolean} [options.emitExperimentalWarning] Emit the experimental warning (default: true)
*/
constructor(providerOrOptions, options = kEmptyObject) {
// Handle case where first arg is options object (no provider)
let provider = null;
if (providerOrOptions !== undefined && providerOrOptions !== null) {
if (typeof providerOrOptions.openSync === 'function') {
// It's a provider
provider = providerOrOptions;
} else if (typeof providerOrOptions === 'object') {
// It's options (no provider specified)
options = providerOrOptions;
provider = null;
}
@@ -92,8 +106,10 @@ class VirtualFileSystem {
this[kProvider] = provider ?? new MemoryProvider();
this[kMountPoint] = null;
this[kNormalizedMountPoint] = null;
this[kMounted] = false;
this[kPromises] = null; // Lazy-initialized
this[kPromises] = null;
this[kLayerId] = nextLayerId++;
}
/**
@@ -112,6 +128,17 @@ class VirtualFileSystem {
return this[kMountPoint];
}
/**
* Gets the mount point as a `file:` URL string, or null if not
* mounted.
* @returns {string|null}
*/
get mountPointURL() {
if (this[kMountPoint] === null) return null;
const { pathToFileURL } = require('internal/url');
return pathToFileURL(this[kMountPoint]).href;
}
/**
* Returns true if VFS is mounted.
* @returns {boolean}
@@ -128,23 +155,28 @@ class VirtualFileSystem {
return this[kProvider].readonly;
}
// ==================== Mount ====================
/**
* Mounts the VFS at a specific path prefix.
* @param {string} prefix The mount point path
* @returns {VirtualFileSystem} The VFS instance for chaining
* Mounts the VFS at its reserved mount point and returns that
* mount point. The mount point is `${os.devNull}/vfs/<layerId>` -
* a location that cannot exist on the real file system (`os.devNull`
* is a character device on POSIX and a device-namespace path on
* Windows; neither can have child filesystem entries) - so virtual
* paths never conflate with real paths, and the owning layer of any
* path is decidable from the path alone.
* @returns {string} The absolute mount point
*/
mount(prefix) {
mount() {
if (this[kMounted]) {
throw new ERR_INVALID_STATE('VFS is already mounted');
}
this[kMountPoint] = resolvePath(prefix);
const mountPoint = getLayerRoot(this[kLayerId]);
this[kMountPoint] = mountPoint;
this[kNormalizedMountPoint] = normalizeMountedPath(mountPoint);
this[kMounted] = true;
debug('mount %s', this[kMountPoint]);
debug('mount %s', mountPoint);
loadVfsSetup();
registerVFS(this);
return this;
return mountPoint;
}
/**
@@ -155,6 +187,7 @@ class VirtualFileSystem {
loadVfsSetup();
deregisterVFS(this);
this[kMountPoint] = null;
this[kNormalizedMountPoint] = null;
this[kMounted] = false;
}
@@ -169,20 +202,21 @@ class VirtualFileSystem {
}
/**
* Checks if a path should be handled by this VFS.
* @param {string} inputPath The path to check (must be absolute & normalized)
* Returns true when `normalizedInput` falls inside this VFS's
* reserved mount point. The caller must have already passed the
* input through `normalizeMountedPath`; the dispatch loop in
* `internal/vfs/setup.js` normalizes once and hands the same value
* to every candidate layer.
* @param {string} normalizedInput
* @returns {boolean}
*/
shouldHandle(inputPath) {
if (!this[kMounted] || !this[kMountPoint]) {
return false;
}
const normalized = isAbsolute(inputPath) ? inputPath : resolvePath(inputPath);
return isUnderMountPoint(normalized, this[kMountPoint]);
shouldHandleNormalized(normalizedInput) {
const mountPoint = this[kNormalizedMountPoint];
if (mountPoint === null) return false;
if (normalizedInput === mountPoint) return true;
return StringPrototypeStartsWith(normalizedInput, mountPoint + sep);
}
// ==================== Path Resolution ====================
/**
* Converts an absolute mounted path to a provider-relative POSIX path.
* If not mounted, treats the path as already provider-relative.
@@ -190,12 +224,13 @@ class VirtualFileSystem {
* @returns {string}
*/
#toProviderPath(inputPath) {
if (this[kMounted] && this[kMountPoint]) {
const resolved = isAbsolute(inputPath) ? inputPath : resolvePath(inputPath);
if (!isUnderMountPoint(resolved, this[kMountPoint])) {
const mountPoint = this[kNormalizedMountPoint];
if (mountPoint !== null) {
const resolved = normalizeMountedPath(inputPath);
if (!this.shouldHandleNormalized(resolved)) {
throw createENOENT('open', inputPath);
}
return getRelativePath(resolved, this[kMountPoint]);
return getRelativePath(resolved, mountPoint);
}
return pathPosix.normalize(inputPath);
}
@@ -213,8 +248,6 @@ class VirtualFileSystem {
return providerPath;
}
// ==================== FS Operations (Sync) ====================
/**
* Checks if a path exists synchronously.
* @param {string} filePath The path to check
@@ -294,14 +327,13 @@ class VirtualFileSystem {
const providerPath = this.#toProviderPath(dirPath);
const result = this[kProvider].readdirSync(providerPath, options);
// Fix Dirent parentPath from provider-relative to actual VFS path
// Rewrite Dirent parentPath from provider-relative to VFS path.
if (options?.withFileTypes === true) {
const recursive = options?.recursive === true;
for (let i = 0; i < result.length; i++) {
const dirent = result[i];
if (recursive) {
// In recursive mode, name may contain slashes (e.g. 'a/b.txt').
// Fix to basename only and set correct parentPath.
const slashIdx = dirent.name.lastIndexOf('/');
if (slashIdx !== -1) {
const subdir = dirent.name.slice(0, slashIdx);
@@ -454,8 +486,6 @@ class VirtualFileSystem {
}
}
// ==================== Additional Sync Operations ====================
/**
* Truncates a file synchronously.
* @param {string} filePath The file path
@@ -528,7 +558,6 @@ class VirtualFileSystem {
*/
mkdtempSync(prefix) {
const providerPrefix = this.#toProviderPath(prefix);
// Generate random 6-character suffix like Node does
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let suffix = '';
for (let i = 0; i < 6; i++) {
@@ -567,8 +596,6 @@ class VirtualFileSystem {
return new Blob([content], { type });
}
// ==================== File Descriptor Operations ====================
/**
* Opens a file synchronously and returns a file descriptor.
* @param {string} filePath The path to open
@@ -643,8 +670,6 @@ class VirtualFileSystem {
return vfd.entry.statSync(options);
}
// ==================== FS Operations (Async with Callbacks) ====================
/**
* Reads a file asynchronously.
* @param {string} filePath The path to read
@@ -991,8 +1016,6 @@ class VirtualFileSystem {
}
}
// ==================== Stream Operations ====================
/**
* Creates a readable stream for a virtual file.
* @param {string} filePath The path to the file
@@ -1013,8 +1036,6 @@ class VirtualFileSystem {
return new VirtualWriteStream(this, filePath, options);
}
// ==================== Watch Operations ====================
/**
* Watches a file or directory for changes.
* @param {string} filePath The path to watch
@@ -1065,8 +1086,6 @@ class VirtualFileSystem {
this[kProvider].unwatchFile(providerPath, listener);
}
// ==================== Promise API ====================
/**
* Gets the promises API for this VFS instance.
* @returns {object} Promise-based fs methods
@@ -1085,7 +1104,7 @@ class VirtualFileSystem {
#createPromisesAPI() {
const provider = this[kProvider];
// Use arrow function to capture `this` for private method access
// Arrow functions capture `this` for private method access.
const toProviderPath = (p) => this.#toProviderPath(p);
const toMountedPath = (p) => this.#toMountedPath(p);
@@ -1273,4 +1292,6 @@ class VirtualFileSystem {
module.exports = {
VirtualFileSystem,
kLayerId,
normalizeMountedPath,
};
+57 -24
View File
@@ -2,45 +2,78 @@
const {
ArrayPrototypeJoin,
StringPrototypeCharCodeAt,
StringPrototypeSplit,
StringPrototypeStartsWith,
} = primordials;
const { isAbsolute, relative, sep } = require('path');
const { relative, resolve, sep, toNamespacedPath } = require('path');
// `path.sep` is required here because on Windows `path.resolve('/virtual')`
// produces 'C:\virtual' and all resolved paths use backslashes - a hardcoded
// '/' check would never match. The trailing-separator guard handles root
// mount points like 'C:\' so we don't end up with 'C:\\'.
function isUnderMountPoint(normalizedPath, mountPoint) {
if (normalizedPath === mountPoint) {
return true;
}
if (mountPoint === '/') {
return StringPrototypeStartsWith(normalizedPath, '/');
}
const prefix = mountPoint[mountPoint.length - 1] === sep ?
mountPoint : mountPoint + sep;
return StringPrototypeStartsWith(normalizedPath, prefix);
// All VFS mount points live under `${os.devNull}/vfs/<id>/`. os.devNull
// is a character device on POSIX (`/dev/null`) and a device-namespace
// path on Windows (`\\.\NUL`); neither can have children, so no real
// file-system path can exist under this root and path ownership is
// decidable from the path alone.
let vfsRoot;
let normalizedVfsRoot;
function getVfsRoot() {
vfsRoot ??= require('os').devNull + sep + 'vfs';
return vfsRoot;
}
// Returns a POSIX-style relative path the provider can consume. Uses
// `path.relative()` so Windows backslash paths are handled correctly, then
// re-joins with forward slashes for the provider's internal POSIX format.
function getNormalizedVfsRoot() {
normalizedVfsRoot ??= toNamespacedPath(resolve(getVfsRoot()));
return normalizedVfsRoot;
}
/**
* Returns the reserved mount point for a VFS layer:
* `${os.devNull}/vfs/<id>`.
* @param {number} layerId
* @returns {string}
*/
function getLayerRoot(layerId) {
return getVfsRoot() + sep + layerId;
}
/**
* Extracts the layer id from a normalized path under the VFS root, or
* returns -1 when the path does not carry a well-formed `.../vfs/<id>`
* segment. The caller must have verified that `normalizedPath` starts
* with the normalized VFS root plus a separator.
* @param {string} normalizedPath
* @returns {number}
*/
function getLayerIdFromPath(normalizedPath) {
const start = getNormalizedVfsRoot().length + 1;
let id = 0;
let i = start;
const len = normalizedPath.length;
if (i >= len) return -1;
for (; i < len; i++) {
const c = StringPrototypeCharCodeAt(normalizedPath, i);
if (c === 47 || c === 92) break; // '/' or '\\'
if (c < 48 || c > 57) return -1; // not a digit
id = id * 10 + (c - 48);
}
if (i === start) return -1;
return id;
}
// POSIX-style relative path for the provider. `path.relative()` handles
// Windows backslashes; we re-join with forward slashes.
function getRelativePath(normalizedPath, mountPoint) {
if (normalizedPath === mountPoint) {
return '/';
}
if (mountPoint === '/') {
return normalizedPath;
}
const rel = relative(mountPoint, normalizedPath);
const segments = StringPrototypeSplit(rel, sep);
return '/' + ArrayPrototypeJoin(segments, '/');
}
module.exports = {
isUnderMountPoint,
getLayerIdFromPath,
getLayerRoot,
getNormalizedVfsRoot,
getRelativePath,
isAbsolutePath: isAbsolute,
};
+424 -167
View File
@@ -1,30 +1,40 @@
'use strict';
const {
ArrayPrototypeIndexOf,
ArrayPrototypePush,
ArrayPrototypeSplice,
ArrayPrototypeForEach,
MapPrototypeForEach,
ObjectKeys,
PromiseResolve,
SafeMap,
String,
StringPrototypeEndsWith,
StringPrototypeStartsWith,
} = primordials;
const { Buffer } = require('buffer');
const { isArrayBufferView } = require('internal/util/types');
const { resolve, sep } = require('path');
const { fileURLToPath, URL } = require('internal/url');
const { dirname, join, sep } = require('path');
const { fileURLToPath, pathToFileURL, URL } = require('internal/url');
const { kEmptyObject } = require('internal/util');
const { validateObject } = require('internal/validators');
const {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_STATE,
ERR_MODULE_NOT_FOUND,
},
} = require('internal/errors');
const { createENOENT, createEXDEV } = require('internal/vfs/errors');
const { kLayerId, normalizeMountedPath } = require('internal/vfs/file_system');
const {
getLayerIdFromPath,
getNormalizedVfsRoot,
} = require('internal/vfs/router');
const { getVirtualFd, closeVirtualFd } = require('internal/vfs/fd');
const { assertEncoding, vfsState, setVfsHandlers } = require('internal/fs/utils');
const { assertEncoding, setVfsHandlers } = require('internal/fs/utils');
const permission = require('internal/process/permission');
const { getOptionValue } = require('internal/options');
const nativeModulesBinding = internalBinding('modules');
let debug = require('internal/util/debuglog').debuglog('vfs', (fn) => {
debug = fn;
});
@@ -72,11 +82,12 @@ function writeFileSyncFd(fd, data, options) {
return true;
}
// Registry of active VFS instances.
const activeVFSList = [];
const activeVFSLayers = new SafeMap();
let hooksInstalled = false;
let vfsHandlerObj;
// Lazy: os.devNull may not be available at snapshot time.
let normalizedVfsRootPrefix = null;
function registerVFS(vfs) {
if (permission.isEnabled() && !getOptionValue('--allow-fs-vfs')) {
@@ -85,82 +96,211 @@ function registerVFS(vfs) {
'Use --allow-fs-vfs to allow it.',
);
}
if (ArrayPrototypeIndexOf(activeVFSList, vfs) !== -1) return;
const newMount = vfs.mountPoint;
if (newMount != null) {
for (let i = 0; i < activeVFSList.length; i++) {
const existingMount = activeVFSList[i].mountPoint;
if (existingMount == null) continue;
// Use path.sep so the trailing-separator guard works on Windows where
// mountPoint values are resolved to drive-letter / backslash paths.
const newPrefix = newMount === sep ? sep : newMount + sep;
const existingPrefix = existingMount === sep ? sep : existingMount + sep;
if (newMount === existingMount ||
StringPrototypeStartsWith(newMount, existingPrefix) ||
StringPrototypeStartsWith(existingMount, newPrefix)) {
throw new ERR_INVALID_STATE(
`VFS mount '${newMount}' overlaps with existing mount '${existingMount}'`,
);
}
}
}
ArrayPrototypePush(activeVFSList, vfs);
debug('register mount=%s active=%d', newMount, activeVFSList.length);
if (activeVFSLayers.has(vfs[kLayerId])) return;
activeVFSLayers.set(vfs[kLayerId], vfs);
debug('register layer=%d mount=%s active=%d',
vfs[kLayerId], vfs.mountPoint, activeVFSLayers.size);
if (!hooksInstalled) {
vfsHandlerObj = createVfsHandlers();
setVfsHandlers(vfsHandlerObj);
hooksInstalled = true;
} else if (vfsState.handlers === null) {
setVfsHandlers(vfsHandlerObj);
installHooks();
}
}
function deregisterVFS(vfs) {
const index = ArrayPrototypeIndexOf(activeVFSList, vfs);
if (index === -1) return;
ArrayPrototypeSplice(activeVFSList, index, 1);
debug('deregister active=%d', activeVFSList.length);
if (activeVFSList.length === 0) {
setVfsHandlers(null);
if (!activeVFSLayers.delete(vfs[kLayerId])) return;
debug('deregister layer=%d active=%d', vfs[kLayerId], activeVFSLayers.size);
purgeLoaderCachesForVFS(vfs);
if (activeVFSLayers.size === 0) {
uninstallHooks();
}
}
/**
* Resolves a path string to the active VFS that owns it, or null.
* Ownership is decidable from the path alone: all mount points live
* under the reserved `${os.devNull}/vfs/<id>` namespace, so a single
* prefix comparison rejects every real-file-system path and a map
* lookup finds the owning layer. The normalized path is returned
* alongside the layer so downstream helpers can skip renormalization.
* @param {string} inputPath
* @returns {{ vfs: object, normalized: string }|null}
*/
function findVFS(inputPath) {
const normalized = normalizeMountedPath(inputPath);
if (!StringPrototypeStartsWith(normalized, normalizedVfsRootPrefix)) {
return null;
}
const layerId = getLayerIdFromPath(normalized);
if (layerId === -1) return null;
const vfs = activeVFSLayers.get(layerId);
if (vfs === undefined || !vfs.shouldHandleNormalized(normalized)) {
return null;
}
return { vfs, normalized };
}
/**
* Drop the cache entries under `vfs`'s mount point from the
* JS-reachable loader caches. Real-fs entries and other-VFS entries
* are left in place. Because mount points cannot collide with real
* paths - and symlink resolution inside a VFS always yields paths
* under the same mount point - a prefix scan is exact.
* @param {object} vfs The VFS being deregistered
*/
function purgeLoaderCachesForVFS(vfs) {
const mountPoint = vfs.mountPoint;
const cjsLoader = require('internal/modules/cjs/loader');
cjsLoader.purgeModuleCachesForPrefix(mountPoint);
const helpers = require('internal/modules/helpers');
helpers.purgeRealpathCacheForPrefix(mountPoint);
const pkgReader = require('internal/modules/package_json_reader');
pkgReader.purgePackageJSONCacheForPrefix(mountPoint);
const esmLoader = require('internal/modules/esm/loader');
if (esmLoader.isCascadedLoaderInitialized()) {
const loader = esmLoader.getOrInitializeCascadedLoader();
const loadCache = loader.loadCache;
const mountURL = pathToFileURL(mountPoint).href;
const mountURLPrefix = mountURL + '/';
// Iterate via MapPrototypeForEach (not for-of map.keys()) so a
// polluted Map iterator can't break the cleanup path.
if (loadCache && typeof loadCache.delete === 'function') {
MapPrototypeForEach(loadCache, (variants, url) => {
if (typeof url === 'string' &&
(url === mountURL ||
StringPrototypeStartsWith(url, mountURLPrefix)) &&
variants) {
ArrayPrototypeForEach(ObjectKeys(variants), (type) => {
loadCache.delete(url, type);
});
}
});
}
}
}
/**
* Returns the stat result code for a VFS path.
* @param {object} vfs The VFS instance
* @param {string} filePath The path to check
* @returns {number} 0 for file, 1 for directory, -2 for not found
*/
function vfsStat(vfs, filePath) {
try {
const stats = vfs.statSync(filePath);
if (stats.isDirectory()) return 1;
return 0;
} catch (err) {
if (typeof err?.errno === 'number') return err.errno;
throw err;
}
}
/**
* Finds the VFS owning `filename` and stats it.
* @param {string} filename The absolute path to check
* @returns {{ vfs: object, result: number }|null}
*/
function findVFSForStat(filename) {
const r = findVFS(filename);
if (r === null) return null;
return { vfs: r.vfs, result: vfsStat(r.vfs, filename) };
}
/**
* Finds the VFS owning `filename` and reads it.
* @param {string} filename The absolute path to read
* @param {string|object} options Read options
* @returns {{ vfs: object, content: Buffer|string }|null}
*/
function findVFSForRead(filename, options) {
const r = findVFS(filename);
if (r === null) return null;
try {
return { vfs: r.vfs, content: r.vfs.readFileSync(filename, options) };
} catch (e) {
const code = e?.code;
if (code === 'ENOENT' || code === 'EISDIR') {
throw createENOENT('open', filename);
}
throw e;
}
}
/**
* Walk up directories inside `vfs`'s mount looking for package.json.
* Always returns an object. When a package.json is found `.tuple` is
* populated with the C++ binding's serialized shape
* (`[name, main, type, imports, exports, filePath]`); otherwise
* `.sentinel` is the last candidate path checked - matches the "not
* found" marker the C++ binding returns for getPackageScopeConfig.
* Syntactically malformed package.json aborts the walk with
* ERR_INVALID_PACKAGE_CONFIG (thrown by the native parser), matching
* native GetPackageJSON.
* @param {object} vfs The VFS that owns startPath
* @param {string} startPath Absolute path to start from
* @param {string} normalizedStart Same as startPath but passed through
* `normalizeMountedPath`. Used to walk the directory chain so the
* containment check is a plain string prefix rather than a fresh
* `toNamespacedPath(resolve(...))` on every iteration.
* @returns {{ vfs?: object, pjsonPath?: string, tuple?: Array, sentinel: string }}
*/
function findVFSPackageJSON(vfs, startPath, normalizedStart) {
let currentDir = dirname(startPath);
let currentNorm = dirname(normalizedStart);
let lastDir;
let sentinel = join(currentDir, 'package.json');
while (currentDir !== lastDir) {
if (StringPrototypeEndsWith(currentDir, '/node_modules') ||
StringPrototypeEndsWith(currentDir, '\\node_modules')) {
break;
}
if (!vfs.shouldHandleNormalized(currentNorm)) {
break;
}
const pjsonPath = join(currentDir, 'package.json');
sentinel = pjsonPath;
if (vfsStat(vfs, pjsonPath) === 0) {
let content;
try {
content = vfs.readFileSync(pjsonPath);
} catch {
content = null;
}
if (content !== null) {
const tuple = nativeModulesBinding.parsePackageJSON(
content, pjsonPath);
return { vfs, pjsonPath, tuple, sentinel: pjsonPath };
}
}
lastDir = currentDir;
currentDir = dirname(currentDir);
currentNorm = dirname(currentNorm);
}
return { sentinel };
}
function findVFSForExists(filename) {
const normalized = resolve(filename);
for (let i = 0; i < activeVFSList.length; i++) {
const vfs = activeVFSList[i];
if (vfs.shouldHandle(normalized)) {
return { vfs, exists: vfs.existsSync(normalized) };
}
}
return null;
const r = findVFS(filename);
if (r === null) return null;
return { vfs: r.vfs, exists: r.vfs.existsSync(filename) };
}
function findVFSForPath(filename) {
const normalized = resolve(filename);
for (let i = 0; i < activeVFSList.length; i++) {
const vfs = activeVFSList[i];
if (vfs.shouldHandle(normalized)) {
return { vfs, normalized };
}
}
return null;
const r = findVFS(filename);
if (r === null) return null;
return { vfs: r.vfs, path: filename };
}
// Sync read: check exists first, fall through to ENOENT for mounted VFS.
function findVFSWith(filename, syscall, fn) {
const normalized = resolve(filename);
for (let i = 0; i < activeVFSList.length; i++) {
const vfs = activeVFSList[i];
if (vfs.shouldHandle(normalized)) {
if (vfs.existsSync(normalized)) {
return fn(vfs, normalized);
}
throw createENOENT(syscall, filename);
}
const r = findVFS(filename);
if (r === null) return undefined;
if (r.vfs.existsSync(filename)) {
return fn(r.vfs, filename);
}
return undefined;
throw createENOENT(syscall, filename);
}
function vfsRead(path, syscall, fn) {
@@ -173,7 +313,7 @@ function vfsOp(path, fn) {
const pathStr = toPathStr(path);
if (pathStr !== null) {
const r = findVFSForPath(pathStr);
if (r !== null) return fn(r.vfs, r.normalized);
if (r !== null) return fn(r.vfs, r.path);
}
return undefined;
}
@@ -182,31 +322,21 @@ function vfsOpVoid(path, fn) {
const pathStr = toPathStr(path);
if (pathStr !== null) {
const r = findVFSForPath(pathStr);
if (r !== null) { fn(r.vfs, r.normalized); return true; }
if (r !== null) { fn(r.vfs, r.path); return true; }
}
return undefined;
}
function checkSameVFS(srcPath, destPath, syscall, srcVfs) {
const destNormalized = resolve(destPath);
for (let i = 0; i < activeVFSList.length; i++) {
const vfs = activeVFSList[i];
if (vfs.shouldHandle(destNormalized)) {
if (vfs !== srcVfs) {
throw createEXDEV(syscall, srcPath);
}
return;
}
if (findVFS(destPath)?.vfs !== srcVfs) {
throw createEXDEV(syscall, srcPath);
}
throw createEXDEV(syscall, srcPath);
}
function createVfsHandlers() {
return {
__proto__: null,
// ==================== Sync path-based read ops ====================
existsSync(path) {
const pathStr = toPathStr(path);
if (pathStr === null) return undefined;
@@ -241,27 +371,12 @@ function createVfsHandlers() {
lstatSync(path, options) {
const pathStr = toPathStr(path);
if (pathStr === null) return undefined;
const normalized = resolve(pathStr);
for (let i = 0; i < activeVFSList.length; i++) {
const vfs = activeVFSList[i];
if (vfs.shouldHandle(normalized)) {
try {
return vfs.lstatSync(normalized, options);
} catch (e) {
if (e?.code === 'ENOENT' && options?.throwIfNoEntry === false) return undefined;
throw e;
}
}
}
return undefined;
const r = findVFS(pathStr);
if (r === null) return undefined;
return r.vfs.lstatSync(pathStr, options);
},
statSync(path, options) {
try {
return vfsRead(path, 'stat', (vfs, n) => vfs.statSync(n, options));
} catch (err) {
if (err?.code === 'ENOENT' && options?.throwIfNoEntry === false) return undefined;
throw err;
}
return vfsRead(path, 'stat', (vfs, n) => vfs.statSync(n, options));
},
realpathSync(path, options) {
const result = vfsRead(path, 'realpath', (vfs, n) => vfs.realpathSync(n));
@@ -278,7 +393,7 @@ function createVfsHandlers() {
if (mode != null && typeof mode !== 'number') {
throw new ERR_INVALID_ARG_TYPE('mode', 'integer', mode);
}
r.vfs.accessSync(r.normalized, mode);
r.vfs.accessSync(r.path, mode);
return true;
}
}
@@ -287,16 +402,11 @@ function createVfsHandlers() {
readlinkSync(path, options) {
const pathStr = toPathStr(path);
if (pathStr === null) return undefined;
const normalized = resolve(pathStr);
for (let i = 0; i < activeVFSList.length; i++) {
const vfs = activeVFSList[i];
if (vfs.shouldHandle(normalized)) {
const result = vfs.readlinkSync(normalized, options);
if (options?.encoding === 'buffer') return Buffer.from(result);
return result;
}
}
return undefined;
const r = findVFS(pathStr);
if (r === null) return undefined;
const result = r.vfs.readlinkSync(pathStr, options);
if (options?.encoding === 'buffer') return Buffer.from(result);
return result;
},
statfsSync(path, options) {
const pathStr = toPathStr(path);
@@ -312,8 +422,6 @@ function createVfsHandlers() {
return undefined;
},
// ==================== Sync path-based write ops ====================
writeFileSync(path, data, options) {
if (typeof path === 'number') return writeFileSyncFd(path, data, options);
return vfsOpVoid(path, (vfs, n) => vfs.writeFileSync(n, data, options));
@@ -329,14 +437,16 @@ function createVfsHandlers() {
unlinkSync: (path) => vfsOpVoid(path, (vfs, n) => vfs.unlinkSync(n)),
renameSync(oldPath, newPath) {
return vfsOpVoid(oldPath, (vfs, n) => {
checkSameVFS(n, toPathStr(newPath), 'rename', vfs);
vfs.renameSync(n, resolve(toPathStr(newPath)));
const destStr = toPathStr(newPath);
checkSameVFS(n, destStr, 'rename', vfs);
vfs.renameSync(n, destStr);
});
},
copyFileSync(src, dest, mode) {
return vfsOpVoid(src, (vfs, n) => {
checkSameVFS(n, toPathStr(dest), 'copyfile', vfs);
vfs.copyFileSync(n, resolve(toPathStr(dest)), mode);
const destStr = toPathStr(dest);
checkSameVFS(n, destStr, 'copyfile', vfs);
vfs.copyFileSync(n, destStr, mode);
});
},
symlinkSync: (target, path, type) =>
@@ -351,8 +461,9 @@ function createVfsHandlers() {
truncateSync: (path, len) => vfsOpVoid(path, (vfs, n) => vfs.truncateSync(n, len)),
linkSync(existingPath, newPath) {
return vfsOpVoid(existingPath, (vfs, n) => {
checkSameVFS(n, toPathStr(newPath), 'link', vfs);
vfs.linkSync(n, resolve(toPathStr(newPath)));
const destStr = toPathStr(newPath);
checkSameVFS(n, destStr, 'link', vfs);
vfs.linkSync(n, destStr);
});
},
mkdtempSync(prefix, options) {
@@ -366,19 +477,14 @@ function createVfsHandlers() {
openAsBlob(path, options) {
const pathStr = toPathStr(path);
if (pathStr !== null) {
const normalized = resolve(pathStr);
for (let i = 0; i < activeVFSList.length; i++) {
const vfs = activeVFSList[i];
if (vfs.shouldHandle(normalized) && vfs.existsSync(normalized)) {
return vfs.openAsBlob(normalized, options);
}
const r = findVFS(pathStr);
if (r !== null && r.vfs.existsSync(pathStr)) {
return r.vfs.openAsBlob(pathStr, options);
}
}
return undefined;
},
// ==================== Sync FD-based ops ====================
openSync: (path, flags, mode) => vfsOp(path, (vfs, n) => vfs.openSync(n, flags, mode)),
closeSync(fd) {
const vfd = getVirtualFd(fd);
@@ -437,8 +543,6 @@ function createVfsHandlers() {
return totalWritten;
},
// ==================== Async FD-based ops ====================
close(fd) {
const vfd = getVirtualFd(fd);
if (!vfd) return undefined;
@@ -472,13 +576,11 @@ function createVfsHandlers() {
fdatasync: noopFd,
fsync: noopFd,
// ==================== Stream ops ====================
createReadStream(path, options) {
const pathStr = toPathStr(path);
if (pathStr !== null) {
const r = findVFSForPath(pathStr);
if (r !== null) return r.vfs.createReadStream(r.normalized, options);
if (r !== null) return r.vfs.createReadStream(r.path, options);
}
return undefined;
},
@@ -486,13 +588,11 @@ function createVfsHandlers() {
const pathStr = toPathStr(path);
if (pathStr !== null) {
const r = findVFSForPath(pathStr);
if (r !== null) return r.vfs.createWriteStream(r.normalized, options);
if (r !== null) return r.vfs.createWriteStream(r.path, options);
}
return undefined;
},
// ==================== Watch ops ====================
watch(filename, options, listener) {
if (typeof options === 'function') {
listener = options;
@@ -510,8 +610,6 @@ function createVfsHandlers() {
return undefined;
},
// ==================== Async path-based ops ====================
readdir(path, options) {
const promise = vfsOp(path, (vfs, n) => vfs.promises.readdir(n, options));
if (promise !== undefined && options?.encoding === 'buffer' && !options?.withFileTypes) {
@@ -527,14 +625,9 @@ function createVfsHandlers() {
lstat(path, options) {
const pathStr = toPathStr(path);
if (pathStr === null) return undefined;
const normalized = resolve(pathStr);
for (let i = 0; i < activeVFSList.length; i++) {
const vfs = activeVFSList[i];
if (vfs.shouldHandle(normalized)) {
return vfs.promises.lstat(normalized, options);
}
}
return undefined;
const r = findVFS(pathStr);
if (r === null) return undefined;
return r.vfs.promises.lstat(pathStr, options);
},
stat(path, options) {
const promise = vfsOp(path, (vfs, n) => vfs.promises.stat(n, options));
@@ -578,18 +671,13 @@ function createVfsHandlers() {
readlink(path, options) {
const pathStr = toPathStr(path);
if (pathStr === null) return undefined;
const normalized = resolve(pathStr);
for (let i = 0; i < activeVFSList.length; i++) {
const vfs = activeVFSList[i];
if (vfs.shouldHandle(normalized)) {
const promise = vfs.promises.readlink(normalized, options);
if (options?.encoding === 'buffer') {
return promise.then((result) => Buffer.from(result));
}
return promise;
}
const r = findVFS(pathStr);
if (r === null) return undefined;
const promise = r.vfs.promises.readlink(pathStr, options);
if (options?.encoding === 'buffer') {
return promise.then((result) => Buffer.from(result));
}
return undefined;
return promise;
},
chown: (path, uid, gid) =>
vfsOp(path, (vfs, n) => vfs.promises.chown(n, uid, gid).then(() => true)),
@@ -630,14 +718,16 @@ function createVfsHandlers() {
unlink: (path) => vfsOp(path, (vfs, n) => vfs.promises.unlink(n).then(() => true)),
rename(oldPath, newPath) {
return vfsOp(oldPath, (vfs, n) => {
checkSameVFS(n, toPathStr(newPath), 'rename', vfs);
return vfs.promises.rename(n, resolve(toPathStr(newPath))).then(() => true);
const destStr = toPathStr(newPath);
checkSameVFS(n, destStr, 'rename', vfs);
return vfs.promises.rename(n, destStr).then(() => true);
});
},
copyFile(src, dest, mode) {
return vfsOp(src, (vfs, n) => {
checkSameVFS(n, toPathStr(dest), 'copyfile', vfs);
return vfs.promises.copyFile(n, resolve(toPathStr(dest)), mode).then(() => true);
const destStr = toPathStr(dest);
checkSameVFS(n, destStr, 'copyfile', vfs);
return vfs.promises.copyFile(n, destStr, mode).then(() => true);
});
},
symlink(target, path, type) {
@@ -647,8 +737,9 @@ function createVfsHandlers() {
vfsOp(path, (vfs, n) => vfs.promises.truncate(n, len).then(() => true)),
link(existingPath, newPath) {
return vfsOp(existingPath, (vfs, n) => {
checkSameVFS(n, toPathStr(newPath), 'link', vfs);
return vfs.promises.link(n, resolve(toPathStr(newPath))).then(() => true);
const destStr = toPathStr(newPath);
checkSameVFS(n, destStr, 'link', vfs);
return vfs.promises.link(n, destStr).then(() => true);
});
},
mkdtemp(prefix, options) {
@@ -663,9 +754,8 @@ function createVfsHandlers() {
utimes: (path, atime, mtime) =>
vfsOp(path, (vfs, n) => vfs.promises.utimes(n, atime, mtime).then(() => true)),
open(path, flags, mode) {
// openSync is synchronous, so an error thrown by the provider would
// escape via fs.open's caller (instead of going through the callback).
// Catch it here and surface as a rejected promise.
// Wrap openSync in an async fn so provider throws become rejections
// instead of escaping past fs.open's callback.
return vfsOp(path, async (vfs, n) => vfs.openSync(n, flags, mode));
},
promisesOpen(path, flags, mode) {
@@ -673,7 +763,7 @@ function createVfsHandlers() {
if (pathStr !== null) {
const r = findVFSForPath(pathStr);
if (r !== null) {
const fd = r.vfs.openSync(r.normalized, flags, mode);
const fd = r.vfs.openSync(r.path, flags, mode);
const vfd = getVirtualFd(fd);
return PromiseResolve(vfd.entry);
}
@@ -685,6 +775,173 @@ function createVfsHandlers() {
};
}
/**
* Install toggleable loader overrides so that the module loader's
* internal fs operations (stat, readFile, realpath) are redirected
* to VFS when appropriate.
*/
function installModuleLoaderOverrides() {
const {
legacyMainResolveExtensions,
legacyMainResolveExtensionsIndexes,
kLoaderOverrideNoResult,
setLoaderOverrides,
} = require('internal/modules/helpers');
const { kResolvedByMainIndexNode } = legacyMainResolveExtensionsIndexes;
const { internal: internalConstants } = internalBinding('constants');
// Overrides return `undefined` for paths the VFS does not own;
// wrapLoaderMethod then falls through to the native binding.
setLoaderOverrides({
internalModuleStat(filename) {
const result = findVFSForStat(filename);
return result !== null ? result.result : undefined;
},
readFileSync(filename, options) {
const pathStr = typeof filename === 'string' ? filename :
(filename instanceof URL ? fileURLToPath(filename) : String(filename));
const result = findVFSForRead(pathStr, options);
return result !== null ? result.content : undefined;
},
realpathSync(filename) {
return findVFSWith(filename, 'realpath', (vfs, n) => vfs.realpathSync(n));
},
getResolutionRoot(pathStr) {
const r = findVFS(pathStr);
if (r === null) return undefined;
const mountPoint = r.vfs.mountPoint;
// The boundary is compared as a plain string prefix by the
// callers, so only report it when the input carries the mount
// point verbatim.
return StringPrototypeStartsWith(pathStr, mountPoint) ?
mountPoint : undefined;
},
legacyMainResolve(pkgPath, main, base) {
if (findVFS(pkgPath) === null) return undefined;
for (let i = 0; i < legacyMainResolveExtensions.length; i++) {
const byMain = i <= kResolvedByMainIndexNode;
if (byMain && !main) continue;
const prefix = byMain ? main : '';
const candidate = join(pkgPath, prefix + legacyMainResolveExtensions[i]);
if (findVFSForStat(candidate)?.result === 0) return i;
}
// Third arg `exactUrl` must be undefined (not a string) so the
// message uses the "package" word and err.url is not overwritten.
// ERR_MODULE_NOT_FOUND enforces strict arity in getMessage(), so
// the undefined has to be passed explicitly.
const initial = main ? join(pkgPath, main) : join(pkgPath, 'index.js');
throw new ERR_MODULE_NOT_FOUND(initial, base, undefined);
},
getFormatOfExtensionlessFile(filePath) {
let result;
try {
result = findVFSForRead(filePath, null);
} catch {
return internalConstants.EXTENSIONLESS_FORMAT_JAVASCRIPT;
}
if (result === null) return undefined;
const content = result.content;
// Wasm magic bytes: 0x00 0x61 0x73 0x6d
if (content && content.length >= 4 &&
content[0] === 0x00 && content[1] === 0x61 &&
content[2] === 0x73 && content[3] === 0x6d) {
return internalConstants.EXTENSIONLESS_FORMAT_WASM;
}
return internalConstants.EXTENSIONLESS_FORMAT_JAVASCRIPT;
},
readPackageJSON(jsonPath, isESM, base, specifier) {
const r = findVFS(jsonPath);
if (r === null) return undefined;
const { vfs } = r;
if (vfsStat(vfs, jsonPath) !== 0) return kLoaderOverrideNoResult;
let content;
try {
content = vfs.readFileSync(jsonPath);
} catch {
return kLoaderOverrideNoResult;
}
// Both CJS and ESM raise ERR_INVALID_PACKAGE_CONFIG since
// nodejs/node#48606.
return nativeModulesBinding.parsePackageJSON(
content, jsonPath, isESM, base, specifier);
},
getNearestParentPackageJSON(checkPath) {
const r = findVFS(checkPath);
if (r === null) return undefined;
const found = findVFSPackageJSON(r.vfs, checkPath, r.normalized);
return found.tuple ?? kLoaderOverrideNoResult;
},
getPackageScopeConfig(resolved) {
let filePath;
if (StringPrototypeStartsWith(resolved, 'file:')) {
try {
filePath = fileURLToPath(resolved);
} catch {
return undefined;
}
} else {
filePath = resolved;
}
const r = findVFS(filePath);
if (r === null) return undefined;
const found = findVFSPackageJSON(r.vfs, filePath, r.normalized);
if (found.tuple !== undefined) return found.tuple;
return found.sentinel;
},
getPackageType(url) {
let filePath;
if (StringPrototypeStartsWith(url, 'file:')) {
try {
filePath = fileURLToPath(url);
} catch {
return undefined;
}
} else {
filePath = url;
}
const r = findVFS(filePath);
if (r === null) return undefined;
const found = findVFSPackageJSON(r.vfs, filePath, r.normalized);
if (found.tuple !== undefined) {
// Tuple shape: [name, main, type, imports, exports, filePath].
const type = found.tuple[2];
if (type === 'module' || type === 'commonjs') return type;
}
return kLoaderOverrideNoResult;
},
});
}
/**
* Install all VFS hooks: module loader overrides and fs handlers.
*/
function installHooks() {
if (hooksInstalled) return;
debug('install hooks');
normalizedVfsRootPrefix = getNormalizedVfsRoot() + sep;
installModuleLoaderOverrides();
vfsHandlerObj = createVfsHandlers();
setVfsHandlers(vfsHandlerObj);
hooksInstalled = true;
}
/**
* Tear down all VFS hooks when the last instance is deregistered. The
* fast path in the loader wrappers is restored so subsequent require/
* import calls pay zero overhead until another VFS is mounted.
*/
function uninstallHooks() {
if (!hooksInstalled) return;
debug('uninstall hooks');
const { setLoaderOverrides } = require('internal/modules/helpers');
setLoaderOverrides();
setVfsHandlers(null);
vfsHandlerObj = undefined;
hooksInstalled = false;
}
module.exports = {
registerVFS,
deregisterVFS,
+182 -124
View File
@@ -91,6 +91,142 @@ Local<Array> BindingData::PackageConfig::Serialize(Realm* realm) const {
return Array::New(isolate, values, 6);
}
bool BindingData::ParsePackageJSON(Realm* realm,
PackageConfig* package_config,
ErrorContext* error_context) {
auto binding_data = realm->GetBindingData<BindingData>();
const std::string_view path = package_config->file_path;
simdjson::ondemand::document document;
simdjson::ondemand::object main_object;
simdjson::error_code error =
binding_data->json_parser.iterate(simdjson::pad(package_config->raw_json))
.get(document);
const auto throw_invalid_package_config = [error_context, path, realm]() {
if (error_context == nullptr) {
THROW_ERR_INVALID_PACKAGE_CONFIG(
realm->isolate(), "Invalid package config %s.", path.data());
} else if (error_context->base.has_value()) {
auto file_url = ada::parse(error_context->base.value());
CHECK(file_url);
auto file_path = url::FileURLToPath(realm->env(), *file_url);
CHECK(file_path.has_value());
THROW_ERR_INVALID_PACKAGE_CONFIG(
realm->isolate(),
"Invalid package config %s while importing \"%s\" from %s.",
path.data(),
error_context->specifier.c_str(),
file_path->c_str());
} else {
THROW_ERR_INVALID_PACKAGE_CONFIG(
realm->isolate(), "Invalid package config %s.", path.data());
}
return false;
};
if (error || document.get_object().get(main_object)) {
return throw_invalid_package_config();
}
simdjson::ondemand::raw_json_string key;
simdjson::ondemand::value value;
std::string_view field_value;
simdjson::ondemand::json_type field_type;
for (auto field : main_object) {
// Throw error if getting key or value fails.
if (field.key().get(key) || field.value().get(value)) {
return throw_invalid_package_config();
}
// based on coverity using key with == derefs the raw value
// avoid derefing if its null
if (key.raw() == nullptr) continue;
if (key == "name") {
// Though there is a key "name" with a corresponding value,
// the value may not be a string or could be an invalid JSON string
if (value.get_string(package_config->name)) {
return throw_invalid_package_config();
}
} else if (key == "main") {
// Omit all non-string values
USE(value.get_string(package_config->main));
} else if (key == "exports") {
if (value.type().get(field_type)) {
return throw_invalid_package_config();
}
switch (field_type) {
case simdjson::ondemand::json_type::object:
case simdjson::ondemand::json_type::array: {
if (value.raw_json().get(field_value)) {
return throw_invalid_package_config();
}
package_config->exports = field_value;
break;
}
case simdjson::ondemand::json_type::string: {
if (value.get_string(package_config->exports)) {
return throw_invalid_package_config();
}
break;
}
default:
break;
}
} else if (key == "imports") {
if (value.type().get(field_type)) {
return throw_invalid_package_config();
}
switch (field_type) {
case simdjson::ondemand::json_type::array:
case simdjson::ondemand::json_type::object: {
if (value.raw_json().get(field_value)) {
return throw_invalid_package_config();
}
package_config->imports = field_value;
break;
}
case simdjson::ondemand::json_type::string: {
if (value.get_string(package_config->imports)) {
return throw_invalid_package_config();
}
break;
}
default:
break;
}
} else if (key == "type") {
if (value.get_string().get(field_value)) {
return throw_invalid_package_config();
}
// Only update type if it is "commonjs" or "module"
// The default value is "none" for backward compatibility.
if (field_value == "commonjs" || field_value == "module") {
package_config->type = field_value;
}
} else if (key == "scripts") {
if (value.type().get(field_type)) {
return throw_invalid_package_config();
}
switch (field_type) {
case simdjson::ondemand::json_type::object: {
if (value.raw_json().get(field_value)) {
return throw_invalid_package_config();
}
package_config->scripts = field_value;
break;
}
default:
break;
}
}
}
return true;
}
const BindingData::PackageConfig* BindingData::GetPackageJSON(
Realm* realm, std::string_view path, ErrorContext* error_context) {
auto binding_data = realm->GetBindingData<BindingData>();
@@ -134,133 +270,10 @@ const BindingData::PackageConfig* BindingData::GetPackageJSON(
return nullptr;
}
simdjson::ondemand::document document;
simdjson::ondemand::object main_object;
simdjson::error_code error =
binding_data->json_parser.iterate(simdjson::pad(package_config.raw_json))
.get(document);
const auto throw_invalid_package_config = [error_context, path, realm]() {
if (error_context == nullptr) {
THROW_ERR_INVALID_PACKAGE_CONFIG(
realm->isolate(), "Invalid package config %s.", path.data());
} else if (error_context->base.has_value()) {
auto file_url = ada::parse(error_context->base.value());
CHECK(file_url);
auto file_path = url::FileURLToPath(realm->env(), *file_url);
CHECK(file_path.has_value());
THROW_ERR_INVALID_PACKAGE_CONFIG(
realm->isolate(),
"Invalid package config %s while importing \"%s\" from %s.",
path.data(),
error_context->specifier.c_str(),
file_path->c_str());
} else {
THROW_ERR_INVALID_PACKAGE_CONFIG(
realm->isolate(), "Invalid package config %s.", path.data());
}
if (!ParsePackageJSON(realm, &package_config, error_context)) {
return nullptr;
};
if (error || document.get_object().get(main_object)) {
return throw_invalid_package_config();
}
simdjson::ondemand::raw_json_string key;
simdjson::ondemand::value value;
std::string_view field_value;
simdjson::ondemand::json_type field_type;
for (auto field : main_object) {
// Throw error if getting key or value fails.
if (field.key().get(key) || field.value().get(value)) {
return throw_invalid_package_config();
}
// based on coverity using key with == derefs the raw value
// avoid derefing if its null
if (key.raw() == nullptr) continue;
if (key == "name") {
// Though there is a key "name" with a corresponding value,
// the value may not be a string or could be an invalid JSON string
if (value.get_string(package_config.name)) {
return throw_invalid_package_config();
}
} else if (key == "main") {
// Omit all non-string values
USE(value.get_string(package_config.main));
} else if (key == "exports") {
if (value.type().get(field_type)) {
return throw_invalid_package_config();
}
switch (field_type) {
case simdjson::ondemand::json_type::object:
case simdjson::ondemand::json_type::array: {
if (value.raw_json().get(field_value)) {
return throw_invalid_package_config();
}
package_config.exports = field_value;
break;
}
case simdjson::ondemand::json_type::string: {
if (value.get_string(package_config.exports)) {
return throw_invalid_package_config();
}
break;
}
default:
break;
}
} else if (key == "imports") {
if (value.type().get(field_type)) {
return throw_invalid_package_config();
}
switch (field_type) {
case simdjson::ondemand::json_type::array:
case simdjson::ondemand::json_type::object: {
if (value.raw_json().get(field_value)) {
return throw_invalid_package_config();
}
package_config.imports = field_value;
break;
}
case simdjson::ondemand::json_type::string: {
if (value.get_string(package_config.imports)) {
return throw_invalid_package_config();
}
break;
}
default:
break;
}
} else if (key == "type") {
if (value.get_string().get(field_value)) {
return throw_invalid_package_config();
}
// Only update type if it is "commonjs" or "module"
// The default value is "none" for backward compatibility.
if (field_value == "commonjs" || field_value == "module") {
package_config.type = field_value;
}
} else if (key == "scripts") {
if (value.type().get(field_type)) {
return throw_invalid_package_config();
}
switch (field_type) {
case simdjson::ondemand::json_type::object: {
if (value.raw_json().get(field_value)) {
return throw_invalid_package_config();
}
package_config.scripts = field_value;
break;
}
default:
break;
}
}
}
// package_config could be quite large, so we should move it instead of
// copying it.
auto cached = binding_data->package_configs_.insert(
@@ -307,6 +320,49 @@ void BindingData::ReadPackageJSON(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(package_json->Serialize(realm));
}
void BindingData::ParsePackageJSONBinding(
const FunctionCallbackInfo<Value>& args) {
// parsePackageJSON(source, jsonPath, isESM, base, specifier)
CHECK_GE(args.Length(), 2);
CHECK(args[0]->IsString() || args[0]->IsArrayBufferView()); // source
CHECK(args[1]->IsString()); // jsonPath
Realm* realm = Realm::GetCurrent(args);
auto isolate = realm->isolate();
BufferValue json_path(isolate, args[1]);
bool is_esm = args.Length() >= 3 && args[2]->IsTrue();
auto error_context = ErrorContext();
if (is_esm) {
CHECK(args[3]->IsUndefined() || args[3]->IsString()); // base
CHECK(args[4]->IsString()); // specifier
if (args[3]->IsString()) {
Utf8Value base_value(isolate, args[3]);
error_context.base = base_value.ToString();
}
Utf8Value specifier(isolate, args[4]);
error_context.specifier = specifier.ToString();
}
PackageConfig package_config{};
package_config.file_path = json_path.ToStringView();
if (args[0]->IsString()) {
Utf8Value source(isolate, args[0]);
package_config.raw_json = source.ToString();
} else {
ArrayBufferViewContents<char> view(args[0]);
package_config.raw_json = std::string(view.data(), view.length());
}
if (!ParsePackageJSON(
realm, &package_config, is_esm ? &error_context : nullptr)) {
return; // ParsePackageJSON already threw
}
args.GetReturnValue().Set(package_config.Serialize(realm));
}
const BindingData::PackageConfig* BindingData::TraverseParent(
Realm* realm, const std::filesystem::path& check_path) {
std::filesystem::path current_path = check_path;
@@ -631,6 +687,7 @@ void BindingData::CreatePerIsolateProperties(IsolateData* isolate_data,
Local<ObjectTemplate> target) {
Isolate* isolate = isolate_data->isolate();
SetMethod(isolate, target, "readPackageJSON", ReadPackageJSON);
SetMethod(isolate, target, "parsePackageJSON", ParsePackageJSONBinding);
SetMethod(isolate,
target,
"getNearestParentPackageJSONType",
@@ -709,6 +766,7 @@ void BindingData::CreatePerContextProperties(Local<Object> target,
void BindingData::RegisterExternalReferences(
ExternalReferenceRegistry* registry) {
registry->Register(ReadPackageJSON);
registry->Register(ParsePackageJSONBinding);
registry->Register(GetNearestParentPackageJSONType);
registry->Register(GetNearestParentPackageJSON);
registry->Register(GetPackageScopeConfig<false>);
+11
View File
@@ -55,6 +55,11 @@ class BindingData : public SnapshotableObject {
SET_MEMORY_INFO_NAME(BindingData)
static void ReadPackageJSON(const v8::FunctionCallbackInfo<v8::Value>& args);
// Like ReadPackageJSON but the caller supplies the raw JSON body.
// Does not populate the C++ `package_configs_` cache.
// Signature: parsePackageJSON(source, jsonPath, isESM, base, specifier)
static void ParsePackageJSONBinding(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetNearestParentPackageJSON(
const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetNearestParentPackageJSONType(
@@ -90,6 +95,12 @@ class BindingData : public SnapshotableObject {
Realm* realm,
std::string_view path,
ErrorContext* error_context = nullptr);
// Parses `package_config->raw_json` into `package_config`; caller
// must set raw_json and file_path first. Returns false and throws
// ERR_INVALID_PACKAGE_CONFIG on a syntactic error.
static bool ParsePackageJSON(Realm* realm,
PackageConfig* package_config,
ErrorContext* error_context);
static const PackageConfig* TraverseParent(
Realm* realm, const std::filesystem::path& check_path);
};
+7
View File
@@ -0,0 +1,7 @@
'use strict';
require('../common');
const runBenchmark = require('../common/benchmark');
runBenchmark('vfs');
+3 -7
View File
@@ -18,17 +18,13 @@ const {
realpathSync,
} = require('fs');
// path.resolve here so the mount point and the assertion targets are in the
// platform's native form (e.g. 'D:\vfs_destr' on Windows). VirtualFileSystem
// stores the mount point via path.resolve internally, so we mirror that.
const MOUNT = path.resolve('/vfs_destr');
const FILE = path.join(MOUNT, 'file.txt');
const myVfs = vfs.create();
myVfs.mkdirSync('/sub', { recursive: true });
myVfs.writeFileSync('/file.txt', 'hello from vfs');
myVfs.writeFileSync('/sub/nested.txt', 'nested content');
myVfs.mount(MOUNT);
const MOUNT = myVfs.mount();
const FILE = path.join(MOUNT, 'file.txt');
{
const content = readFileSync(FILE, 'utf8');
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-accessSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
// Existing path succeeds
fs.accessSync(path.join(mountPoint, 'src/hello.txt'));
@@ -9,14 +9,11 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-cb-err-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-chmod-cb-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
const target = path.join(mountPoint, 'src/hello.txt');
const uid = process.getuid?.() ?? 0;
+1 -2
View File
@@ -10,11 +10,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-chmodSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
const target = path.join(mountPoint, 'src/hello.txt');
const uid = process.getuid?.() ?? 0;
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-copyFileSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
fs.copyFileSync(
path.join(mountPoint, 'src/hello.txt'),
@@ -10,14 +10,11 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-createReadStream-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
@@ -10,15 +10,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve(
'/tmp/vfs-createWriteStream-' + process.pid,
);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-existsSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
assert.strictEqual(fs.existsSync(path.join(mountPoint, 'src/hello.txt')), true);
assert.strictEqual(fs.existsSync(path.join(mountPoint, 'src')), true);
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-fchmod-cb-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
const fd = fs.openSync(path.join(mountPoint, 'src/hello.txt'), 'r+');
const uid = process.getuid?.() ?? 0;
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-linkSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
fs.linkSync(
path.join(mountPoint, 'src/hello.txt'),
+1 -4
View File
@@ -9,14 +9,11 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-mkdir-cb-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
+1 -2
View File
@@ -9,10 +9,9 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-mkdirSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
// Plain mkdir
fs.mkdirSync(path.join(mountPoint, 'src/d1'));
+1 -2
View File
@@ -10,10 +10,9 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-mkdtempSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
const prefix = path.join(mountPoint, 'src/tmp-');
+1 -4
View File
@@ -10,14 +10,11 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-open-cb-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-openAsBlob-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
fs.openAsBlob(path.join(mountPoint, 'src/hello.txt'))
.then(async (blob) => {
+1 -2
View File
@@ -12,11 +12,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-openSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
// openSync + fstatSync + readSync + closeSync
{
@@ -10,15 +10,12 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-opendir-cb-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.writeFileSync('/src/data.json', '{}');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
+1 -2
View File
@@ -9,12 +9,11 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-opendirSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src/subdir', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.writeFileSync('/src/data.json', '{}');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
const dir = fs.opendirSync(path.join(mountPoint, 'src'));
const names = [];
@@ -10,14 +10,11 @@ const fsp = require('fs/promises');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-buf-enc-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
@@ -11,11 +11,10 @@ const path = require('path');
const vfs = require('node:vfs');
(async () => {
const mountPoint = path.resolve('/tmp/vfs-stat-no-throw-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
// Missing file -> undefined
const missing = await fsp.stat(path.join(mountPoint, 'src/nope'),
+1 -2
View File
@@ -12,11 +12,10 @@ const path = require('path');
const vfs = require('node:vfs');
(async () => {
const mountPoint = path.resolve('/tmp/vfs-promises-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
const p = (s) => path.join(mountPoint, s);
// Path-based reads
@@ -10,14 +10,11 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-readFile-cb-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
+4 -9
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-readFileSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
// Default (buffer) result
{
@@ -48,15 +47,12 @@ myVfs.unmount();
// is renamed.
{
const root = path.join('/tmp', 'vfs-real-readFileSync-' + process.pid);
const realMountPoint = path.join('/tmp', 'vfs-real-readFileSync-mount-' + process.pid);
fs.rmSync(root, { recursive: true, force: true });
fs.rmSync(realMountPoint, { recursive: true, force: true });
fs.mkdirSync(root, { recursive: true });
fs.mkdirSync(realMountPoint, { recursive: true });
const realVfs = vfs
.create(new vfs.RealFSProvider(root), { emitExperimentalWarning: false })
.mount(realMountPoint);
const realVfs = vfs.create(new vfs.RealFSProvider(root),
{ emitExperimentalWarning: false });
const realMountPoint = realVfs.mount();
try {
fs.writeFileSync(path.join(root, 'a.txt'), 'still readable');
const fd = fs.openSync(path.join(realMountPoint, 'a.txt'), 'r');
@@ -69,6 +65,5 @@ myVfs.unmount();
} finally {
realVfs.unmount();
fs.rmSync(root, { recursive: true, force: true });
fs.rmSync(realMountPoint, { recursive: true, force: true });
}
}
+1 -2
View File
@@ -10,12 +10,11 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-readdirSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src/subdir', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.writeFileSync('/src/data.json', '{}');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
// Default (utf8 string array)
{
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-realpathSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
const p = path.join(mountPoint, 'src/hello.txt');
+1 -4
View File
@@ -9,14 +9,11 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-rename-cb-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-renameSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
fs.renameSync(
path.join(mountPoint, 'src/hello.txt'),
+1 -2
View File
@@ -9,13 +9,12 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-rmSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src/subdir', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.writeFileSync('/src/subdir/inside.txt', 'inside');
myVfs.mkdirSync('/empty');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
// rmdirSync on an empty directory
fs.rmdirSync(path.join(mountPoint, 'empty'));
+1 -4
View File
@@ -9,14 +9,11 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-stat-cb-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
+1 -2
View File
@@ -10,11 +10,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-statSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
// statSync on a regular file
{
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-symlink-cb-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
fs.symlink('hello.txt', path.join(mountPoint, 'src/lnk.txt'),
common.mustSucceed(() => {
+1 -2
View File
@@ -10,11 +10,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-symlinkSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
fs.symlinkSync('hello.txt', path.join(mountPoint, 'src/link.txt'));
assert.strictEqual(
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-truncate-cb-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
fs.truncate(path.join(mountPoint, 'src/hello.txt'), 5,
common.mustSucceed(() => {
+1 -2
View File
@@ -9,11 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-truncateSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
fs.truncateSync(path.join(mountPoint, 'src/hello.txt'), 5);
assert.strictEqual(
+1 -2
View File
@@ -10,11 +10,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-watch-dispatch-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
const watcher = fs.watch(path.join(mountPoint, 'src/hello.txt'));
assert.ok(watcher);
@@ -9,13 +9,10 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseMountPoint = path.resolve('/tmp/vfs-writeFile-cb-' + process.pid);
let counter = 0;
function mounted() {
const mountPoint = baseMountPoint + '-' + (counter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
+4 -9
View File
@@ -9,10 +9,9 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-writeFileSync-' + process.pid);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
const target = path.join(mountPoint, 'src/new.txt');
@@ -58,15 +57,12 @@ myVfs.unmount();
// after the backing path is renamed.
{
const root = path.join('/tmp', 'vfs-real-writeFileSync-' + process.pid);
const realMountPoint = path.join('/tmp', 'vfs-real-writeFileSync-mount-' + process.pid);
fs.rmSync(root, { recursive: true, force: true });
fs.rmSync(realMountPoint, { recursive: true, force: true });
fs.mkdirSync(root, { recursive: true });
fs.mkdirSync(realMountPoint, { recursive: true });
const realVfs = vfs
.create(new vfs.RealFSProvider(root), { emitExperimentalWarning: false })
.mount(realMountPoint);
const realVfs = vfs.create(
new vfs.RealFSProvider(root), { emitExperimentalWarning: false });
const realMountPoint = realVfs.mount();
try {
const mountedFile = path.join(realMountPoint, 'a.txt');
fs.writeFileSync(path.join(root, 'a.txt'), 'old');
@@ -83,6 +79,5 @@ myVfs.unmount();
} finally {
realVfs.unmount();
fs.rmSync(root, { recursive: true, force: true });
fs.rmSync(realMountPoint, { recursive: true, force: true });
}
}
+139
View File
@@ -0,0 +1,139 @@
// Flags: --experimental-vfs
import '../common/index.mjs';
import assert from 'assert';
import { pathToFileURL } from 'node:url';
import vfs from 'node:vfs';
const vfsImport = (path) => pathToFileURL(path).href;
// ESM imports are cached by URL and unmounting does not clear the V8 module
// cache; each vfs.create() gets its own layer id so mount points are unique.
// Test importing a simple virtual ES module
{
const myVfs = vfs.create();
myVfs.writeFileSync('/hello.mjs', 'export const message = "hello from vfs";');
const mountPoint = myVfs.mount();
const { message } = await import(vfsImport(`${mountPoint}/hello.mjs`));
assert.strictEqual(message, 'hello from vfs');
myVfs.unmount();
}
// Test importing a virtual module with default export
{
const myVfs = vfs.create();
myVfs.writeFileSync('/default.mjs', 'export default { name: "test", value: 42 };');
const mountPoint = myVfs.mount();
const mod = await import(vfsImport(`${mountPoint}/default.mjs`));
assert.strictEqual(mod.default.name, 'test');
assert.strictEqual(mod.default.value, 42);
myVfs.unmount();
}
// Test importing a virtual module that imports another virtual module.
// Mount first so the embedded absolute specifier can use the mount point.
{
const myVfs = vfs.create();
const mountPoint = myVfs.mount();
myVfs.writeFileSync(`${mountPoint}/utils.mjs`,
'export function add(a, b) { return a + b; }');
myVfs.writeFileSync(`${mountPoint}/main.mjs`, `
import { add } from ${JSON.stringify(vfsImport(`${mountPoint}/utils.mjs`))};
export const result = add(10, 20);
`);
const { result } = await import(vfsImport(`${mountPoint}/main.mjs`));
assert.strictEqual(result, 30);
myVfs.unmount();
}
// Test importing with relative paths
{
const myVfs = vfs.create();
myVfs.mkdirSync('/lib', { recursive: true });
myVfs.writeFileSync('/lib/helper.mjs', 'export const helper = () => "helped";');
myVfs.writeFileSync('/lib/index.mjs', `
import { helper } from './helper.mjs';
export const output = helper();
`);
const mountPoint = myVfs.mount();
const { output } = await import(vfsImport(`${mountPoint}/lib/index.mjs`));
assert.strictEqual(output, 'helped');
myVfs.unmount();
}
// Test importing JSON from VFS (with import assertion)
{
const myVfs = vfs.create();
myVfs.writeFileSync('/data.json', JSON.stringify({ items: [1, 2, 3], enabled: true }));
const mountPoint = myVfs.mount();
const data = await import(vfsImport(`${mountPoint}/data.json`), { with: { type: 'json' } });
assert.deepStrictEqual(data.default.items, [1, 2, 3]);
assert.strictEqual(data.default.enabled, true);
myVfs.unmount();
}
// Test that real modules still work when VFS is mounted
{
const myVfs = vfs.create();
myVfs.writeFileSync('/test.mjs', 'export const x = 1;');
myVfs.mount();
const assertMod = await import('node:assert');
assert.strictEqual(typeof assertMod.strictEqual, 'function');
myVfs.unmount();
}
// Test mixed CJS and ESM - ESM importing from VFS while CJS also works
{
const myVfs = vfs.create();
myVfs.writeFileSync('/esm-module.mjs', 'export const esmValue = "esm";');
myVfs.writeFileSync('/cjs-module.js', 'module.exports = { cjsValue: "cjs" };');
const mountPoint = myVfs.mount();
const { esmValue } = await import(vfsImport(`${mountPoint}/esm-module.mjs`));
assert.strictEqual(esmValue, 'esm');
const { createRequire } = await import('module');
const require = createRequire(import.meta.url);
const { cjsValue } = require(`${mountPoint}/cjs-module.js`);
assert.strictEqual(cjsValue, 'cjs');
myVfs.unmount();
}
// Test ESM bare specifier resolution from VFS node_modules.
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/my-vfs-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/my-vfs-pkg/package.json', JSON.stringify({
name: 'my-vfs-pkg',
type: 'module',
exports: { '.': './index.mjs' },
}));
myVfs.writeFileSync(
'/app/node_modules/my-vfs-pkg/index.mjs',
'export const fromVfs = true;',
);
// Importing module must live in the VFS mount so node_modules walk stays inside VFS.
myVfs.writeFileSync(
'/app/entry.mjs',
"export { fromVfs } from 'my-vfs-pkg';",
);
const mountPoint = myVfs.mount();
const { fromVfs } = await import(vfsImport(`${mountPoint}/app/entry.mjs`));
assert.strictEqual(fromVfs, true);
myVfs.unmount();
}
@@ -0,0 +1,76 @@
// Flags: --experimental-vfs --expose-internals
'use strict';
const common = require('../common');
const assert = require('assert');
const vfs = require('node:vfs');
// Malformed package.json in VFS throws ERR_INVALID_PACKAGE_CONFIG
// (matches native CJS behavior after nodejs/node#48606).
{
const myVfs = vfs.create();
myVfs.mkdirSync('/pkg', { recursive: true });
myVfs.writeFileSync('/pkg/package.json', '{ invalid json');
myVfs.writeFileSync('/pkg/index.js', 'module.exports = 42;');
const mountPoint = myVfs.mount();
assert.throws(() => require(`${mountPoint}/pkg`),
{ code: 'ERR_INVALID_PACKAGE_CONFIG' });
myVfs.unmount();
}
// Valid package.json still works
{
const myVfs = vfs.create();
myVfs.mkdirSync('/pkg2', { recursive: true });
myVfs.writeFileSync('/pkg2/package.json', '{"main": "lib.js"}');
myVfs.writeFileSync('/pkg2/lib.js', 'module.exports = 99;');
const mountPoint = myVfs.mount();
assert.strictEqual(require(`${mountPoint}/pkg2`), 99);
myVfs.unmount();
}
// Missing package.json (ENOENT) still falls through to index.js
{
const myVfs = vfs.create();
myVfs.mkdirSync('/pkg3', { recursive: true });
myVfs.writeFileSync('/pkg3/index.js', 'module.exports = 77;');
const mountPoint = myVfs.mount();
assert.strictEqual(require(`${mountPoint}/pkg3`), 77);
myVfs.unmount();
}
// A malformed ancestor package.json aborts the scope walk with
// ERR_INVALID_PACKAGE_CONFIG for both CJS and ESM.
{
const myVfs = vfs.create();
myVfs.mkdirSync('/outer/inner', { recursive: true });
myVfs.writeFileSync('/outer/package.json', '{ bad }');
myVfs.writeFileSync('/outer/inner/mod.js', 'module.exports = 1;');
const mountPoint = myVfs.mount();
assert.throws(() => require(`${mountPoint}/outer/inner/mod.js`),
{ code: 'ERR_INVALID_PACKAGE_CONFIG' });
myVfs.unmount();
}
(async () => {
const myVfs = vfs.create();
myVfs.mkdirSync('/outer2/inner', { recursive: true });
myVfs.writeFileSync('/outer2/package.json', '{ bad }');
myVfs.writeFileSync('/outer2/inner/mod.js', 'export const x = 1;');
myVfs.mount();
await assert.rejects(
() => import(`${myVfs.mountPointURL}/outer2/inner/mod.js`),
{ code: 'ERR_INVALID_PACKAGE_CONFIG' },
);
myVfs.unmount();
})().then(common.mustCall());
@@ -0,0 +1,45 @@
// Flags: --experimental-vfs
// Regression: unmounting a layer whose id is a decimal prefix of another
// (e.g. layer 1 vs layer 10) must not purge the other's ESM cache entries.
// Mount points look like `${os.devNull}/vfs/<id>`, so we create instances
// until the returned mount points exhibit the prefix collision, then
// verify the survivor's cache lives on.
import '../common/index.mjs';
import assert from 'node:assert';
import { pathToFileURL } from 'node:url';
import vfs from 'node:vfs';
const vfsImport = (path) => pathToFileURL(path).href;
// Layer ids are per-process and increment on every `vfs.create()`, so the
// second construction lands at id 1 and the eleventh at id 10.
const instances = [];
for (let i = 0; i < 11; i++) instances.push(vfs.create());
const layerOne = instances[1];
const layerTen = instances[10];
layerOne.writeFileSync('/m.mjs', 'export const tag = "one";');
const mountOne = layerOne.mount();
layerTen.writeFileSync('/m.mjs', 'export const tag = "ten";');
const mountTen = layerTen.mount();
assert.notStrictEqual(mountOne, mountTen);
assert.ok(mountTen.startsWith(mountOne),
'test scaffolding: expected layerTen mount to start with layerOne mount');
const oneA = await import(vfsImport(`${mountOne}/m.mjs`));
const tenA = await import(vfsImport(`${mountTen}/m.mjs`));
assert.strictEqual(oneA.tag, 'one');
assert.strictEqual(tenA.tag, 'ten');
layerOne.unmount();
// Layer 10 still mounted: re-import must hit the cache and return the same
// namespace object. A prefix-based purge would evict it and cause re-eval.
const tenB = await import(vfsImport(`${mountTen}/m.mjs`));
assert.strictEqual(tenA, tenB);
layerTen.unmount();
+1 -2
View File
@@ -8,7 +8,6 @@ const fsp = require('fs/promises');
const path = require('path');
const vfs = require('node:vfs');
const mountPoint = path.resolve('/tmp/vfs-lchown-' + process.pid);
const myVfs = vfs.create();
myVfs.writeFileSync('/sync-target.txt', 'target');
myVfs.symlinkSync('/sync-target.txt', '/sync-link.txt');
@@ -16,7 +15,7 @@ myVfs.writeFileSync('/async-target.txt', 'target');
myVfs.symlinkSync('/async-target.txt', '/async-link.txt');
myVfs.writeFileSync('/promise-target.txt', 'target');
myVfs.symlinkSync('/promise-target.txt', '/promise-link.txt');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
function assertOwnership(filePath, uid, gid) {
const stats = fs.lstatSync(path.join(mountPoint, filePath));
@@ -0,0 +1,123 @@
// Flags: --experimental-vfs
'use strict';
const common = require('../common');
const assert = require('assert');
const { pathToFileURL } = require('node:url');
const vfs = require('node:vfs');
const vfsImport = (path) => pathToFileURL(path).href;
// After a full deregister, a fresh register re-installs hooks cleanly.
{
const a = vfs.create();
a.writeFileSync('/m1.js', 'module.exports = "first"');
const mountA = a.mount();
assert.strictEqual(require(`${mountA}/m1.js`), 'first');
a.unmount();
const b = vfs.create();
b.writeFileSync('/m2.js', 'module.exports = "second"');
const mountB = b.mount();
assert.strictEqual(require(`${mountB}/m2.js`), 'second');
b.unmount();
}
// After the last VFS is removed, real-fs require still works.
{
const v = vfs.create();
v.writeFileSync('/x.js', 'module.exports = 1');
const mountPoint = v.mount();
require(`${mountPoint}/x.js`);
v.unmount();
const fs = require('fs');
assert.strictEqual(typeof fs.readFileSync, 'function');
}
// Top-level non-object package.json is rejected with ERR_INVALID_PACKAGE_CONFIG
// (matches the native binding's throw_invalid_package_config path).
{
const v = vfs.create();
v.mkdirSync('/pkg');
v.writeFileSync('/pkg/package.json', 'null');
v.writeFileSync('/pkg/index.js', 'module.exports = 1');
const mountPoint = v.mount();
assert.throws(
() => require(`${mountPoint}/pkg`),
{ code: 'ERR_INVALID_PACKAGE_CONFIG' },
);
v.unmount();
}
// Non-string `main` is silently omitted, matching the native binding
// (`USE(value.get_string(...))` in src/node_modules.cc).
{
const v = vfs.create();
v.mkdirSync('/pkg');
v.writeFileSync('/pkg/package.json', '{"main": 42}');
v.writeFileSync('/pkg/index.js', 'module.exports = "via-index"');
const mountPoint = v.mount();
assert.strictEqual(require(`${mountPoint}/pkg`), 'via-index');
v.unmount();
}
// Partial deregister of a multi-mount setup leaves the still-mounted
// VFS fully functional.
{
const a = vfs.create();
a.writeFileSync('/a.js', 'module.exports = "a"');
const mountA = a.mount();
const b = vfs.create();
b.writeFileSync('/b.js', 'module.exports = "b"');
const mountB = b.mount();
assert.strictEqual(require(`${mountA}/a.js`), 'a');
assert.strictEqual(require(`${mountB}/b.js`), 'b');
a.unmount();
assert.strictEqual(require(`${mountB}/b.js`), 'b');
b.unmount();
}
// ESM legacyMainResolve override produces ERR_MODULE_NOT_FOUND with the
// resolved candidate path when `main` points at a missing file, and err.url
// is undefined (regression: previously 'package' leaked into err.url).
(async () => {
const v = vfs.create();
v.mkdirSync('/app/node_modules/badpkg', { recursive: true });
v.writeFileSync(
'/app/node_modules/badpkg/package.json', '{"main": "./nope.js"}');
v.writeFileSync('/app/entry.mjs', "import 'badpkg';");
const mountPoint = v.mount();
await assert.rejects(
() => import(vfsImport(`${mountPoint}/app/entry.mjs`)),
(err) => {
assert.strictEqual(err.code, 'ERR_MODULE_NOT_FOUND');
assert.match(err.message, /nope\.js/);
assert.match(err.message, /^Cannot find package /);
assert.strictEqual(err.url, undefined);
return true;
},
);
v.unmount();
})().then(common.mustCall());
// Symlink inside a VFS: unmount purges cache entries recorded under the
// resolved realpath too. Remounting the same instance at the same prefix
// reuses the same mount point, so a stale entry would be revived.
{
const v = vfs.create();
v.mkdirSync('/real', { recursive: true });
v.writeFileSync('/real/mod.js', 'module.exports = "one"');
v.symlinkSync('/real/mod.js', '/link.js');
const mountPoint = v.mount();
assert.strictEqual(require(`${mountPoint}/link.js`), 'one');
v.unmount();
v.writeFileSync('/real/mod.js', 'module.exports = "two"');
const mountPoint2 = v.mount();
assert.strictEqual(mountPoint2, mountPoint);
assert.strictEqual(require(`${mountPoint2}/link.js`), 'two');
v.unmount();
}
+657
View File
@@ -0,0 +1,657 @@
// Flags: --experimental-vfs
import '../common/index.mjs';
import assert from 'assert';
import { createRequire } from 'module';
import { pathToFileURL } from 'node:url';
import vfs from 'node:vfs';
const require = createRequire(import.meta.url);
const vfsImport = (path) => pathToFileURL(path).href;
// mount() returns the actual mount point (reserved under os.devNull);
// each test captures it and uses it for requires/imports.
// Test: CJS bare specifier resolution with exports string shorthand
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/str-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/str-pkg/package.json', JSON.stringify({
name: 'str-pkg',
exports: './main.js',
}));
myVfs.writeFileSync(
'/app/node_modules/str-pkg/main.js',
'module.exports = { strExport: true };',
);
myVfs.writeFileSync(
'/app/entry.js',
"module.exports = require('str-pkg');",
);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/app/entry.js`);
assert.strictEqual(result.strExport, true);
myVfs.unmount();
}
// Test: Conditional exports with import/require/default conditions
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/cond-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/cond-pkg/package.json', JSON.stringify({
name: 'cond-pkg',
exports: {
import: './esm.mjs',
require: './cjs.js',
default: './default.js',
},
}));
myVfs.writeFileSync(
'/app/node_modules/cond-pkg/esm.mjs',
'export const source = "esm";',
);
myVfs.writeFileSync(
'/app/node_modules/cond-pkg/cjs.js',
'module.exports = { source: "cjs" };',
);
myVfs.writeFileSync(
'/app/node_modules/cond-pkg/default.js',
'module.exports = { source: "default" };',
);
myVfs.writeFileSync(
'/app/esm-entry.mjs',
"export { source } from 'cond-pkg';",
);
myVfs.writeFileSync(
'/app/cjs-entry.js',
"module.exports = require('cond-pkg');",
);
const mountPoint = myVfs.mount();
const esmResult = await import(vfsImport(`${mountPoint}/app/esm-entry.mjs`));
assert.strictEqual(esmResult.source, 'esm');
const cjsResult = require(`${mountPoint}/app/cjs-entry.js`);
assert.strictEqual(cjsResult.source, 'cjs');
myVfs.unmount();
}
// Test: Subpath exports map
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/sub-pkg/lib', { recursive: true });
myVfs.writeFileSync('/app/node_modules/sub-pkg/package.json', JSON.stringify({
name: 'sub-pkg',
exports: {
'.': './lib/index.mjs',
'./feature': './lib/feature.mjs',
},
}));
myVfs.writeFileSync(
'/app/node_modules/sub-pkg/lib/index.mjs',
'export const main = true;',
);
myVfs.writeFileSync(
'/app/node_modules/sub-pkg/lib/feature.mjs',
'export const feature = true;',
);
myVfs.writeFileSync(
'/app/entry.mjs',
`
import { main } from 'sub-pkg';
import { feature } from 'sub-pkg/feature';
export { main, feature };
`,
);
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/app/entry.mjs`));
assert.strictEqual(result.main, true);
assert.strictEqual(result.feature, true);
myVfs.unmount();
}
// Test: Subpath exports with conditional object target
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/sub-cond-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/sub-cond-pkg/package.json', JSON.stringify({
name: 'sub-cond-pkg',
exports: {
'.': {
import: './esm.mjs',
require: './cjs.js',
},
},
}));
myVfs.writeFileSync(
'/app/node_modules/sub-cond-pkg/esm.mjs',
'export const fromSubCond = "esm";',
);
myVfs.writeFileSync(
'/app/node_modules/sub-cond-pkg/cjs.js',
'module.exports = { fromSubCond: "cjs" };',
);
myVfs.writeFileSync(
'/app/entry2.mjs',
"export { fromSubCond } from 'sub-cond-pkg';",
);
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/app/entry2.mjs`));
assert.strictEqual(result.fromSubCond, 'esm');
myVfs.unmount();
}
// Test: Nested conditional exports (e.g. node -> import/require)
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/nested-cond-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/nested-cond-pkg/package.json', JSON.stringify({
name: 'nested-cond-pkg',
exports: {
node: {
import: './node-esm.mjs',
require: './node-cjs.js',
},
default: './fallback.js',
},
}));
myVfs.writeFileSync(
'/app/node_modules/nested-cond-pkg/node-esm.mjs',
'export const nested = "node-esm";',
);
myVfs.writeFileSync(
'/app/node_modules/nested-cond-pkg/node-cjs.js',
'module.exports = { nested: "node-cjs" };',
);
myVfs.writeFileSync(
'/app/node_modules/nested-cond-pkg/fallback.js',
'module.exports = { nested: "fallback" };',
);
myVfs.writeFileSync(
'/app/entry3.mjs',
"export { nested } from 'nested-cond-pkg';",
);
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/app/entry3.mjs`));
assert.strictEqual(result.nested, 'node-esm');
myVfs.unmount();
}
// Test: Package without exports, using main field
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/main-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/main-pkg/package.json', JSON.stringify({
name: 'main-pkg',
main: './lib/entry.js',
}));
myVfs.mkdirSync('/app/node_modules/main-pkg/lib', { recursive: true });
myVfs.writeFileSync(
'/app/node_modules/main-pkg/lib/entry.js',
'module.exports = { fromMain: true };',
);
myVfs.writeFileSync(
'/app/entry4.js',
"module.exports = require('main-pkg');",
);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/app/entry4.js`);
assert.strictEqual(result.fromMain, true);
myVfs.unmount();
}
// Test: Package without exports/main, fallback to index.js
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/index-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/index-pkg/package.json', JSON.stringify({
name: 'index-pkg',
}));
myVfs.writeFileSync(
'/app/node_modules/index-pkg/index.js',
'module.exports = { fromIndex: true };',
);
myVfs.writeFileSync(
'/app/entry5.js',
"module.exports = require('index-pkg');",
);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/app/entry5.js`);
assert.strictEqual(result.fromIndex, true);
myVfs.unmount();
}
// Test: Extension resolution (require without file extension)
{
const myVfs = vfs.create();
// The embedded specifier must be an absolute mounted path, so mount first.
const mountPoint = myVfs.mount();
myVfs.mkdirSync(`${mountPoint}/lib`, { recursive: true });
myVfs.writeFileSync(`${mountPoint}/lib/utils.js`, 'module.exports = { ext: "js" };');
myVfs.writeFileSync(
`${mountPoint}/lib/main.js`,
`module.exports = require(${JSON.stringify(`${mountPoint}/lib/utils`)});`,
);
const result = require(`${mountPoint}/lib/main.js`);
assert.strictEqual(result.ext, 'js');
myVfs.unmount();
}
// Test: Extension resolution with .json
{
const myVfs = vfs.create();
const mountPoint = myVfs.mount();
myVfs.writeFileSync(`${mountPoint}/data.json`, JSON.stringify({ ext: 'json' }));
myVfs.writeFileSync(
`${mountPoint}/reader.js`,
`module.exports = require(${JSON.stringify(`${mountPoint}/data`)});`,
);
const result = require(`${mountPoint}/reader.js`);
assert.strictEqual(result.ext, 'json');
myVfs.unmount();
}
// Test: Scoped package resolution (@scope/pkg)
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/@myorg/mylib', { recursive: true });
myVfs.writeFileSync('/app/node_modules/@myorg/mylib/package.json', JSON.stringify({
name: '@myorg/mylib',
type: 'module',
exports: './index.mjs',
}));
myVfs.writeFileSync(
'/app/node_modules/@myorg/mylib/index.mjs',
'export const scoped = true;',
);
myVfs.writeFileSync(
'/app/scoped-entry.mjs',
"export { scoped } from '@myorg/mylib';",
);
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/app/scoped-entry.mjs`));
assert.strictEqual(result.scoped, true);
myVfs.unmount();
}
// Test: Scoped package with subpath
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/@myorg/utils/lib', { recursive: true });
myVfs.writeFileSync('/app/node_modules/@myorg/utils/package.json', JSON.stringify({
name: '@myorg/utils',
exports: {
'.': './lib/index.mjs',
'./helpers': './lib/helpers.mjs',
},
}));
myVfs.writeFileSync(
'/app/node_modules/@myorg/utils/lib/index.mjs',
'export const main = true;',
);
myVfs.writeFileSync(
'/app/node_modules/@myorg/utils/lib/helpers.mjs',
'export const helpers = true;',
);
myVfs.writeFileSync(
'/app/scoped-sub-entry.mjs',
`
import { helpers } from '@myorg/utils/helpers';
export { helpers };
`,
);
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/app/scoped-sub-entry.mjs`));
assert.strictEqual(result.helpers, true);
myVfs.unmount();
}
// Test: .js file with type: module in package.json -> ESM format
{
const myVfs = vfs.create();
myVfs.writeFileSync('/package.json', JSON.stringify({ type: 'module' }));
myVfs.writeFileSync('/mod.js', 'export const fromModule = true;');
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/mod.js`));
assert.strictEqual(result.fromModule, true);
myVfs.unmount();
}
// Test: .cjs always treated as CommonJS regardless of package type
{
const myVfs = vfs.create();
const mountPoint = myVfs.mount();
myVfs.writeFileSync(`${mountPoint}/package.json`, JSON.stringify({ type: 'module' }));
myVfs.writeFileSync(`${mountPoint}/helper.cjs`, 'module.exports = { cjsAlways: true };');
myVfs.writeFileSync(
`${mountPoint}/use-cjs.js`,
`
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const result = require(${JSON.stringify(`${mountPoint}/helper.cjs`)});
export const cjsAlways = result.cjsAlways;
`,
);
const result = await import(vfsImport(`${mountPoint}/use-cjs.js`));
assert.strictEqual(result.cjsAlways, true);
myVfs.unmount();
}
// Test: file: URL specifier
{
const myVfs = vfs.create();
myVfs.writeFileSync('/fileurl.mjs', 'export const fromFileUrl = true;');
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/fileurl.mjs`));
assert.strictEqual(result.fromFileUrl, true);
myVfs.unmount();
}
// Test: Package with main field requiring extension resolution
{
const myVfs = vfs.create();
myVfs.mkdirSync('/dir-pkg', { recursive: true });
myVfs.writeFileSync('/dir-pkg/package.json', JSON.stringify({
name: 'dir-pkg',
main: './entry',
}));
myVfs.writeFileSync(
'/dir-pkg/entry.js',
'module.exports = { dirPkg: true };',
);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/dir-pkg`);
assert.strictEqual(result.dirPkg, true);
myVfs.unmount();
}
// Test: Bare specifier with package subpath (no exports, direct file)
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/direct-pkg/lib', { recursive: true });
myVfs.writeFileSync('/app/node_modules/direct-pkg/package.json', JSON.stringify({
name: 'direct-pkg',
}));
myVfs.writeFileSync(
'/app/node_modules/direct-pkg/lib/util.js',
'module.exports = { directSub: true };',
);
myVfs.writeFileSync(
'/app/entry-sub.js',
"module.exports = require('direct-pkg/lib/util.js');",
);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/app/entry-sub.js`);
assert.strictEqual(result.directSub, true);
myVfs.unmount();
}
// Test: Bare specifier subpath with extension resolution
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/ext-pkg/lib', { recursive: true });
myVfs.writeFileSync('/app/node_modules/ext-pkg/package.json', JSON.stringify({
name: 'ext-pkg',
}));
myVfs.writeFileSync(
'/app/node_modules/ext-pkg/lib/util.js',
'module.exports = { extSub: true };',
);
myVfs.writeFileSync(
'/app/entry-ext.js',
"module.exports = require('ext-pkg/lib/util');",
);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/app/entry-ext.js`);
assert.strictEqual(result.extSub, true);
myVfs.unmount();
}
// Test: Bare specifier main field with extension resolution
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/main-ext-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/main-ext-pkg/package.json', JSON.stringify({
name: 'main-ext-pkg',
main: './entry',
}));
myVfs.writeFileSync(
'/app/node_modules/main-ext-pkg/entry.js',
'module.exports = { mainExt: true };',
);
myVfs.writeFileSync(
'/app/entry-main-ext.js',
"module.exports = require('main-ext-pkg');",
);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/app/entry-main-ext.js`);
assert.strictEqual(result.mainExt, true);
myVfs.unmount();
}
// Test: exports with array value (fallback array)
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/arr-exp-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/arr-exp-pkg/package.json', JSON.stringify({
name: 'arr-exp-pkg',
exports: {
'.': ['./index.js', './fallback.js'],
},
main: './index.js',
}));
myVfs.writeFileSync(
'/app/node_modules/arr-exp-pkg/index.js',
'module.exports = { arrExport: true };',
);
myVfs.writeFileSync(
'/app/entry-arr.js',
"module.exports = require('arr-exp-pkg');",
);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/app/entry-arr.js`);
assert.strictEqual(result.arrExport, true);
myVfs.unmount();
}
// Test: Exports with "default" condition
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/default-pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/default-pkg/package.json', JSON.stringify({
name: 'default-pkg',
exports: {
'.': {
browser: './browser.js',
default: './default.mjs',
},
},
}));
myVfs.writeFileSync(
'/app/node_modules/default-pkg/default.mjs',
'export const fromDefault = true;',
);
myVfs.writeFileSync(
'/app/entry-default.mjs',
"export { fromDefault } from 'default-pkg';",
);
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/app/entry-default.mjs`));
assert.strictEqual(result.fromDefault, true);
myVfs.unmount();
}
// Test: Package.json type "commonjs" explicitly set for .js
{
const myVfs = vfs.create();
myVfs.writeFileSync('/package.json', JSON.stringify({ type: 'commonjs' }));
myVfs.writeFileSync('/explicit-cjs.js', 'module.exports = { explicitCjs: true };');
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/explicit-cjs.js`);
assert.strictEqual(result.explicitCjs, true);
myVfs.unmount();
}
// Test: .js file with no package.json -> defaults to commonjs
{
const myVfs = vfs.create();
myVfs.writeFileSync('/no-pkg.js', 'module.exports = { noPkg: true };');
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/no-pkg.js`);
assert.strictEqual(result.noPkg, true);
myVfs.unmount();
}
// Test: Package.json type walk stops at node_modules boundary
{
const myVfs = vfs.create();
myVfs.writeFileSync('/package.json', JSON.stringify({ type: 'module' }));
myVfs.mkdirSync('/node_modules/inner', { recursive: true });
myVfs.writeFileSync(
'/node_modules/inner/index.js',
'module.exports = { inner: true };',
);
const mountPoint = myVfs.mount();
// Walk stops at node_modules; type:module from root is not inherited.
const result = require(`${mountPoint}/node_modules/inner/index.js`);
assert.strictEqual(result.inner, true);
myVfs.unmount();
}
// Test: Invalid package.json in directory resolution
{
const myVfs = vfs.create();
myVfs.mkdirSync('/bad-json-dir', { recursive: true });
myVfs.writeFileSync('/bad-json-dir/package.json', '{ invalid json }');
myVfs.writeFileSync(
'/bad-json-dir/index.js',
'module.exports = { fallbackIndex: true };',
);
const mountPoint = myVfs.mount();
// Malformed package.json raises ERR_INVALID_PACKAGE_CONFIG after nodejs/node#48606.
assert.throws(() => require(`${mountPoint}/bad-json-dir`),
{ code: 'ERR_INVALID_PACKAGE_CONFIG' });
myVfs.unmount();
}
// Test: Invalid package.json in type walk-up
{
const myVfs = vfs.create();
myVfs.writeFileSync('/package.json', '{ broken json }');
myVfs.writeFileSync('/no-type.js', 'module.exports = { noType: true };');
const mountPoint = myVfs.mount();
assert.throws(() => require(`${mountPoint}/no-type.js`),
{ code: 'ERR_INVALID_PACKAGE_CONFIG' });
myVfs.unmount();
}
// Test: Scoped package without slash (just @scope/name)
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/@solo/pkg', { recursive: true });
myVfs.writeFileSync('/app/node_modules/@solo/pkg/package.json', JSON.stringify({
name: '@solo/pkg',
main: './index.js',
}));
myVfs.writeFileSync(
'/app/node_modules/@solo/pkg/index.js',
'module.exports = { solo: true };',
);
myVfs.writeFileSync(
'/app/entry-solo.js',
"module.exports = require('@solo/pkg');",
);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/app/entry-solo.js`);
assert.strictEqual(result.solo, true);
myVfs.unmount();
}
// Test: node: builtin passthrough
{
const myVfs = vfs.create();
myVfs.writeFileSync('/use-builtin.mjs', `
import path from 'node:path';
export const sep = path.sep;
`);
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/use-builtin.mjs`));
assert.strictEqual(typeof result.sep, 'string');
myVfs.unmount();
}
// Test: JSON import with type assertion
{
const myVfs = vfs.create();
myVfs.writeFileSync('/data.json', JSON.stringify({ preformat: true }));
const mountPoint = myVfs.mount();
const result = await import(vfsImport(`${mountPoint}/data.json`), { with: { type: 'json' } });
assert.strictEqual(result.default.preformat, true);
myVfs.unmount();
}
// Test: File with unknown extension -> defaults to commonjs
{
const myVfs = vfs.create();
myVfs.writeFileSync('/data.txt', 'module.exports = { txt: true };');
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/data.txt`);
assert.strictEqual(result.txt, true);
myVfs.unmount();
}
+106
View File
@@ -0,0 +1,106 @@
// Flags: --experimental-vfs
'use strict';
// The `node_modules` lookup for modules inside a mounted VFS stops at the
// mount point: no candidate directories above the mount root are generated,
// while the legacy CommonJS global folders (NODE_PATH etc.) still apply.
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('url');
const { execFileSync } = require('child_process');
const Module = require('module');
const vfs = require('node:vfs');
const tmpdir = require('../common/tmpdir');
// Test: module.paths for a CJS module inside a mounted VFS ends at the
// mount root.
{
const myVfs = vfs.create();
myVfs.mkdirSync('/foo/bar', { recursive: true });
myVfs.writeFileSync('/foo/bar/main.cjs', 'module.exports = module.paths;');
const mountPoint = myVfs.mount();
const paths = require(path.join(mountPoint, 'foo/bar/main.cjs'));
assert.deepStrictEqual(paths, [
path.join(mountPoint, 'foo/bar/node_modules'),
path.join(mountPoint, 'foo/node_modules'),
path.join(mountPoint, 'node_modules'),
]);
myVfs.unmount();
}
// Test: Module._nodeModulePaths for real paths still walks to the file
// system root.
{
const paths = Module._nodeModulePaths(__dirname);
const root = path.parse(__dirname).root;
assert.strictEqual(paths[paths.length - 1],
path.join(root, 'node_modules'));
}
// Test: bare specifiers resolve through node_modules directories inside
// the VFS, for both require() and import.
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/dep', { recursive: true });
myVfs.writeFileSync('/app/node_modules/dep/package.json',
'{"name":"dep","main":"index.js"}');
myVfs.writeFileSync('/app/node_modules/dep/index.js',
'module.exports = "dep-from-vfs";');
myVfs.writeFileSync('/app/main.cjs', 'module.exports = require("dep");');
myVfs.writeFileSync('/app/main.mjs',
'import dep from "dep"; export default dep;');
const mountPoint = myVfs.mount();
assert.strictEqual(require(path.join(mountPoint, 'app/main.cjs')),
'dep-from-vfs');
import(pathToFileURL(path.join(mountPoint, 'app/main.mjs')).href)
.then(common.mustCall((ns) => {
assert.strictEqual(ns.default, 'dep-from-vfs');
myVfs.unmount();
}));
}
// Test: a bare specifier that exists nowhere fails for both loaders.
{
const myVfs = vfs.create();
myVfs.writeFileSync('/missing.cjs', 'require("missing-pkg-xyz");');
myVfs.writeFileSync('/missing.mjs', 'import "missing-pkg-xyz";');
const mountPoint = myVfs.mount();
assert.throws(() => require(path.join(mountPoint, 'missing.cjs')),
{ code: 'MODULE_NOT_FOUND' });
assert.rejects(
import(pathToFileURL(path.join(mountPoint, 'missing.mjs')).href),
{ code: 'ERR_MODULE_NOT_FOUND' },
).then(() => myVfs.unmount()).then(common.mustCall());
}
// Test: the legacy CommonJS global folders still apply to require() from
// inside a VFS: a NODE_PATH directory provides the fallback.
{
tmpdir.refresh();
const globalDir = tmpdir.resolve('gpath');
fs.mkdirSync(path.join(globalDir, 'gdep'), { recursive: true });
fs.writeFileSync(path.join(globalDir, 'gdep', 'index.js'),
'module.exports = "from-node-path";');
const out = execFileSync(process.execPath, ['--experimental-vfs', '-e', `
const vfs = require('node:vfs');
const path = require('path');
const myVfs = vfs.create();
myVfs.writeFileSync('/main.cjs', 'console.log(require("gdep"));');
const mountPoint = myVfs.mount();
require(path.join(mountPoint, 'main.cjs'));
`], {
encoding: 'utf8',
env: { ...process.env, NODE_PATH: globalDir, NODE_NO_WARNINGS: '1' },
});
assert.strictEqual(out.trim(), 'from-node-path');
}
+31 -49
View File
@@ -3,30 +3,25 @@
// Error paths in the VFS mount layer:
// - EXDEV when renaming/linking across different VFS instances or VFS<->real
// - lastunmount handler cleanup (vfsState.handlers becomes null again)
// - rename of root mount point is rejected as overlapping
// - last-unmount handler cleanup (vfsState.handlers becomes null again)
// - namespace isolation between layers
require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const os = require('os');
const vfs = require('node:vfs');
const { vfsState } = require('internal/fs/utils');
const baseMountPoint = path.resolve('/tmp/vfs-mount-errors-' + process.pid);
let mountCounter = 0;
const nextMount = () => baseMountPoint + '-' + (mountCounter++);
// EXDEV: rename across two different VFS instances
{
const mountA = nextMount();
const mountB = nextMount();
const a = vfs.create();
const b = vfs.create();
a.writeFileSync('/file.txt', 'a');
b.mkdirSync('/x', { recursive: true });
a.mount(mountA);
b.mount(mountB);
const mountA = a.mount();
const mountB = b.mount();
assert.throws(
() => fs.renameSync(path.join(mountA, 'file.txt'),
@@ -39,14 +34,12 @@ const nextMount = () => baseMountPoint + '-' + (mountCounter++);
// EXDEV: copyFileSync across two different VFS instances
{
const mountA = nextMount();
const mountB = nextMount();
const a = vfs.create();
const b = vfs.create();
a.writeFileSync('/file.txt', 'a');
b.mkdirSync('/x', { recursive: true });
a.mount(mountA);
b.mount(mountB);
const mountA = a.mount();
const mountB = b.mount();
assert.throws(
() => fs.copyFileSync(path.join(mountA, 'file.txt'),
@@ -59,14 +52,12 @@ const nextMount = () => baseMountPoint + '-' + (mountCounter++);
// EXDEV: linkSync across two different VFS instances
{
const mountA = nextMount();
const mountB = nextMount();
const a = vfs.create();
const b = vfs.create();
a.writeFileSync('/file.txt', 'a');
b.mkdirSync('/x', { recursive: true });
a.mount(mountA);
b.mount(mountB);
const mountA = a.mount();
const mountB = b.mount();
assert.throws(
() => fs.linkSync(path.join(mountA, 'file.txt'),
@@ -79,10 +70,9 @@ const nextMount = () => baseMountPoint + '-' + (mountCounter++);
// EXDEV: rename from VFS to a real-fs path
{
const mountA = nextMount();
const a = vfs.create();
a.writeFileSync('/file.txt', 'a');
a.mount(mountA);
const mountA = a.mount();
const tmpReal = '/tmp/vfs-mount-real-' + process.pid + '.txt';
assert.throws(
@@ -96,25 +86,25 @@ const nextMount = () => baseMountPoint + '-' + (mountCounter++);
{
assert.strictEqual(vfsState.handlers, null);
const x = vfs.create();
x.mount(nextMount());
x.mount();
assert.notStrictEqual(vfsState.handlers, null);
x.unmount();
assert.strictEqual(vfsState.handlers, null);
// And it re-installs on a subsequent mount
const y = vfs.create();
y.mount(nextMount());
y.mount();
assert.notStrictEqual(vfsState.handlers, null);
y.unmount();
assert.strictEqual(vfsState.handlers, null);
}
// Two parallel non-overlapping mounts both register, last-out clears handlers
// Two parallel mounts both register, last-out clears handlers
{
const a = vfs.create();
const b = vfs.create();
a.mount(nextMount());
b.mount(nextMount());
a.mount();
b.mount();
assert.notStrictEqual(vfsState.handlers, null);
a.unmount();
assert.notStrictEqual(vfsState.handlers, null);
@@ -122,38 +112,30 @@ const nextMount = () => baseMountPoint + '-' + (mountCounter++);
assert.strictEqual(vfsState.handlers, null);
}
// Overlap detection: nested-under and parent-of both rejected
// Namespace isolation: a path in an unmounted (or never-mounted) layer
// namespace is not served by other active layers.
{
const parent = nextMount();
const child = path.join(parent, 'child');
const a = vfs.create();
const b = vfs.create();
a.mount(parent);
assert.throws(() => b.mount(child), { code: 'ERR_INVALID_STATE' });
a.unmount();
// Reverse direction: child first, then parent rejected
const c = vfs.create();
const d = vfs.create();
c.mount(child);
assert.throws(() => d.mount(parent), { code: 'ERR_INVALID_STATE' });
c.unmount();
}
// Equal mount points: second one rejected
{
const m = nextMount();
const a = vfs.create();
const b = vfs.create();
a.mount(m);
assert.throws(() => b.mount(m), { code: 'ERR_INVALID_STATE' });
a.writeFileSync('/f.txt', 'a');
b.writeFileSync('/f.txt', 'b');
const mountA = a.mount();
const mountB = b.mount();
assert.notStrictEqual(mountA, mountB);
b.unmount();
// B's namespace is dead even though A is still mounted.
assert.strictEqual(fs.existsSync(path.join(mountB, 'f.txt')), false);
assert.strictEqual(fs.readFileSync(path.join(mountA, 'f.txt'), 'utf8'), 'a');
// A malformed layer segment under the VFS root is not served either.
const bogus = path.join(os.devNull, 'vfs', 'not-a-number', 'f.txt');
assert.strictEqual(fs.existsSync(bogus), false);
a.unmount();
}
// Double-mount of same instance rejected
{
const a = vfs.create();
a.mount(nextMount());
assert.throws(() => a.mount(nextMount()), { code: 'ERR_INVALID_STATE' });
a.mount();
assert.throws(() => a.mount(), { code: 'ERR_INVALID_STATE' });
a.unmount();
}
+41
View File
@@ -0,0 +1,41 @@
// Flags: --experimental-vfs
'use strict';
require('../common');
const assert = require('assert');
const fs = require('fs');
const { pathToFileURL } = require('url');
const vfs = require('node:vfs');
// Test: null while not mounted.
{
const myVfs = vfs.create();
assert.strictEqual(myVfs.mountPointURL, null);
}
// Test: file: URL string of the mount point while mounted, null again
// after unmounting.
{
const myVfs = vfs.create();
const mountPoint = myVfs.mount();
const url = myVfs.mountPointURL;
assert.strictEqual(typeof url, 'string');
assert.ok(url.startsWith('file:'));
assert.strictEqual(url, pathToFileURL(mountPoint).href);
myVfs.unmount();
assert.strictEqual(myVfs.mountPointURL, null);
}
// Test: the URL is usable to address files in the mounted VFS.
{
const myVfs = vfs.create();
myVfs.writeFileSync('/data.txt', 'hello url');
myVfs.mount();
const fileURL = new URL(`${myVfs.mountPointURL}/data.txt`);
assert.strictEqual(fs.readFileSync(fileURL, 'utf8'), 'hello url');
myVfs.unmount();
}
+27 -19
View File
@@ -5,32 +5,37 @@ const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const os = require('os');
const vfs = require('node:vfs');
// Mount points look like `${os.devNull}/vfs/<id>` where `<id>` is a decimal
// integer segment. This regex captures that structural invariant without
// tying the tests to a specific id.
const mountPointShape = new RegExp(
`^${os.devNull.replace(/[\\^$.*+?()[\]{}|/\\\\]/g, '\\$&')}` +
`\\${path.sep}vfs\\${path.sep}\\d+$`,
);
// Basic mount/unmount API and dispatch through node:vfs from the public fs.
const baseMountPoint = path.resolve('/tmp/vfs-mount-' + process.pid);
let mountCounter = 0;
function createMountedVfs() {
const mountPoint = baseMountPoint + '-' + (mountCounter++);
const myVfs = vfs.create();
myVfs.mkdirSync('/src', { recursive: true });
myVfs.writeFileSync('/src/hello.txt', 'hello world');
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
return { myVfs, mountPoint };
}
// Test: mounted/mountPoint getters
// Test: mounted/mountPoint getters; mount() returns a path under os.devNull.
{
const myVfs = vfs.create();
assert.strictEqual(myVfs.mounted, false);
assert.strictEqual(myVfs.mountPoint, null);
const mountPoint = baseMountPoint + '-' + (mountCounter++);
myVfs.mount(mountPoint);
const mountPoint = myVfs.mount();
assert.strictEqual(myVfs.mounted, true);
assert.strictEqual(myVfs.mountPoint, mountPoint);
assert.match(mountPoint, mountPointShape);
myVfs.unmount();
assert.strictEqual(myVfs.mounted, false);
@@ -40,22 +45,26 @@ function createMountedVfs() {
// Test: double-mount throws
{
const myVfs = vfs.create();
const mountPoint = baseMountPoint + '-' + (mountCounter++);
myVfs.mount(mountPoint);
assert.throws(() => myVfs.mount(mountPoint), { code: 'ERR_INVALID_STATE' });
myVfs.mount();
assert.throws(() => myVfs.mount(), { code: 'ERR_INVALID_STATE' });
myVfs.unmount();
}
// Test: overlapping mounts throw
// Test: two instances get distinct mount points in their own layer namespace.
{
const a = vfs.create();
const b = vfs.create();
const mountPoint = baseMountPoint + '-' + (mountCounter++);
a.mount(mountPoint);
assert.throws(() => b.mount(mountPoint), { code: 'ERR_INVALID_STATE' });
assert.throws(() => b.mount(path.join(mountPoint, 'inner')),
{ code: 'ERR_INVALID_STATE' });
a.writeFileSync('/f.txt', 'A');
b.writeFileSync('/f.txt', 'B');
const mountA = a.mount();
const mountB = b.mount();
assert.notStrictEqual(mountA, mountB);
assert.match(mountA, mountPointShape);
assert.match(mountB, mountPointShape);
assert.strictEqual(fs.readFileSync(path.join(mountA, 'f.txt'), 'utf8'), 'A');
assert.strictEqual(fs.readFileSync(path.join(mountB, 'f.txt'), 'utf8'), 'B');
a.unmount();
b.unmount();
}
// Test: fs.readFileSync intercepted
@@ -165,8 +174,7 @@ function createMountedVfs() {
// Test: Symbol.dispose unmounts
{
const myVfs = vfs.create();
const mountPoint = baseMountPoint + '-' + (mountCounter++);
myVfs.mount(mountPoint);
myVfs.mount();
assert.strictEqual(myVfs.mounted, true);
myVfs[Symbol.dispose]();
assert.strictEqual(myVfs.mounted, false);
+4 -7
View File
@@ -1,8 +1,8 @@
// Flags: --experimental-vfs
'use strict';
// Two concurrent non-overlapping mounts must each route to its own VFS without
// interference. Also exercises that the handler registry iterates and routes
// Two concurrent mounts must each route to its own VFS without
// interference. Also exercises that the layer registry routes
// correctly when more than one VFS is active.
require('../common');
@@ -11,9 +11,6 @@ const fs = require('fs');
const path = require('path');
const vfs = require('node:vfs');
const baseA = path.resolve('/tmp/vfs-multi-a-' + process.pid);
const baseB = path.resolve('/tmp/vfs-multi-b-' + process.pid);
const a = vfs.create();
a.writeFileSync('/file.txt', 'from-a');
a.mkdirSync('/dir', { recursive: true });
@@ -24,8 +21,8 @@ b.writeFileSync('/file.txt', 'from-b');
b.mkdirSync('/dir', { recursive: true });
b.writeFileSync('/dir/inside.txt', 'b-inside');
a.mount(baseA);
b.mount(baseB);
const baseA = a.mount();
const baseB = b.mount();
// Each mount sees its own content
assert.strictEqual(fs.readFileSync(path.join(baseA, 'file.txt'), 'utf8'),
@@ -0,0 +1,40 @@
// Flags: --experimental-vfs
'use strict';
// Package.json caches must be cleared on VFS unmount.
require('../common');
const assert = require('assert');
const fs = require('fs');
const vfs = require('node:vfs');
const myVfs = vfs.create();
myVfs.mkdirSync('/pkg');
myVfs.writeFileSync('/pkg/package.json', '{"name":"test","type":"module"}');
myVfs.writeFileSync('/pkg/index.js', 'module.exports = 42');
const mountPoint = myVfs.mount();
assert.ok(fs.existsSync(`${mountPoint}/pkg/package.json`));
myVfs.unmount();
assert.strictEqual(fs.existsSync(`${mountPoint}/pkg/package.json`), false);
// Remounting the same instance reuses the same mount point; a package.json
// whose `type` changed between mounts must be re-read, not served from the
// nearest-parent caches populated during the first mount.
{
const remountVfs = vfs.create();
remountVfs.mkdirSync('/scope');
remountVfs.writeFileSync('/scope/package.json', '{"type":"commonjs"}');
remountVfs.writeFileSync('/scope/index.js', 'module.exports = 42;');
const mp = remountVfs.mount();
assert.strictEqual(require(`${mp}/scope/index.js`), 42);
remountVfs.unmount();
remountVfs.writeFileSync('/scope/package.json', '{"type":"module"}');
remountVfs.writeFileSync('/scope/index.js', 'export default 43;');
assert.strictEqual(remountVfs.mount(), mp);
assert.strictEqual(require(`${mp}/scope/index.js`).default, 43);
remountVfs.unmount();
}
+183
View File
@@ -0,0 +1,183 @@
// Flags: --experimental-vfs --expose-internals
'use strict';
require('../common');
const assert = require('assert');
const path = require('path');
const vfs = require('node:vfs');
// read() reads package.json from VFS
{
const myVfs = vfs.create();
myVfs.mkdirSync('/pkg', { recursive: true });
myVfs.writeFileSync('/pkg/package.json', JSON.stringify({
name: 'test-pkg',
type: 'module',
main: './index.js',
exports: { '.': './index.js' },
}));
const mountPoint = myVfs.mount();
const packageJsonReader = require('internal/modules/package_json_reader');
const result = packageJsonReader.read(
path.join(mountPoint, 'pkg', 'package.json'), {},
);
assert.strictEqual(result.exists, true);
assert.strictEqual(result.name, 'test-pkg');
assert.strictEqual(result.type, 'module');
assert.strictEqual(result.main, './index.js');
assert.deepStrictEqual(result.exports, { '.': './index.js' });
assert.strictEqual(
result.pjsonPath,
path.join(mountPoint, 'pkg', 'package.json'),
);
// Non-existent package.json returns exists: false
const missing = packageJsonReader.read(
path.join(mountPoint, 'nope', 'package.json'), {},
);
assert.strictEqual(missing.exists, false);
myVfs.unmount();
}
// getNearestParentPackageJSON() walks up VFS directories
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/src/lib/deep', { recursive: true });
myVfs.writeFileSync('/app/package.json', JSON.stringify({
name: 'my-app',
type: 'module',
}));
myVfs.writeFileSync('/app/src/lib/deep/module.js', '');
const mountPoint = myVfs.mount();
const packageJsonReader = require('internal/modules/package_json_reader');
const result = packageJsonReader.getNearestParentPackageJSON(
path.join(mountPoint, 'app', 'src', 'lib', 'deep', 'module.js'),
);
assert.ok(result);
assert.strictEqual(result.exists, true);
assert.strictEqual(result.data.name, 'my-app');
assert.strictEqual(result.data.type, 'module');
assert.strictEqual(
result.path,
path.join(mountPoint, 'app', 'package.json'),
);
myVfs.unmount();
}
// getPackageScopeConfig() returns correct scope from VFS
{
const myVfs = vfs.create();
myVfs.mkdirSync('/project/src', { recursive: true });
myVfs.writeFileSync('/project/package.json', JSON.stringify({
name: 'my-project',
type: 'commonjs',
exports: { '.': './main.js' },
}));
myVfs.writeFileSync('/project/src/index.js', '');
const mountPoint = myVfs.mount();
const packageJsonReader = require('internal/modules/package_json_reader');
const { pathToFileURL } = require('url');
const scopeUrl = pathToFileURL(
path.join(mountPoint, 'project', 'src', 'index.js'),
).href;
const result = packageJsonReader.getPackageScopeConfig(scopeUrl);
assert.strictEqual(result.exists, true);
assert.strictEqual(result.type, 'commonjs');
assert.strictEqual(result.name, 'my-project');
assert.strictEqual(
result.pjsonPath,
path.join(mountPoint, 'project', 'package.json'),
);
// Path with no package.json returns exists: false
const myVfs2 = vfs.create();
myVfs2.mkdirSync('/empty/src', { recursive: true });
myVfs2.writeFileSync('/empty/src/file.js', '');
const mountPoint2 = myVfs2.mount();
const emptyUrl = pathToFileURL(
path.join(mountPoint2, 'empty', 'src', 'file.js'),
).href;
const emptyResult = packageJsonReader.getPackageScopeConfig(emptyUrl);
assert.strictEqual(emptyResult.exists, false);
myVfs2.unmount();
myVfs.unmount();
}
// getPackageType() returns correct type from VFS
{
const myVfs = vfs.create();
myVfs.mkdirSync('/esm-app', { recursive: true });
myVfs.writeFileSync('/esm-app/package.json', JSON.stringify({
type: 'module',
}));
myVfs.writeFileSync('/esm-app/index.js', '');
const mountPoint = myVfs.mount();
const packageJsonReader = require('internal/modules/package_json_reader');
const { pathToFileURL } = require('url');
const typeUrl = pathToFileURL(
path.join(mountPoint, 'esm-app', 'index.js'),
).href;
const type = packageJsonReader.getPackageType(typeUrl);
assert.strictEqual(type, 'module');
// No package.json => 'none'
const myVfs2 = vfs.create();
myVfs2.mkdirSync('/bare', { recursive: true });
myVfs2.writeFileSync('/bare/file.js', '');
const mountPoint2 = myVfs2.mount();
const noneUrl = pathToFileURL(
path.join(mountPoint2, 'bare', 'file.js'),
).href;
const noneType = packageJsonReader.getPackageType(noneUrl);
assert.strictEqual(noneType, 'none');
myVfs2.unmount();
myVfs.unmount();
}
// End-to-end CJS require with package.json type detection
{
const myVfs = vfs.create();
myVfs.mkdirSync('/cjs-app', { recursive: true });
myVfs.writeFileSync('/cjs-app/package.json', JSON.stringify({
name: 'cjs-app',
type: 'commonjs',
}));
myVfs.writeFileSync('/cjs-app/main.js',
'module.exports = { format: "cjs", ok: true };');
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/cjs-app/main.js`);
assert.strictEqual(result.format, 'cjs');
assert.strictEqual(result.ok, true);
myVfs.unmount();
}
// End-to-end ESM import with VFS package type
{
const myVfs = vfs.create();
myVfs.mkdirSync('/esm', { recursive: true });
myVfs.writeFileSync('/esm/package.json', JSON.stringify({
type: 'module',
}));
myVfs.writeFileSync('/esm/mod.mjs', 'export const x = 42;');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/esm/mod.mjs`);
assert.strictEqual(mod.x, 42);
myVfs.unmount();
}
+411
View File
@@ -0,0 +1,411 @@
// Flags: --experimental-vfs
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const { pathToFileURL } = require('node:url');
const vfs = require('node:vfs');
const vfsImport = (path) => pathToFileURL(path).href;
// Test requiring a simple virtual module
{
const myVfs = vfs.create();
myVfs.writeFileSync('/hello.js', 'module.exports = "hello from vfs";');
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/hello.js`);
assert.strictEqual(result, 'hello from vfs');
myVfs.unmount();
}
// Test requiring a virtual module that exports an object
{
const myVfs = vfs.create();
myVfs.writeFileSync('/config.js', `
module.exports = {
name: 'test-config',
version: '1.0.0',
getValue: function() { return 42; }
};
`);
const mountPoint = myVfs.mount();
const config = require(`${mountPoint}/config.js`);
assert.strictEqual(config.name, 'test-config');
assert.strictEqual(config.version, '1.0.0');
assert.strictEqual(config.getValue(), 42);
myVfs.unmount();
}
// Test requiring a virtual module that requires another virtual module.
// Mount first so the embedded absolute specifier can use the mount point.
{
const myVfs = vfs.create();
const mountPoint = myVfs.mount();
myVfs.writeFileSync(`${mountPoint}/utils.js`, `
module.exports = {
add: function(a, b) { return a + b; }
};
`);
myVfs.writeFileSync(`${mountPoint}/main.js`, `
const utils = require(${JSON.stringify(`${mountPoint}/utils.js`)});
module.exports = {
sum: utils.add(10, 20)
};
`);
const main = require(`${mountPoint}/main.js`);
assert.strictEqual(main.sum, 30);
myVfs.unmount();
}
// Test requiring a JSON file from VFS
{
const myVfs = vfs.create();
myVfs.writeFileSync('/data.json', JSON.stringify({
items: [1, 2, 3],
enabled: true,
}));
const mountPoint = myVfs.mount();
const data = require(`${mountPoint}/data.json`);
assert.deepStrictEqual(data.items, [1, 2, 3]);
assert.strictEqual(data.enabled, true);
myVfs.unmount();
}
// Test virtual package.json resolution
{
const myVfs = vfs.create();
myVfs.mkdirSync('/my-package', { recursive: true });
myVfs.writeFileSync('/my-package/package.json', JSON.stringify({
name: 'my-package',
main: 'index.js',
}));
myVfs.writeFileSync('/my-package/index.js', `
module.exports = { loaded: true };
`);
const mountPoint = myVfs.mount();
const pkg = require(`${mountPoint}/my-package`);
assert.strictEqual(pkg.loaded, true);
myVfs.unmount();
}
// Test that real modules still work when VFS is mounted
{
const myVfs = vfs.create();
myVfs.writeFileSync('/test.js', 'module.exports = 1;');
myVfs.mount();
assert.strictEqual(typeof assert.strictEqual, 'function');
const commonMod = require('../common');
assert.ok(commonMod);
myVfs.unmount();
}
// Test require with relative paths inside VFS module
{
const myVfs = vfs.create();
myVfs.mkdirSync('/lib', { recursive: true });
myVfs.writeFileSync('/lib/helper.js', `
module.exports = { help: function() { return 'helped'; } };
`);
myVfs.writeFileSync('/lib/index.js', `
const helper = require('./helper.js');
module.exports = helper.help();
`);
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/lib/index.js`);
assert.strictEqual(result, 'helped');
myVfs.unmount();
}
// Test fs.readFileSync interception when VFS is active
{
const myVfs = vfs.create();
myVfs.writeFileSync('/file.txt', 'virtual content');
const mountPoint = myVfs.mount();
const content = fs.readFileSync(`${mountPoint}/file.txt`, 'utf8');
assert.strictEqual(content, 'virtual content');
myVfs.unmount();
}
// Test requiring an ESM .mjs module from VFS
{
const myVfs = vfs.create();
myVfs.writeFileSync('/esm.mjs', 'export const msg = "hello from esm";');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/esm.mjs`);
assert.strictEqual(mod.msg, 'hello from esm');
myVfs.unmount();
}
// Test requiring an ESM .mjs module with default export from VFS
{
const myVfs = vfs.create();
myVfs.writeFileSync('/esm-default.mjs', 'export default function() { return 42; }');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/esm-default.mjs`);
assert.strictEqual(mod.default(), 42);
myVfs.unmount();
}
// Test require(esm): .js file detected as ESM via VFS package.json type:module
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app', { recursive: true });
myVfs.writeFileSync('/app/package.json', JSON.stringify({
name: 'esm-app',
type: 'module',
}));
myVfs.writeFileSync('/app/lib.js',
'export const value = 42;' +
' export function hello() { return "hi"; }');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/app/lib.js`);
assert.strictEqual(mod.value, 42);
assert.strictEqual(mod.hello(), 'hi');
myVfs.unmount();
}
// Test require(esm): nested .js walks up to parent package.json in VFS
{
const myVfs = vfs.create();
myVfs.mkdirSync('/project/src/utils', { recursive: true });
myVfs.writeFileSync('/project/package.json', JSON.stringify({
name: 'nested-esm',
type: 'module',
}));
myVfs.writeFileSync('/project/src/utils/math.js',
'export const add = (a, b) => a + b;' +
' export default 99;');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/project/src/utils/math.js`);
assert.strictEqual(mod.add(3, 4), 7);
assert.strictEqual(mod.default, 99);
myVfs.unmount();
}
// Test require(esm): .js without type field stays CJS
{
const myVfs = vfs.create();
myVfs.mkdirSync('/cjs-app', { recursive: true });
myVfs.writeFileSync('/cjs-app/package.json', JSON.stringify({
name: 'cjs-app',
}));
myVfs.writeFileSync('/cjs-app/index.js',
'module.exports = { cjs: true };');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/cjs-app/index.js`);
assert.strictEqual(mod.cjs, true);
myVfs.unmount();
}
// Test require(esm): ESM .js that imports another ESM .js in VFS
{
const myVfs = vfs.create();
myVfs.mkdirSync('/multi/src', { recursive: true });
myVfs.writeFileSync('/multi/package.json', JSON.stringify({
type: 'module',
}));
myVfs.writeFileSync('/multi/src/dep.js', 'export const X = 100;');
myVfs.writeFileSync('/multi/src/main.js',
'import { X } from "./dep.js";' +
' export const result = X + 1;');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/multi/src/main.js`);
assert.strictEqual(mod.result, 101);
myVfs.unmount();
}
// Test require(esm): .mjs without any package.json loads as ESM
{
const myVfs = vfs.create();
myVfs.writeFileSync('/no-pkg.mjs',
'export const x = 1; export default "hello";');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/no-pkg.mjs`);
assert.strictEqual(mod.x, 1);
assert.strictEqual(mod.default, 'hello');
myVfs.unmount();
}
// Test require(esm): .mjs with package.json that has no type field
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app', { recursive: true });
myVfs.writeFileSync('/app/package.json',
JSON.stringify({ name: 'no-type' }));
myVfs.writeFileSync('/app/lib.mjs', 'export const val = 42;');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/app/lib.mjs`);
assert.strictEqual(mod.val, 42);
myVfs.unmount();
}
// Test require(esm): .mjs in type:commonjs package still loads as ESM
{
const myVfs = vfs.create();
myVfs.mkdirSync('/cjs-pkg', { recursive: true });
myVfs.writeFileSync('/cjs-pkg/package.json', JSON.stringify({
name: 'cjs-pkg',
type: 'commonjs',
}));
myVfs.writeFileSync('/cjs-pkg/esm.mjs', 'export const z = 99;');
const mountPoint = myVfs.mount();
const mod = require(`${mountPoint}/cjs-pkg/esm.mjs`);
assert.strictEqual(mod.z, 99);
myVfs.unmount();
}
// Test CJS: package with "main" field resolves through VFS
{
const myVfs = vfs.create();
myVfs.mkdirSync('/pkg/lib', { recursive: true });
myVfs.writeFileSync('/pkg/package.json', JSON.stringify({
name: 'legacy-main-pkg',
main: './lib/entry',
}));
myVfs.writeFileSync('/pkg/lib/entry.js', 'module.exports = "legacy-main";');
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/pkg`);
assert.strictEqual(result, 'legacy-main');
myVfs.unmount();
}
// Test CJS: package with no "main" field resolves index.js
{
const myVfs = vfs.create();
myVfs.mkdirSync('/pkg2', { recursive: true });
myVfs.writeFileSync('/pkg2/package.json', JSON.stringify({
name: 'no-main-pkg',
}));
myVfs.writeFileSync('/pkg2/index.js', 'module.exports = "index-fallback";');
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/pkg2`);
assert.strictEqual(result, 'index-fallback');
myVfs.unmount();
}
// Test ESM legacyMainResolve: import() a VFS package with "main" (no "exports")
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app/node_modules/esm-legacy-main/lib', { recursive: true });
myVfs.writeFileSync('/app/node_modules/esm-legacy-main/package.json', JSON.stringify({
name: 'esm-legacy-main',
type: 'module',
main: './lib/entry.js',
}));
myVfs.writeFileSync('/app/node_modules/esm-legacy-main/lib/entry.js',
'export const value = "esm-legacy-main";');
myVfs.writeFileSync('/app/main.mjs',
'export { value } from "esm-legacy-main";');
const mountPoint = myVfs.mount();
import(vfsImport(`${mountPoint}/app/main.mjs`)).then(common.mustCall((mod) => {
assert.strictEqual(mod.value, 'esm-legacy-main');
myVfs.unmount();
}));
}
// Test ESM legacyMainResolve: import() a VFS package with no "main" (index.js fallback)
{
const myVfs = vfs.create();
myVfs.mkdirSync('/app2/node_modules/esm-nomain', { recursive: true });
myVfs.writeFileSync('/app2/node_modules/esm-nomain/package.json', JSON.stringify({
name: 'esm-nomain',
type: 'module',
}));
myVfs.writeFileSync('/app2/node_modules/esm-nomain/index.js',
'export const value = "esm-index-fallback";');
myVfs.writeFileSync('/app2/main.mjs',
'export { value } from "esm-nomain";');
const mountPoint = myVfs.mount();
import(vfsImport(`${mountPoint}/app2/main.mjs`)).then(common.mustCall((mod) => {
assert.strictEqual(mod.value, 'esm-index-fallback');
myVfs.unmount();
}));
}
// Test getFormatOfExtensionlessFile: extensionless JS file in type:module package
{
const myVfs = vfs.create();
myVfs.mkdirSync('/esm-pkg', { recursive: true });
myVfs.writeFileSync('/esm-pkg/package.json', JSON.stringify({
name: 'esm-pkg',
type: 'module',
}));
myVfs.writeFileSync('/esm-pkg/entry', 'export const x = 123;');
const mountPoint = myVfs.mount();
import(vfsImport(`${mountPoint}/esm-pkg/entry`)).then(common.mustCall((mod) => {
assert.strictEqual(mod.x, 123);
myVfs.unmount();
}));
}
// Test that unmounting stops interception
{
const myVfs = vfs.create();
myVfs.writeFileSync('/unmount-test.js', 'module.exports = "before unmount";');
const mountPoint = myVfs.mount();
const result = require(`${mountPoint}/unmount-test.js`);
assert.strictEqual(result, 'before unmount');
myVfs.unmount();
// On Windows, the native loader may surface the NUL-backed former mount
// path as ERR_INVALID_PACKAGE_CONFIG while probing for package.json.
assert.throws(() => {
delete require.cache[path.join(mountPoint, 'unmount-test.js')];
require(`${mountPoint}/unmount-test.js`);
}, (err) => {
if (common.isWindows) {
assert.ok(
['ERR_INVALID_PACKAGE_CONFIG', 'MODULE_NOT_FOUND'].includes(err.code),
);
} else {
assert.strictEqual(err.code, 'MODULE_NOT_FOUND');
}
return true;
});
}
+1 -37
View File
@@ -9,38 +9,11 @@
require('../common');
const assert = require('assert');
const path = require('path');
const { isUnderMountPoint, getRelativePath, isAbsolutePath } =
require('internal/vfs/router');
const { getRelativePath } = require('internal/vfs/router');
const mount = path.resolve('/app');
const nested = path.join(mount, 'src', 'index.js');
// isUnderMountPoint: equal paths are always considered "under"
assert.strictEqual(isUnderMountPoint(mount, mount), true);
// isUnderMountPoint: nested paths
assert.strictEqual(isUnderMountPoint(nested, mount), true);
// isUnderMountPoint: rejects sibling paths that share the prefix string
assert.strictEqual(
isUnderMountPoint(path.resolve('/app2/index.js'), mount), false,
);
assert.strictEqual(isUnderMountPoint(path.resolve('/applebrick'), mount),
false);
// isUnderMountPoint: rejects an unrelated absolute path
assert.strictEqual(isUnderMountPoint(path.resolve('/other'), mount), false);
// isUnderMountPoint: root mount matches any absolute path on POSIX.
// On Windows the root mount '/' resolves to a drive-letter root, so the
// special-case in router.js only applies when mountPoint === '/'. Skip the
// root-mount checks where they would not be representative on Windows.
if (process.platform !== 'win32') {
assert.strictEqual(isUnderMountPoint('/anywhere', '/'), true);
assert.strictEqual(isUnderMountPoint('/', '/'), true);
assert.strictEqual(isUnderMountPoint('/a/b/c', '/'), true);
}
// getRelativePath: equal => '/'
assert.strictEqual(getRelativePath(mount, mount), '/');
@@ -48,16 +21,7 @@ assert.strictEqual(getRelativePath(mount, mount), '/');
// the platform-native input separators.
assert.strictEqual(getRelativePath(nested, mount), '/src/index.js');
// getRelativePath: root mount returns the original (already absolute) path
if (process.platform !== 'win32') {
assert.strictEqual(getRelativePath('/foo/bar', '/'), '/foo/bar');
}
// getRelativePath: deeper nesting
const mountA = path.resolve('/m/a');
const deep = path.join(mountA, 'b', 'c', 'd');
assert.strictEqual(getRelativePath(deep, mountA), '/b/c/d');
// isAbsolutePath is re-exported from node:path
assert.strictEqual(isAbsolutePath(path.resolve('/foo')), true);
assert.strictEqual(isAbsolutePath('foo'), false);
@@ -0,0 +1,57 @@
// Flags: --experimental-vfs
'use strict';
// Deregistering one VFS must scope-purge loader caches: entries under the
// unmounted mount point are dropped, entries from other VFSes are kept.
const common = require('../common');
const assert = require('assert');
const { pathToFileURL } = require('node:url');
const vfs = require('node:vfs');
const vfsImport = (path) => pathToFileURL(path).href;
// Multi-mount: deregistering one VFS keeps the other's CJS require.cache warm.
{
const a = vfs.create();
a.writeFileSync('/value.js', 'module.exports = "a-cached"');
const mountA = a.mount();
const b = vfs.create();
b.writeFileSync('/value.js', 'module.exports = "b-cached"');
const mountB = b.mount();
assert.strictEqual(require(`${mountA}/value.js`), 'a-cached');
assert.strictEqual(require(`${mountB}/value.js`), 'b-cached');
const bKey = require.resolve(`${mountB}/value.js`);
assert.ok(bKey in require.cache, 'b should be cached before unmount');
a.unmount();
assert.ok(
bKey in require.cache,
'unmounting a different VFS must not evict b\'s cache entry',
);
assert.strictEqual(require(`${mountB}/value.js`), 'b-cached');
b.unmount();
}
// import.meta.url is the plain file URL under the mount point, and repeated
// dynamic imports (including via import.meta.resolve) return the same namespace.
(async () => {
const v = vfs.create();
v.writeFileSync('/m.mjs',
'export const url = import.meta.url;\n' +
'export const resolved = import.meta.resolve("./m.mjs");');
const mountPoint = v.mount();
const ns = await import(vfsImport(`${mountPoint}/m.mjs`));
assert.strictEqual(ns.url, pathToFileURL(`${mountPoint}/m.mjs`).href);
const nsAgain = await import(ns.resolved);
assert.strictEqual(ns, nsAgain);
v.unmount();
})().then(common.mustCall());