initial commit

This commit is contained in:
2023-08-13 16:48:04 +03:00
commit 73b7dbb0a6
1267 changed files with 1017047 additions and 0 deletions

24
node_modules/ts-node/dist-raw/NODE-LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,24 @@
This directory contains portions of Node.js source code which is licensed as follows:
---
Copyright Joyent, Inc. and other Node contributors.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.

36
node_modules/ts-node/dist-raw/README.md generated vendored Normal file
View File

@ -0,0 +1,36 @@
The `dist-raw` directory contains JS sources that are distributed verbatim, not compiled nor typechecked via TS.
To implement ESM support, we unfortunately must duplicate some of node's built-in functionality that is not
exposed via an API. We have copy-pasted the necessary code from https://github.com/nodejs/node/tree/master/lib
then modified it to suite our needs.
Formatting may be intentionally bad to keep the diff as small as possible, to make it easier to merge
upstream changes and understand our modifications. For example, when we need to wrap node's source code
in a factory function, we will not indent the function body, to avoid whitespace changes in the diff.
One obvious problem with this approach: the code has been pulled from one version of node, whereas users of ts-node
run multiple versions of node.
Users running node 12 may see that ts-node behaves like node 14, for example.
## `raw` directory
Within the `raw` directory, we keep unmodified copies of the node source files. This allows us to use diffing tools to
compare files in `raw` to those in `dist-raw`, which will highlight all of the changes we have made. Hopefully, these
changes are as minimal as possible.
## Naming convention
Not used consistently, but the idea is:
`node-<directory>(...-<directory>)-<filename>.js`
`node-internal-errors.js` -> `github.com/nodejs/node/blob/TAG/lib/internal/errors.js`
So, take the path within node's `lib/` directory, and replace slashes with hyphens.
In the `raw` directory, files are suffixed with the version number or revision from which
they were downloaded.
If they have a `stripped` suffix, this means they have large chunks of code deleted, but no other modifications.
This is useful when diffing. Sometimes our `dist-raw` files only have a small part of a much larger node source file.
It is easier to diff `raw/*-stripped.js` against `dist-raw/*.js`.

View File

@ -0,0 +1,4 @@
// Copied from https://github.com/nodejs/node/blob/master/lib/internal/constants.js
module.exports = {
CHAR_FORWARD_SLASH: 47, /* / */
};

82
node_modules/ts-node/dist-raw/node-internal-errors.js generated vendored Normal file
View File

@ -0,0 +1,82 @@
'use strict';
const path = require('path');
exports.codes = {
ERR_INPUT_TYPE_NOT_ALLOWED: createErrorCtor(joinArgs('ERR_INPUT_TYPE_NOT_ALLOWED')),
ERR_INVALID_ARG_VALUE: createErrorCtor(joinArgs('ERR_INVALID_ARG_VALUE')),
ERR_INVALID_MODULE_SPECIFIER: createErrorCtor(joinArgs('ERR_INVALID_MODULE_SPECIFIER')),
ERR_INVALID_PACKAGE_CONFIG: createErrorCtor(joinArgs('ERR_INVALID_PACKAGE_CONFIG')),
ERR_INVALID_PACKAGE_TARGET: createErrorCtor(joinArgs('ERR_INVALID_PACKAGE_TARGET')),
ERR_MANIFEST_DEPENDENCY_MISSING: createErrorCtor(joinArgs('ERR_MANIFEST_DEPENDENCY_MISSING')),
ERR_MODULE_NOT_FOUND: createErrorCtor((path, base, type = 'package') => {
return `Cannot find ${type} '${path}' imported from ${base}`
}),
ERR_PACKAGE_IMPORT_NOT_DEFINED: createErrorCtor(joinArgs('ERR_PACKAGE_IMPORT_NOT_DEFINED')),
ERR_PACKAGE_PATH_NOT_EXPORTED: createErrorCtor(joinArgs('ERR_PACKAGE_PATH_NOT_EXPORTED')),
ERR_UNSUPPORTED_DIR_IMPORT: createErrorCtor(joinArgs('ERR_UNSUPPORTED_DIR_IMPORT')),
ERR_UNSUPPORTED_ESM_URL_SCHEME: createErrorCtor(joinArgs('ERR_UNSUPPORTED_ESM_URL_SCHEME')),
ERR_UNKNOWN_FILE_EXTENSION: createErrorCtor(joinArgs('ERR_UNKNOWN_FILE_EXTENSION')),
}
function joinArgs(name) {
return (...args) => {
return [name, ...args].join(' ')
}
}
function createErrorCtor(errorMessageCreator) {
return class CustomError extends Error {
constructor(...args) {
super(errorMessageCreator(...args))
}
}
}
exports.createErrRequireEsm = createErrRequireEsm;
// Native ERR_REQUIRE_ESM Error is declared here:
// https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L1294-L1313
// Error class factory is implemented here:
// function E: https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L323-L341
// function makeNodeErrorWithCode: https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/errors.js#L251-L278
// The code below should create an error that matches the native error as closely as possible.
// Third-party libraries which attempt to catch the native ERR_REQUIRE_ESM should recognize our imitation error.
function createErrRequireEsm(filename, parentPath, packageJsonPath) {
const code = 'ERR_REQUIRE_ESM'
const err = new Error(getErrRequireEsmMessage(filename, parentPath, packageJsonPath))
// Set `name` to be used in stack trace, generate stack trace with that name baked in, then re-declare the `name` field.
// This trick is copied from node's source.
err.name = `Error [${ code }]`
err.stack
Object.defineProperty(err, 'name', {
value: 'Error',
enumerable: false,
writable: true,
configurable: true
})
err.code = code
return err
}
// Copy-pasted from https://github.com/nodejs/node/blob/b533fb3508009e5f567cc776daba8fbf665386a6/lib/internal/errors.js#L1293-L1311
// so that our error message is identical to the native message.
function getErrRequireEsmMessage(filename, parentPath = null, packageJsonPath = null) {
const ext = path.extname(filename)
let msg = `Must use import to load ES Module: ${filename}`;
if (parentPath && packageJsonPath) {
const path = require('path');
const basename = path.basename(filename) === path.basename(parentPath) ?
filename : path.basename(filename);
msg +=
'\nrequire() of ES modules is not supported.\nrequire() of ' +
`${filename} ${parentPath ? `from ${parentPath} ` : ''}` +
`is an ES module file as it is a ${ext} file whose nearest parent ` +
`package.json contains "type": "module" which defines all ${ext} ` +
'files in that package scope as ES modules.\nInstead ' +
'change the requiring code to use ' +
'import(), or remove "type": "module" from ' +
`${packageJsonPath}.\n`;
return msg;
}
return msg;
}

View File

@ -0,0 +1,89 @@
// Copied from https://github.com/nodejs/node/blob/v17.0.1/lib/internal/modules/cjs/helpers.js
'use strict';
const {
ArrayPrototypeForEach,
ObjectDefineProperty,
ObjectPrototypeHasOwnProperty,
SafeSet,
StringPrototypeIncludes,
StringPrototypeStartsWith,
} = require('./node-primordials');
const { getOptionValue } = require('./node-options');
const userConditions = getOptionValue('--conditions');
const noAddons = getOptionValue('--no-addons');
const addonConditions = noAddons ? [] : ['node-addons'];
// TODO: Use this set when resolving pkg#exports conditions in loader.js.
const cjsConditions = new SafeSet([
'require',
'node',
...addonConditions,
...userConditions,
]);
/**
* @param {any} object
* @param {string} [dummyModuleName]
* @return {void}
*/
function addBuiltinLibsToObject(object, dummyModuleName) {
// Make built-in modules available directly (loaded lazily).
const Module = require('module').Module;
const { builtinModules } = Module;
// To require built-in modules in user-land and ignore modules whose
// `canBeRequiredByUsers` is false. So we create a dummy module object and not
// use `require()` directly.
const dummyModule = new Module(dummyModuleName);
ArrayPrototypeForEach(builtinModules, (name) => {
// Neither add underscored modules, nor ones that contain slashes (e.g.,
// 'fs/promises') or ones that are already defined.
if (StringPrototypeStartsWith(name, '_') ||
StringPrototypeIncludes(name, '/') ||
ObjectPrototypeHasOwnProperty(object, name)) {
return;
}
// Goals of this mechanism are:
// - Lazy loading of built-in modules
// - Having all built-in modules available as non-enumerable properties
// - Allowing the user to re-assign these variables as if there were no
// pre-existing globals with the same name.
const setReal = (val) => {
// Deleting the property before re-assigning it disables the
// getter/setter mechanism.
delete object[name];
object[name] = val;
};
ObjectDefineProperty(object, name, {
get: () => {
// Node 12 hack; remove when we drop node12 support
const lib = (dummyModule.require || require)(name);
// Disable the current getter/setter and set up a new
// non-enumerable property.
delete object[name];
ObjectDefineProperty(object, name, {
get: () => lib,
set: setReal,
configurable: true,
enumerable: false
});
return lib;
},
set: setReal,
configurable: true,
enumerable: false
});
});
}
exports.addBuiltinLibsToObject = addBuiltinLibsToObject;
exports.cjsConditions = cjsConditions;

View File

@ -0,0 +1,593 @@
// Copied from several files in node's source code.
// https://github.com/nodejs/node/blob/2d5d77306f6dff9110c1f77fefab25f973415770/lib/internal/modules/cjs/loader.js
// Each function and variable below must have a comment linking to the source in node's github repo.
'use strict';
const {
ArrayIsArray,
ArrayPrototypeIncludes,
ArrayPrototypeJoin,
ArrayPrototypePush,
JSONParse,
ObjectKeys,
RegExpPrototypeTest,
SafeMap,
SafeWeakMap,
StringPrototypeCharCodeAt,
StringPrototypeEndsWith,
StringPrototypeLastIndexOf,
StringPrototypeIndexOf,
StringPrototypeMatch,
StringPrototypeSlice,
StringPrototypeStartsWith,
} = require('./node-primordials');
const { NativeModule } = require('./node-nativemodule');
const { pathToFileURL, fileURLToPath } = require('url');
const fs = require('fs');
const path = require('path');
const { sep } = path;
const { internalModuleStat } = require('./node-internalBinding-fs');
const packageJsonReader = require('./node-internal-modules-package_json_reader');
const {
cjsConditions,
} = require('./node-internal-modules-cjs-helpers');
const { getOptionValue } = require('./node-options');
const preserveSymlinks = getOptionValue('--preserve-symlinks');
const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
const {normalizeSlashes} = require('../dist/util');
const {createErrRequireEsm} = require('./node-internal-errors');
const {
codes: {
ERR_INVALID_MODULE_SPECIFIER,
},
} = require('./node-internal-errors');
const {
CHAR_FORWARD_SLASH,
} = require('./node-internal-constants');
const Module = require('module');
const isWindows = process.platform === 'win32';
let statCache = null;
function stat(filename) {
filename = path.toNamespacedPath(filename);
if (statCache !== null) {
const result = statCache.get(filename);
if (result !== undefined) return result;
}
const result = internalModuleStat(filename);
if (statCache !== null && result >= 0) {
// Only set cache when `internalModuleStat(filename)` succeeds.
statCache.set(filename, result);
}
return result;
}
// Note:
// we cannot get access to node's internal cache, which is populated from
// within node's Module constructor. So the cache here will always be empty.
// It's possible we could approximate our own cache by building it up with
// hacky workarounds, but it's not worth the complexity and flakiness.
const moduleParentCache = new SafeWeakMap();
// Given a module name, and a list of paths to test, returns the first
// matching file in the following precedence.
//
// require("a.<ext>")
// -> a.<ext>
//
// require("a")
// -> a
// -> a.<ext>
// -> a/index.<ext>
const packageJsonCache = new SafeMap();
function readPackage(requestPath) {
const jsonPath = path.resolve(requestPath, 'package.json');
const existing = packageJsonCache.get(jsonPath);
if (existing !== undefined) return existing;
const result = packageJsonReader.read(jsonPath);
const json = result.containsKeys === false ? '{}' : result.string;
if (json === undefined) {
packageJsonCache.set(jsonPath, false);
return false;
}
try {
const parsed = JSONParse(json);
const filtered = {
name: parsed.name,
main: parsed.main,
exports: parsed.exports,
imports: parsed.imports,
type: parsed.type
};
packageJsonCache.set(jsonPath, filtered);
return filtered;
} catch (e) {
e.path = jsonPath;
e.message = 'Error parsing ' + jsonPath + ': ' + e.message;
throw e;
}
}
function readPackageScope(checkPath) {
const rootSeparatorIndex = StringPrototypeIndexOf(checkPath, sep);
let separatorIndex;
do {
separatorIndex = StringPrototypeLastIndexOf(checkPath, sep);
checkPath = StringPrototypeSlice(checkPath, 0, separatorIndex);
if (StringPrototypeEndsWith(checkPath, sep + 'node_modules'))
return false;
const pjson = readPackage(checkPath + sep);
if (pjson) return {
data: pjson,
path: checkPath,
};
} while (separatorIndex > rootSeparatorIndex);
return false;
}
/**
* @param {{
* nodeEsmResolver: ReturnType<typeof import('./node-internal-modules-esm-resolve').createResolve>,
* extensions: import('../src/file-extensions').Extensions,
* preferTsExts
* }} opts
*/
function createCjsLoader(opts) {
const {nodeEsmResolver, preferTsExts} = opts;
const {replacementsForCjs, replacementsForJs, replacementsForMjs, replacementsForJsx} = opts.extensions;
const {
encodedSepRegEx,
packageExportsResolve,
packageImportsResolve
} = nodeEsmResolver;
function tryPackage(requestPath, exts, isMain, originalPath) {
// const pkg = readPackage(requestPath)?.main;
const tmp = readPackage(requestPath)
const pkg = tmp != null ? tmp.main : undefined;
if (!pkg) {
return tryExtensions(path.resolve(requestPath, 'index'), exts, isMain);
}
const filename = path.resolve(requestPath, pkg);
let actual = tryReplacementExtensions(filename, isMain) ||
tryFile(filename, isMain) ||
tryExtensions(filename, exts, isMain) ||
tryExtensions(path.resolve(filename, 'index'), exts, isMain);
if (actual === false) {
actual = tryExtensions(path.resolve(requestPath, 'index'), exts, isMain);
if (!actual) {
// eslint-disable-next-line no-restricted-syntax
const err = new Error(
`Cannot find module '${filename}'. ` +
'Please verify that the package.json has a valid "main" entry'
);
err.code = 'MODULE_NOT_FOUND';
err.path = path.resolve(requestPath, 'package.json');
err.requestPath = originalPath;
// TODO(BridgeAR): Add the requireStack as well.
throw err;
} else {
const jsonPath = path.resolve(requestPath, 'package.json');
process.emitWarning(
`Invalid 'main' field in '${jsonPath}' of '${pkg}'. ` +
'Please either fix that or report it to the module author',
'DeprecationWarning',
'DEP0128'
);
}
}
return actual;
}
// In order to minimize unnecessary lstat() calls,
// this cache is a list of known-real paths.
// Set to an empty Map to reset.
const realpathCache = new SafeMap();
// Check if the file exists and is not a directory
// if using --preserve-symlinks and isMain is false,
// keep symlinks intact, otherwise resolve to the
// absolute realpath.
function tryFile(requestPath, isMain) {
const rc = stat(requestPath);
if (rc !== 0) return;
if (preserveSymlinks && !isMain) {
return path.resolve(requestPath);
}
return toRealPath(requestPath);
}
function toRealPath(requestPath) {
return fs.realpathSync(requestPath, {
// [internalFS.realpathCacheKey]: realpathCache
});
}
function statReplacementExtensions(p) {
const lastDotIndex = p.lastIndexOf('.');
if(lastDotIndex >= 0) {
const ext = p.slice(lastDotIndex);
if (ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs') {
const pathnameWithoutExtension = p.slice(0, lastDotIndex);
const replacementExts =
ext === '.js' ? replacementsForJs
: ext === '.jsx' ? replacementsForJsx
: ext === '.mjs' ? replacementsForMjs
: replacementsForCjs;
for (let i = 0; i < replacementExts.length; i++) {
const filename = pathnameWithoutExtension + replacementExts[i];
const rc = stat(filename);
if (rc === 0) {
return [rc, filename];
}
}
}
}
return [stat(p), p];
}
function tryReplacementExtensions(p, isMain) {
const lastDotIndex = p.lastIndexOf('.');
if(lastDotIndex >= 0) {
const ext = p.slice(lastDotIndex);
if (ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs') {
const pathnameWithoutExtension = p.slice(0, lastDotIndex);
const replacementExts =
ext === '.js' ? replacementsForJs
: ext === '.jsx' ? replacementsForJsx
: ext === '.mjs' ? replacementsForMjs
: replacementsForCjs;
for (let i = 0; i < replacementExts.length; i++) {
const filename = tryFile(pathnameWithoutExtension + replacementExts[i], isMain);
if (filename) {
return filename;
}
}
}
}
return false;
}
// Given a path, check if the file exists with any of the set extensions
function tryExtensions(p, exts, isMain) {
for (let i = 0; i < exts.length; i++) {
const filename = tryFile(p + exts[i], isMain);
if (filename) {
return filename;
}
}
return false;
}
function trySelfParentPath(parent) {
if (!parent) return false;
if (parent.filename) {
return parent.filename;
} else if (parent.id === '<repl>' || parent.id === 'internal/preload') {
try {
return process.cwd() + path.sep;
} catch {
return false;
}
}
}
function trySelf(parentPath, request) {
if (!parentPath) return false;
const { data: pkg, path: pkgPath } = readPackageScope(parentPath) || {};
if (!pkg || pkg.exports === undefined) return false;
if (typeof pkg.name !== 'string') return false;
let expansion;
if (request === pkg.name) {
expansion = '.';
} else if (StringPrototypeStartsWith(request, `${pkg.name}/`)) {
expansion = '.' + StringPrototypeSlice(request, pkg.name.length);
} else {
return false;
}
try {
return finalizeEsmResolution(packageExportsResolve(
pathToFileURL(pkgPath + '/package.json'), expansion, pkg,
pathToFileURL(parentPath), cjsConditions).resolved, parentPath, pkgPath);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND')
throw createEsmNotFoundErr(request, pkgPath + '/package.json');
throw e;
}
}
// This only applies to requests of a specific form:
// 1. name/.*
// 2. @scope/name/.*
const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/;
function resolveExports(nmPath, request) {
// The implementation's behavior is meant to mirror resolution in ESM.
const { 1: name, 2: expansion = '' } =
StringPrototypeMatch(request, EXPORTS_PATTERN) || [];
if (!name)
return;
const pkgPath = path.resolve(nmPath, name);
const pkg = readPackage(pkgPath);
// if (pkg?.exports != null) {
if (pkg != null && pkg.exports != null) {
try {
return finalizeEsmResolution(packageExportsResolve(
pathToFileURL(pkgPath + '/package.json'), '.' + expansion, pkg, null,
cjsConditions).resolved, null, pkgPath);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND')
throw createEsmNotFoundErr(request, pkgPath + '/package.json');
throw e;
}
}
}
// Backwards compat for old node versions
const hasModulePathCache = !!require('module')._pathCache;
const Module_pathCache = Object.create(null);
const Module_pathCache_get = hasModulePathCache ? (cacheKey) => Module._pathCache[cacheKey] : (cacheKey) => Module_pathCache[cacheKey];
const Module_pathCache_set = hasModulePathCache ? (cacheKey, value) => (Module._pathCache[cacheKey] = value) : (cacheKey) => (Module_pathCache[cacheKey] = value);
const trailingSlashRegex = /(?:^|\/)\.?\.$/;
const Module_findPath = function _findPath(request, paths, isMain) {
const absoluteRequest = path.isAbsolute(request);
if (absoluteRequest) {
paths = [''];
} else if (!paths || paths.length === 0) {
return false;
}
const cacheKey = request + '\x00' + ArrayPrototypeJoin(paths, '\x00');
const entry = Module_pathCache_get(cacheKey);
if (entry)
return entry;
let exts;
let trailingSlash = request.length > 0 &&
StringPrototypeCharCodeAt(request, request.length - 1) ===
CHAR_FORWARD_SLASH;
if (!trailingSlash) {
trailingSlash = RegExpPrototypeTest(trailingSlashRegex, request);
}
// For each path
for (let i = 0; i < paths.length; i++) {
// Don't search further if path doesn't exist
const curPath = paths[i];
if (curPath && stat(curPath) < 1) continue;
if (!absoluteRequest) {
const exportsResolved = resolveExports(curPath, request);
if (exportsResolved)
return exportsResolved;
}
const _basePath = path.resolve(curPath, request);
let filename;
const [rc, basePath] = statReplacementExtensions(_basePath);
if (!trailingSlash) {
if (rc === 0) { // File.
if (!isMain) {
if (preserveSymlinks) {
filename = path.resolve(basePath);
} else {
filename = toRealPath(basePath);
}
} else if (preserveSymlinksMain) {
// For the main module, we use the preserveSymlinksMain flag instead
// mainly for backward compatibility, as the preserveSymlinks flag
// historically has not applied to the main module. Most likely this
// was intended to keep .bin/ binaries working, as following those
// symlinks is usually required for the imports in the corresponding
// files to resolve; that said, in some use cases following symlinks
// causes bigger problems which is why the preserveSymlinksMain option
// is needed.
filename = path.resolve(basePath);
} else {
filename = toRealPath(basePath);
}
}
if (!filename) {
// Try it with each of the extensions
if (exts === undefined)
exts = ObjectKeys(Module._extensions);
filename = tryExtensions(basePath, exts, isMain);
}
}
if (!filename && rc === 1) { // Directory.
// try it with each of the extensions at "index"
if (exts === undefined)
exts = ObjectKeys(Module._extensions);
filename = tryPackage(basePath, exts, isMain, request);
}
if (filename) {
Module_pathCache_set(cacheKey, filename);
return filename;
}
}
return false;
};
const Module_resolveFilename = function _resolveFilename(request, parent, isMain, options) {
if (StringPrototypeStartsWith(request, 'node:') ||
NativeModule.canBeRequiredByUsers(request)) {
return request;
}
let paths;
if (typeof options === 'object' && options !== null) {
if (ArrayIsArray(options.paths)) {
const isRelative = StringPrototypeStartsWith(request, './') ||
StringPrototypeStartsWith(request, '../') ||
((isWindows && StringPrototypeStartsWith(request, '.\\')) ||
StringPrototypeStartsWith(request, '..\\'));
if (isRelative) {
paths = options.paths;
} else {
const fakeParent = new Module('', null);
paths = [];
for (let i = 0; i < options.paths.length; i++) {
const path = options.paths[i];
fakeParent.paths = Module._nodeModulePaths(path);
const lookupPaths = Module._resolveLookupPaths(request, fakeParent);
for (let j = 0; j < lookupPaths.length; j++) {
if (!ArrayPrototypeIncludes(paths, lookupPaths[j]))
ArrayPrototypePush(paths, lookupPaths[j]);
}
}
}
} else if (options.paths === undefined) {
paths = Module._resolveLookupPaths(request, parent);
} else {
throw new ERR_INVALID_ARG_VALUE('options.paths', options.paths);
}
} else {
paths = Module._resolveLookupPaths(request, parent);
}
// if (parent?.filename) {
// node 12 hack
if (parent != null && parent.filename) {
if (request[0] === '#') {
const pkg = readPackageScope(parent.filename) || {};
// if (pkg.data?.imports != null) {
// node 12 hack
if (pkg.data != null && pkg.data.imports != null) {
try {
return finalizeEsmResolution(
packageImportsResolve(request, pathToFileURL(parent.filename),
cjsConditions), parent.filename,
pkg.path);
} catch (e) {
if (e.code === 'ERR_MODULE_NOT_FOUND')
throw createEsmNotFoundErr(request);
throw e;
}
}
}
}
// Try module self resolution first
const parentPath = trySelfParentPath(parent);
const selfResolved = trySelf(parentPath, request);
if (selfResolved) {
const cacheKey = request + '\x00' +
(paths.length === 1 ? paths[0] : ArrayPrototypeJoin(paths, '\x00'));
Module._pathCache[cacheKey] = selfResolved;
return selfResolved;
}
// Look up the filename first, since that's the cache key.
const filename = Module._findPath(request, paths, isMain, false);
if (filename) return filename;
const requireStack = [];
for (let cursor = parent;
cursor;
cursor = moduleParentCache.get(cursor)) {
ArrayPrototypePush(requireStack, cursor.filename || cursor.id);
}
let message = `Cannot find module '${request}'`;
if (requireStack.length > 0) {
message = message + '\nRequire stack:\n- ' +
ArrayPrototypeJoin(requireStack, '\n- ');
}
// eslint-disable-next-line no-restricted-syntax
const err = new Error(message);
err.code = 'MODULE_NOT_FOUND';
err.requireStack = requireStack;
throw err;
};
function finalizeEsmResolution(resolved, parentPath, pkgPath) {
if (RegExpPrototypeTest(encodedSepRegEx, resolved))
throw new ERR_INVALID_MODULE_SPECIFIER(
resolved, 'must not include encoded "/" or "\\" characters', parentPath);
const filename = fileURLToPath(resolved);
const actual = tryReplacementExtensions(filename) || tryFile(filename);
if (actual)
return actual;
const err = createEsmNotFoundErr(filename,
path.resolve(pkgPath, 'package.json'));
throw err;
}
function createEsmNotFoundErr(request, path) {
// eslint-disable-next-line no-restricted-syntax
const err = new Error(`Cannot find module '${request}'`);
err.code = 'MODULE_NOT_FOUND';
if (path)
err.path = path;
// TODO(BridgeAR): Add the requireStack as well.
return err;
}
return {
Module_findPath,
Module_resolveFilename
}
}
/**
* copied from Module._extensions['.js']
* https://github.com/nodejs/node/blob/v15.3.0/lib/internal/modules/cjs/loader.js#L1113-L1120
* @param {import('../src/index').Service} service
* @param {NodeJS.Module} module
* @param {string} filename
*/
function assertScriptCanLoadAsCJSImpl(service, module, filename) {
const pkg = readPackageScope(filename);
// ts-node modification: allow our configuration to override
const tsNodeClassification = service.moduleTypeClassifier.classifyModuleByModuleTypeOverrides(normalizeSlashes(filename));
if(tsNodeClassification.moduleType === 'cjs') return;
// ignore package.json when file extension is ESM-only or CJS-only
// [MUST_UPDATE_FOR_NEW_FILE_EXTENSIONS]
const lastDotIndex = filename.lastIndexOf('.');
const ext = lastDotIndex >= 0 ? filename.slice(lastDotIndex) : '';
if((ext === '.cts' || ext === '.cjs') && tsNodeClassification.moduleType === 'auto') return;
// Function require shouldn't be used in ES modules.
if (ext === '.mts' || ext === '.mjs' || tsNodeClassification.moduleType === 'esm' || (pkg && pkg.data && pkg.data.type === 'module')) {
const parentPath = module.parent && module.parent.filename;
const packageJsonPath = pkg ? path.resolve(pkg.path, 'package.json') : null;
throw createErrRequireEsm(filename, parentPath, packageJsonPath);
}
}
module.exports = {
createCjsLoader,
assertScriptCanLoadAsCJSImpl,
readPackageScope
};

View File

@ -0,0 +1,106 @@
// Copied from https://raw.githubusercontent.com/nodejs/node/v15.3.0/lib/internal/modules/esm/get_format.js
'use strict';
const {
RegExpPrototypeExec,
StringPrototypeStartsWith,
} = require('./node-primordials');
const { extname } = require('path');
const { getOptionValue } = require('./node-options');
const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(s => parseInt(s, 10));
const experimentalJsonModules =
nodeMajor > 17
|| (nodeMajor === 17 && nodeMinor >= 5)
|| (nodeMajor === 16 && nodeMinor >= 15)
|| getOptionValue('--experimental-json-modules');
const experimentalWasmModules = getOptionValue('--experimental-wasm-modules');
const { URL, fileURLToPath } = require('url');
const { ERR_UNKNOWN_FILE_EXTENSION } = require('./node-internal-errors').codes;
const extensionFormatMap = {
'__proto__': null,
'.cjs': 'commonjs',
'.js': 'module',
'.mjs': 'module'
};
const legacyExtensionFormatMap = {
'__proto__': null,
'.cjs': 'commonjs',
'.js': 'commonjs',
'.json': 'commonjs',
'.mjs': 'module',
'.node': 'commonjs'
};
if (experimentalWasmModules)
extensionFormatMap['.wasm'] = legacyExtensionFormatMap['.wasm'] = 'wasm';
if (experimentalJsonModules)
extensionFormatMap['.json'] = legacyExtensionFormatMap['.json'] = 'json';
/**
*
* @param {'node' | 'explicit'} [tsNodeExperimentalSpecifierResolution]
* @param {ReturnType<
* typeof import('../dist-raw/node-internal-modules-esm-resolve').createResolve
* >} nodeEsmResolver
*/
function createGetFormat(tsNodeExperimentalSpecifierResolution, nodeEsmResolver) {
// const experimentalSpeciferResolution = tsNodeExperimentalSpecifierResolution ?? getOptionValue('--experimental-specifier-resolution');
let experimentalSpeciferResolution = tsNodeExperimentalSpecifierResolution != null ? tsNodeExperimentalSpecifierResolution : getOptionValue('--experimental-specifier-resolution');
const { getPackageType } = nodeEsmResolver;
/**
* @param {string} url
* @param {{}} context
* @param {any} defaultGetFormatUnused
* @returns {ReturnType<import('../src/esm').NodeLoaderHooksAPI1.GetFormatHook>}
*/
function defaultGetFormat(url, context, defaultGetFormatUnused) {
if (StringPrototypeStartsWith(url, 'node:')) {
return { format: 'builtin' };
}
const parsed = new URL(url);
if (parsed.protocol === 'data:') {
const [ , mime ] = RegExpPrototypeExec(
/^([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
parsed.pathname,
) || [ null, null, null ];
const format = ({
'__proto__': null,
'text/javascript': 'module',
'application/json': experimentalJsonModules ? 'json' : null,
'application/wasm': experimentalWasmModules ? 'wasm' : null
})[mime] || null;
return { format };
} else if (parsed.protocol === 'file:') {
const ext = extname(parsed.pathname);
let format;
if (ext === '.js') {
format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs';
} else {
format = extensionFormatMap[ext];
}
if (!format) {
if (experimentalSpeciferResolution === 'node') {
process.emitWarning(
'The Node.js specifier resolution in ESM is experimental.',
'ExperimentalWarning');
format = legacyExtensionFormatMap[ext];
} else {
throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url));
}
}
return { format: format || null };
}
return { format: null };
}
return {defaultGetFormat};
}
module.exports = {
createGetFormat
};

View File

@ -0,0 +1,962 @@
// Copied from https://raw.githubusercontent.com/nodejs/node/v15.3.0/lib/internal/modules/esm/resolve.js
'use strict';
const {versionGteLt} = require('../dist/util');
// Test for node >14.13.1 || (>=12.20.0 && <13)
const builtinModuleProtocol =
versionGteLt(process.versions.node, '14.13.1') ||
versionGteLt(process.versions.node, '12.20.0', '13.0.0')
? 'node:'
: 'nodejs:';
const {
ArrayIsArray,
ArrayPrototypeJoin,
ArrayPrototypeShift,
JSONParse,
JSONStringify,
ObjectFreeze,
ObjectGetOwnPropertyNames,
ObjectPrototypeHasOwnProperty,
RegExpPrototypeTest,
SafeMap,
SafeSet,
StringPrototypeEndsWith,
StringPrototypeIndexOf,
StringPrototypeLastIndexOf,
StringPrototypeReplace,
StringPrototypeSlice,
StringPrototypeSplit,
StringPrototypeStartsWith,
StringPrototypeSubstr,
} = require('./node-primordials');
// const internalFS = require('internal/fs/utils');
const Module = require('module');
const { NativeModule } = require('./node-nativemodule');
const {
realpathSync,
statSync,
Stats,
} = require('fs');
// const { getOptionValue } = require('internal/options');
const { getOptionValue } = require('./node-options');
// // Do not eagerly grab .manifest, it may be in TDZ
// const policy = getOptionValue('--experimental-policy') ?
// require('internal/process/policy') :
// null;
// disabled for now. I am not sure if/how we should support this
const policy = null;
const { sep, relative } = require('path');
const preserveSymlinks = getOptionValue('--preserve-symlinks');
const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
const typeFlag = getOptionValue('--input-type');
// const { URL, pathToFileURL, fileURLToPath } = require('internal/url');
const { URL, pathToFileURL, fileURLToPath } = require('url');
const {
ERR_INPUT_TYPE_NOT_ALLOWED,
ERR_INVALID_ARG_VALUE,
ERR_INVALID_MODULE_SPECIFIER,
ERR_INVALID_PACKAGE_CONFIG,
ERR_INVALID_PACKAGE_TARGET,
ERR_MANIFEST_DEPENDENCY_MISSING,
ERR_MODULE_NOT_FOUND,
ERR_PACKAGE_IMPORT_NOT_DEFINED,
ERR_PACKAGE_PATH_NOT_EXPORTED,
ERR_UNSUPPORTED_DIR_IMPORT,
ERR_UNSUPPORTED_ESM_URL_SCHEME,
// } = require('internal/errors').codes;
} = require('./node-internal-errors').codes;
// const { Module: CJSModule } = require('internal/modules/cjs/loader');
const CJSModule = Module;
// const packageJsonReader = require('internal/modules/package_json_reader');
const packageJsonReader = require('./node-internal-modules-package_json_reader');
const userConditions = getOptionValue('--conditions');
const DEFAULT_CONDITIONS = ObjectFreeze(['node', 'import', ...userConditions]);
const DEFAULT_CONDITIONS_SET = new SafeSet(DEFAULT_CONDITIONS);
const pendingDeprecation = getOptionValue('--pending-deprecation');
/**
* @param {{
* extensions: import('../src/file-extensions').Extensions,
* preferTsExts: boolean | undefined;
* tsNodeExperimentalSpecifierResolution: import('../src/index').ExperimentalSpecifierResolution | undefined;
* }} opts
*/
function createResolve(opts) {
// TODO receive cached fs implementations here
const {preferTsExts, tsNodeExperimentalSpecifierResolution, extensions} = opts;
const esrnExtensions = extensions.experimentalSpecifierResolutionAddsIfOmitted;
const {legacyMainResolveAddsIfOmitted, replacementsForCjs, replacementsForJs, replacementsForMjs, replacementsForJsx} = extensions;
// const experimentalSpecifierResolution = tsNodeExperimentalSpecifierResolution ?? getOptionValue('--experimental-specifier-resolution');
const experimentalSpecifierResolution = tsNodeExperimentalSpecifierResolution != null ? tsNodeExperimentalSpecifierResolution : getOptionValue('--experimental-specifier-resolution');
const emittedPackageWarnings = new SafeSet();
function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) {
const pjsonPath = fileURLToPath(pjsonUrl);
if (!pendingDeprecation) {
const nodeModulesIndex = StringPrototypeLastIndexOf(pjsonPath,
'/node_modules/');
if (nodeModulesIndex !== -1) {
const afterNodeModulesPath = StringPrototypeSlice(pjsonPath,
nodeModulesIndex + 14,
-13);
try {
const { packageSubpath } = parsePackageName(afterNodeModulesPath);
if (packageSubpath === '.')
return;
} catch {}
}
}
if (emittedPackageWarnings.has(pjsonPath + '|' + match))
return;
emittedPackageWarnings.add(pjsonPath + '|' + match);
process.emitWarning(
`Use of deprecated folder mapping "${match}" in the ${isExports ?
'"exports"' : '"imports"'} field module resolution of the package at ${
pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ''}.\n` +
`Update this package.json to use a subpath pattern like "${match}*".`,
'DeprecationWarning',
'DEP0148'
);
}
function getConditionsSet(conditions) {
if (conditions !== undefined && conditions !== DEFAULT_CONDITIONS) {
if (!ArrayIsArray(conditions)) {
throw new ERR_INVALID_ARG_VALUE('conditions', conditions,
'expected an array');
}
return new SafeSet(conditions);
}
return DEFAULT_CONDITIONS_SET;
}
const realpathCache = new SafeMap();
const packageJSONCache = new SafeMap(); /* string -> PackageConfig */
const statSupportsThrowIfNoEntry = versionGteLt(process.versions.node, '15.3.0') ||
versionGteLt(process.versions.node, '14.17.0', '15.0.0');
const tryStatSync = statSupportsThrowIfNoEntry ? tryStatSyncWithoutErrors : tryStatSyncWithErrors;
const statsIfNotFound = new Stats();
function tryStatSyncWithoutErrors(path) {
const stats = statSync(path, { throwIfNoEntry: false });
if(stats != null) return stats;
return statsIfNotFound;
}
function tryStatSyncWithErrors(path) {
try {
return statSync(path);
} catch {
return statsIfNotFound;
}
}
function getPackageConfig(path, specifier, base) {
const existing = packageJSONCache.get(path);
if (existing !== undefined) {
return existing;
}
const source = packageJsonReader.read(path).string;
if (source === undefined) {
const packageConfig = {
pjsonPath: path,
exists: false,
main: undefined,
name: undefined,
type: 'none',
exports: undefined,
imports: undefined,
};
packageJSONCache.set(path, packageConfig);
return packageConfig;
}
let packageJSON;
try {
packageJSON = JSONParse(source);
} catch (error) {
throw new ERR_INVALID_PACKAGE_CONFIG(
path,
(base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier),
error.message
);
}
let { imports, main, name, type } = packageJSON;
const { exports } = packageJSON;
if (typeof imports !== 'object' || imports === null) imports = undefined;
if (typeof main !== 'string') main = undefined;
if (typeof name !== 'string') name = undefined;
// Ignore unknown types for forwards compatibility
if (type !== 'module' && type !== 'commonjs') type = 'none';
const packageConfig = {
pjsonPath: path,
exists: true,
main,
name,
type,
exports,
imports,
};
packageJSONCache.set(path, packageConfig);
return packageConfig;
}
function getPackageScopeConfig(resolved) {
let packageJSONUrl = new URL('./package.json', resolved);
while (true) {
const packageJSONPath = packageJSONUrl.pathname;
if (StringPrototypeEndsWith(packageJSONPath, 'node_modules/package.json'))
break;
const packageConfig = getPackageConfig(fileURLToPath(packageJSONUrl),
resolved);
if (packageConfig.exists) return packageConfig;
const lastPackageJSONUrl = packageJSONUrl;
packageJSONUrl = new URL('../package.json', packageJSONUrl);
// Terminates at root where ../package.json equals ../../package.json
// (can't just check "/package.json" for Windows support).
if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) break;
}
const packageJSONPath = fileURLToPath(packageJSONUrl);
const packageConfig = {
pjsonPath: packageJSONPath,
exists: false,
main: undefined,
name: undefined,
type: 'none',
exports: undefined,
imports: undefined,
};
packageJSONCache.set(packageJSONPath, packageConfig);
return packageConfig;
}
/*
* Legacy CommonJS main resolution:
* 1. let M = pkg_url + (json main field)
* 2. TRY(M, M.js, M.json, M.node)
* 3. TRY(M/index.js, M/index.json, M/index.node)
* 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
* 5. NOT_FOUND
*/
function fileExists(url) {
return tryStatSync(fileURLToPath(url)).isFile();
}
function legacyMainResolve(packageJSONUrl, packageConfig, base) {
let guess;
if (packageConfig.main !== undefined) {
// Note: fs check redundances will be handled by Descriptor cache here.
if(guess = resolveReplacementExtensions(new URL(`./${packageConfig.main}`, packageJSONUrl))) {
return guess;
}
if (fileExists(guess = new URL(`./${packageConfig.main}`,
packageJSONUrl))) {
return guess;
}
for(const extension of legacyMainResolveAddsIfOmitted) {
if (fileExists(guess = new URL(`./${packageConfig.main}${extension}`,
packageJSONUrl))) {
return guess;
}
}
for(const extension of legacyMainResolveAddsIfOmitted) {
if (fileExists(guess = new URL(`./${packageConfig.main}/index${extension}`,
packageJSONUrl))) {
return guess;
}
}
// Fallthrough.
}
for(const extension of legacyMainResolveAddsIfOmitted) {
if (fileExists(guess = new URL(`./index${extension}`, packageJSONUrl))) {
return guess;
}
}
// Not found.
throw new ERR_MODULE_NOT_FOUND(
fileURLToPath(new URL('.', packageJSONUrl)), fileURLToPath(base));
}
/** attempts replacement extensions, then tries exact name, then attempts appending extensions */
function resolveExtensionsWithTryExactName(search) {
const resolvedReplacementExtension = resolveReplacementExtensions(search);
if(resolvedReplacementExtension) return resolvedReplacementExtension;
if (fileExists(search)) return search;
return resolveExtensions(search);
}
// This appends missing extensions
function resolveExtensions(search) {
for (let i = 0; i < esrnExtensions.length; i++) {
const extension = esrnExtensions[i];
const guess = new URL(`${search.pathname}${extension}`, search);
if (fileExists(guess)) return guess;
}
return undefined;
}
/** This replaces JS with TS extensions */
function resolveReplacementExtensions(search) {
const lastDotIndex = search.pathname.lastIndexOf('.');
if(lastDotIndex >= 0) {
const ext = search.pathname.slice(lastDotIndex);
if (ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs') {
const pathnameWithoutExtension = search.pathname.slice(0, lastDotIndex);
const replacementExts =
ext === '.js' ? replacementsForJs
: ext === '.jsx' ? replacementsForJsx
: ext === '.mjs' ? replacementsForMjs
: replacementsForCjs;
const guess = new URL(search.toString());
for (let i = 0; i < replacementExts.length; i++) {
const extension = replacementExts[i];
guess.pathname = `${pathnameWithoutExtension}${extension}`;
if (fileExists(guess)) return guess;
}
}
}
return undefined;
}
function resolveIndex(search) {
return resolveExtensions(new URL('index', search));
}
const encodedSepRegEx = /%2F|%2C/i;
function finalizeResolution(resolved, base) {
if (RegExpPrototypeTest(encodedSepRegEx, resolved.pathname))
throw new ERR_INVALID_MODULE_SPECIFIER(
resolved.pathname, 'must not include encoded "/" or "\\" characters',
fileURLToPath(base));
if (experimentalSpecifierResolution === 'node') {
const path = fileURLToPath(resolved);
let file = resolveExtensionsWithTryExactName(resolved);
if (file !== undefined) return file;
if (!StringPrototypeEndsWith(path, '/')) {
file = resolveIndex(new URL(`${resolved}/`));
if (file !== undefined) return file;
} else {
return resolveIndex(resolved) || resolved;
}
throw new ERR_MODULE_NOT_FOUND(
resolved.pathname, fileURLToPath(base), 'module');
}
const file = resolveReplacementExtensions(resolved) || resolved;
const path = fileURLToPath(file);
const stats = tryStatSync(StringPrototypeEndsWith(path, '/') ?
StringPrototypeSlice(path, -1) : path);
if (stats.isDirectory()) {
const err = new ERR_UNSUPPORTED_DIR_IMPORT(path, fileURLToPath(base));
err.url = String(resolved);
throw err;
} else if (!stats.isFile()) {
throw new ERR_MODULE_NOT_FOUND(
path || resolved.pathname, fileURLToPath(base), 'module');
}
return file;
}
function throwImportNotDefined(specifier, packageJSONUrl, base) {
throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(
specifier, packageJSONUrl && fileURLToPath(new URL('.', packageJSONUrl)),
fileURLToPath(base));
}
function throwExportsNotFound(subpath, packageJSONUrl, base) {
throw new ERR_PACKAGE_PATH_NOT_EXPORTED(
fileURLToPath(new URL('.', packageJSONUrl)), subpath,
base && fileURLToPath(base));
}
function throwInvalidSubpath(subpath, packageJSONUrl, internal, base) {
const reason = `request is not a valid subpath for the "${internal ?
'imports' : 'exports'}" resolution of ${fileURLToPath(packageJSONUrl)}`;
throw new ERR_INVALID_MODULE_SPECIFIER(subpath, reason,
base && fileURLToPath(base));
}
function throwInvalidPackageTarget(
subpath, target, packageJSONUrl, internal, base) {
if (typeof target === 'object' && target !== null) {
target = JSONStringify(target, null, '');
} else {
target = `${target}`;
}
throw new ERR_INVALID_PACKAGE_TARGET(
fileURLToPath(new URL('.', packageJSONUrl)), subpath, target,
internal, base && fileURLToPath(base));
}
const invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/;
const patternRegEx = /\*/g;
function resolvePackageTargetString(
target, subpath, match, packageJSONUrl, base, pattern, internal, conditions) {
if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
if (!StringPrototypeStartsWith(target, './')) {
if (internal && !StringPrototypeStartsWith(target, '../') &&
!StringPrototypeStartsWith(target, '/')) {
let isURL = false;
try {
new URL(target);
isURL = true;
} catch {}
if (!isURL) {
const exportTarget = pattern ?
StringPrototypeReplace(target, patternRegEx, subpath) :
target + subpath;
return packageResolve(exportTarget, packageJSONUrl, conditions);
}
}
throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
}
if (RegExpPrototypeTest(invalidSegmentRegEx, StringPrototypeSlice(target, 2)))
throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
const resolved = new URL(target, packageJSONUrl);
const resolvedPath = resolved.pathname;
const packagePath = new URL('.', packageJSONUrl).pathname;
if (!StringPrototypeStartsWith(resolvedPath, packagePath))
throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
if (subpath === '') return resolved;
if (RegExpPrototypeTest(invalidSegmentRegEx, subpath))
throwInvalidSubpath(match + subpath, packageJSONUrl, internal, base);
if (pattern)
return new URL(StringPrototypeReplace(resolved.href, patternRegEx,
subpath));
return new URL(subpath, resolved);
}
/**
* @param {string} key
* @returns {boolean}
*/
function isArrayIndex(key) {
const keyNum = +key;
if (`${keyNum}` !== key) return false;
return keyNum >= 0 && keyNum < 0xFFFF_FFFF;
}
function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath,
base, pattern, internal, conditions) {
if (typeof target === 'string') {
return resolvePackageTargetString(
target, subpath, packageSubpath, packageJSONUrl, base, pattern, internal,
conditions);
} else if (ArrayIsArray(target)) {
if (target.length === 0)
return null;
let lastException;
for (let i = 0; i < target.length; i++) {
const targetItem = target[i];
let resolved;
try {
resolved = resolvePackageTarget(
packageJSONUrl, targetItem, subpath, packageSubpath, base, pattern,
internal, conditions);
} catch (e) {
lastException = e;
if (e.code === 'ERR_INVALID_PACKAGE_TARGET')
continue;
throw e;
}
if (resolved === undefined)
continue;
if (resolved === null) {
lastException = null;
continue;
}
return resolved;
}
if (lastException === undefined || lastException === null)
return lastException;
throw lastException;
} else if (typeof target === 'object' && target !== null) {
const keys = ObjectGetOwnPropertyNames(target);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (isArrayIndex(key)) {
throw new ERR_INVALID_PACKAGE_CONFIG(
fileURLToPath(packageJSONUrl), base,
'"exports" cannot contain numeric property keys.');
}
}
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === 'default' || conditions.has(key)) {
const conditionalTarget = target[key];
const resolved = resolvePackageTarget(
packageJSONUrl, conditionalTarget, subpath, packageSubpath, base,
pattern, internal, conditions);
if (resolved === undefined)
continue;
return resolved;
}
}
return undefined;
} else if (target === null) {
return null;
}
throwInvalidPackageTarget(packageSubpath, target, packageJSONUrl, internal,
base);
}
function isConditionalExportsMainSugar(exports, packageJSONUrl, base) {
if (typeof exports === 'string' || ArrayIsArray(exports)) return true;
if (typeof exports !== 'object' || exports === null) return false;
const keys = ObjectGetOwnPropertyNames(exports);
let isConditionalSugar = false;
let i = 0;
for (let j = 0; j < keys.length; j++) {
const key = keys[j];
const curIsConditionalSugar = key === '' || key[0] !== '.';
if (i++ === 0) {
isConditionalSugar = curIsConditionalSugar;
} else if (isConditionalSugar !== curIsConditionalSugar) {
throw new ERR_INVALID_PACKAGE_CONFIG(
fileURLToPath(packageJSONUrl), base,
'"exports" cannot contain some keys starting with \'.\' and some not.' +
' The exports object must either be an object of package subpath keys' +
' or an object of main entry condition name keys only.');
}
}
return isConditionalSugar;
}
/**
* @param {URL} packageJSONUrl
* @param {string} packageSubpath
* @param {object} packageConfig
* @param {string} base
* @param {Set<string>} conditions
* @returns {{resolved: URL, exact: boolean}}
*/
function packageExportsResolve(
packageJSONUrl, packageSubpath, packageConfig, base, conditions) {
let exports = packageConfig.exports;
if (isConditionalExportsMainSugar(exports, packageJSONUrl, base))
exports = { '.': exports };
if (ObjectPrototypeHasOwnProperty(exports, packageSubpath)) {
const target = exports[packageSubpath];
const resolved = resolvePackageTarget(
packageJSONUrl, target, '', packageSubpath, base, false, false, conditions
);
if (resolved === null || resolved === undefined)
throwExportsNotFound(packageSubpath, packageJSONUrl, base);
return { resolved, exact: true };
}
let bestMatch = '';
const keys = ObjectGetOwnPropertyNames(exports);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key[key.length - 1] === '*' &&
StringPrototypeStartsWith(packageSubpath,
StringPrototypeSlice(key, 0, -1)) &&
packageSubpath.length >= key.length &&
key.length > bestMatch.length) {
bestMatch = key;
} else if (key[key.length - 1] === '/' &&
StringPrototypeStartsWith(packageSubpath, key) &&
key.length > bestMatch.length) {
bestMatch = key;
}
}
if (bestMatch) {
const target = exports[bestMatch];
const pattern = bestMatch[bestMatch.length - 1] === '*';
const subpath = StringPrototypeSubstr(packageSubpath, bestMatch.length -
(pattern ? 1 : 0));
const resolved = resolvePackageTarget(packageJSONUrl, target, subpath,
bestMatch, base, pattern, false,
conditions);
if (resolved === null || resolved === undefined)
throwExportsNotFound(packageSubpath, packageJSONUrl, base);
if (!pattern)
emitFolderMapDeprecation(bestMatch, packageJSONUrl, true, base);
return { resolved, exact: pattern };
}
throwExportsNotFound(packageSubpath, packageJSONUrl, base);
}
function packageImportsResolve(name, base, conditions) {
if (name === '#' || StringPrototypeStartsWith(name, '#/')) {
const reason = 'is not a valid internal imports specifier name';
throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath(base));
}
let packageJSONUrl;
const packageConfig = getPackageScopeConfig(base);
if (packageConfig.exists) {
packageJSONUrl = pathToFileURL(packageConfig.pjsonPath);
const imports = packageConfig.imports;
if (imports) {
if (ObjectPrototypeHasOwnProperty(imports, name)) {
const resolved = resolvePackageTarget(
packageJSONUrl, imports[name], '', name, base, false, true, conditions
);
if (resolved !== null)
return { resolved, exact: true };
} else {
let bestMatch = '';
const keys = ObjectGetOwnPropertyNames(imports);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key[key.length - 1] === '*' &&
StringPrototypeStartsWith(name,
StringPrototypeSlice(key, 0, -1)) &&
name.length >= key.length &&
key.length > bestMatch.length) {
bestMatch = key;
} else if (key[key.length - 1] === '/' &&
StringPrototypeStartsWith(name, key) &&
key.length > bestMatch.length) {
bestMatch = key;
}
}
if (bestMatch) {
const target = imports[bestMatch];
const pattern = bestMatch[bestMatch.length - 1] === '*';
const subpath = StringPrototypeSubstr(name, bestMatch.length -
(pattern ? 1 : 0));
const resolved = resolvePackageTarget(
packageJSONUrl, target, subpath, bestMatch, base, pattern, true,
conditions);
if (resolved !== null) {
if (!pattern)
emitFolderMapDeprecation(bestMatch, packageJSONUrl, false, base);
return { resolved, exact: pattern };
}
}
}
}
}
throwImportNotDefined(name, packageJSONUrl, base);
}
function getPackageType(url) {
const packageConfig = getPackageScopeConfig(url);
return packageConfig.type;
}
function parsePackageName(specifier, base) {
let separatorIndex = StringPrototypeIndexOf(specifier, '/');
let validPackageName = true;
let isScoped = false;
if (specifier[0] === '@') {
isScoped = true;
if (separatorIndex === -1 || specifier.length === 0) {
validPackageName = false;
} else {
separatorIndex = StringPrototypeIndexOf(
specifier, '/', separatorIndex + 1);
}
}
const packageName = separatorIndex === -1 ?
specifier : StringPrototypeSlice(specifier, 0, separatorIndex);
// Package name cannot have leading . and cannot have percent-encoding or
// separators.
for (let i = 0; i < packageName.length; i++) {
if (packageName[i] === '%' || packageName[i] === '\\') {
validPackageName = false;
break;
}
}
if (!validPackageName) {
throw new ERR_INVALID_MODULE_SPECIFIER(
specifier, 'is not a valid package name', fileURLToPath(base));
}
const packageSubpath = '.' + (separatorIndex === -1 ? '' :
StringPrototypeSlice(specifier, separatorIndex));
return { packageName, packageSubpath, isScoped };
}
/**
* @param {string} specifier
* @param {URL} base
* @param {Set<string>} conditions
* @returns {URL}
*/
function packageResolve(specifier, base, conditions) {
const { packageName, packageSubpath, isScoped } =
parsePackageName(specifier, base);
// ResolveSelf
const packageConfig = getPackageScopeConfig(base);
if (packageConfig.exists) {
const packageJSONUrl = pathToFileURL(packageConfig.pjsonPath);
if (packageConfig.name === packageName &&
packageConfig.exports !== undefined && packageConfig.exports !== null) {
return packageExportsResolve(
packageJSONUrl, packageSubpath, packageConfig, base, conditions
).resolved;
}
}
let packageJSONUrl =
new URL('./node_modules/' + packageName + '/package.json', base);
let packageJSONPath = fileURLToPath(packageJSONUrl);
let lastPath;
do {
const stat = tryStatSync(StringPrototypeSlice(packageJSONPath, 0,
packageJSONPath.length - 13));
if (!stat.isDirectory()) {
lastPath = packageJSONPath;
packageJSONUrl = new URL((isScoped ?
'../../../../node_modules/' : '../../../node_modules/') +
packageName + '/package.json', packageJSONUrl);
packageJSONPath = fileURLToPath(packageJSONUrl);
continue;
}
// Package match.
const packageConfig = getPackageConfig(packageJSONPath, specifier, base);
if (packageConfig.exports !== undefined && packageConfig.exports !== null)
return packageExportsResolve(
packageJSONUrl, packageSubpath, packageConfig, base, conditions
).resolved;
if (packageSubpath === '.')
return legacyMainResolve(packageJSONUrl, packageConfig, base);
return new URL(packageSubpath, packageJSONUrl);
// Cross-platform root check.
} while (packageJSONPath.length !== lastPath.length);
// eslint can't handle the above code.
// eslint-disable-next-line no-unreachable
throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base));
}
function isBareSpecifier(specifier) {
return specifier[0] && specifier[0] !== '/' && specifier[0] !== '.';
}
function isRelativeSpecifier(specifier) {
if (specifier[0] === '.') {
if (specifier.length === 1 || specifier[1] === '/') return true;
if (specifier[1] === '.') {
if (specifier.length === 2 || specifier[2] === '/') return true;
}
}
return false;
}
function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
if (specifier === '') return false;
if (specifier[0] === '/') return true;
return isRelativeSpecifier(specifier);
}
/**
* @param {string} specifier
* @param {URL} base
* @param {Set<string>} conditions
* @returns {URL}
*/
function moduleResolve(specifier, base, conditions) {
// Order swapped from spec for minor perf gain.
// Ok since relative URLs cannot parse as URLs.
let resolved;
if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
resolved = new URL(specifier, base);
} else if (specifier[0] === '#') {
({ resolved } = packageImportsResolve(specifier, base, conditions));
} else {
try {
resolved = new URL(specifier);
} catch {
resolved = packageResolve(specifier, base, conditions);
}
}
return finalizeResolution(resolved, base);
}
/**
* Try to resolve an import as a CommonJS module
* @param {string} specifier
* @param {string} parentURL
* @returns {boolean|string}
*/
function resolveAsCommonJS(specifier, parentURL) {
try {
const parent = fileURLToPath(parentURL);
const tmpModule = new CJSModule(parent, null);
tmpModule.paths = CJSModule._nodeModulePaths(parent);
let found = CJSModule._resolveFilename(specifier, tmpModule, false);
// If it is a relative specifier return the relative path
// to the parent
if (isRelativeSpecifier(specifier)) {
found = relative(parent, found);
// Add '.separator if the path does not start with '..separator'
// This should be a safe assumption because when loading
// esm modules there should be always a file specified so
// there should not be a specifier like '..' or '.'
if (!StringPrototypeStartsWith(found, `..${sep}`)) {
found = `.${sep}${found}`;
}
} else if (isBareSpecifier(specifier)) {
// If it is a bare specifier return the relative path within the
// module
const pkg = StringPrototypeSplit(specifier, '/')[0];
const index = StringPrototypeIndexOf(found, pkg);
if (index !== -1) {
found = StringPrototypeSlice(found, index);
}
}
// Normalize the path separator to give a valid suggestion
// on Windows
if (process.platform === 'win32') {
found = StringPrototypeReplace(found, new RegExp(`\\${sep}`, 'g'), '/');
}
return found;
} catch {
return false;
}
}
function defaultResolve(specifier, context = {}, defaultResolveUnused) {
let { parentURL, conditions } = context;
if (parentURL && policy != null && policy.manifest) {
const redirects = policy.manifest.getDependencyMapper(parentURL);
if (redirects) {
const { resolve, reaction } = redirects;
const destination = resolve(specifier, new SafeSet(conditions));
let missing = true;
if (destination === true) {
missing = false;
} else if (destination) {
const href = destination.href;
return { url: href };
}
if (missing) {
reaction(new ERR_MANIFEST_DEPENDENCY_MISSING(
parentURL,
specifier,
ArrayPrototypeJoin([...conditions], ', '))
);
}
}
}
let parsed;
try {
parsed = new URL(specifier);
if (parsed.protocol === 'data:') {
return {
url: specifier
};
}
} catch {}
if (parsed && parsed.protocol === builtinModuleProtocol)
return { url: specifier };
if (parsed && parsed.protocol !== 'file:' && parsed.protocol !== 'data:')
throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed);
if (NativeModule.canBeRequiredByUsers(specifier)) {
return {
url: builtinModuleProtocol + specifier
};
}
if (parentURL && StringPrototypeStartsWith(parentURL, 'data:')) {
// This is gonna blow up, we want the error
new URL(specifier, parentURL);
}
const isMain = parentURL === undefined;
if (isMain) {
parentURL = pathToFileURL(`${process.cwd()}/`).href;
// This is the initial entry point to the program, and --input-type has
// been passed as an option; but --input-type can only be used with
// --eval, --print or STDIN string input. It is not allowed with file
// input, to avoid user confusion over how expansive the effect of the
// flag should be (i.e. entry point only, package scope surrounding the
// entry point, etc.).
if (typeFlag)
throw new ERR_INPUT_TYPE_NOT_ALLOWED();
}
conditions = getConditionsSet(conditions);
let url;
try {
url = moduleResolve(specifier, parentURL, conditions);
} catch (error) {
// Try to give the user a hint of what would have been the
// resolved CommonJS module
if (error.code === 'ERR_MODULE_NOT_FOUND' ||
error.code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
if (StringPrototypeStartsWith(specifier, 'file://')) {
specifier = fileURLToPath(specifier);
}
const found = resolveAsCommonJS(specifier, parentURL);
if (found) {
// Modify the stack and message string to include the hint
const lines = StringPrototypeSplit(error.stack, '\n');
const hint = `Did you mean to import ${found}?`;
error.stack =
ArrayPrototypeShift(lines) + '\n' +
hint + '\n' +
ArrayPrototypeJoin(lines, '\n');
error.message += `\n${hint}`;
}
}
throw error;
}
if (isMain ? !preserveSymlinksMain : !preserveSymlinks) {
const urlPath = fileURLToPath(url);
const real = realpathSync(urlPath, {
// [internalFS.realpathCacheKey]: realpathCache
});
const old = url;
url = pathToFileURL(
real + (StringPrototypeEndsWith(urlPath, sep) ? '/' : ''));
url.search = old.search;
url.hash = old.hash;
}
return { url: `${url}` };
}
return {
DEFAULT_CONDITIONS,
defaultResolve,
encodedSepRegEx,
getPackageType,
packageExportsResolve,
packageImportsResolve
};
}
module.exports = {
createResolve
};

View File

@ -0,0 +1,44 @@
// copied from https://github.com/nodejs/node/blob/v15.3.0/lib/internal/modules/package_json_reader.js
'use strict';
const { SafeMap } = require('./node-primordials');
const { internalModuleReadJSON } = require('./node-internalBinding-fs');
const { pathToFileURL } = require('url');
const { toNamespacedPath } = require('path');
// const { getOptionValue } = require('./node-options');
const cache = new SafeMap();
let manifest;
/**
* @param {string} jsonPath
* @return {{string: string, containsKeys: boolean}}
*/
function read(jsonPath) {
if (cache.has(jsonPath)) {
return cache.get(jsonPath);
}
const [string, containsKeys] = internalModuleReadJSON(
toNamespacedPath(jsonPath)
);
const result = { string, containsKeys };
if (string !== undefined) {
if (manifest === undefined) {
// manifest = getOptionValue('--experimental-policy') ?
// require('internal/process/policy').manifest :
// null;
// disabled for now. I am not sure if/how we should support this
manifest = null;
}
if (manifest !== null) {
const jsonURL = pathToFileURL(jsonPath);
manifest.assertIntegrity(jsonURL, string);
}
}
cache.set(jsonPath, result);
return result;
}
module.exports = { read };

View File

@ -0,0 +1,254 @@
// copied from https://github.com/nodejs/node/blob/88799930794045795e8abac874730f9eba7e2300/lib/internal/repl/await.js
'use strict';
const {
ArrayFrom,
ArrayPrototypeForEach,
ArrayPrototypeIncludes,
ArrayPrototypeJoin,
ArrayPrototypePop,
ArrayPrototypePush,
FunctionPrototype,
ObjectKeys,
RegExpPrototypeSymbolReplace,
StringPrototypeEndsWith,
StringPrototypeIncludes,
StringPrototypeIndexOf,
StringPrototypeRepeat,
StringPrototypeSplit,
StringPrototypeStartsWith,
SyntaxError,
} = require('./node-primordials');
const parser = require('acorn').Parser;
const walk = require('acorn-walk');
const { Recoverable } = require('repl');
function isTopLevelDeclaration(state) {
return state.ancestors[state.ancestors.length - 2] === state.body;
}
const noop = FunctionPrototype;
const visitorsWithoutAncestors = {
ClassDeclaration(node, state, c) {
if (isTopLevelDeclaration(state)) {
state.prepend(node, `${node.id.name}=`);
ArrayPrototypePush(
state.hoistedDeclarationStatements,
`let ${node.id.name}; `
);
}
walk.base.ClassDeclaration(node, state, c);
},
ForOfStatement(node, state, c) {
if (node.await === true) {
state.containsAwait = true;
}
walk.base.ForOfStatement(node, state, c);
},
FunctionDeclaration(node, state, c) {
state.prepend(node, `${node.id.name}=`);
ArrayPrototypePush(
state.hoistedDeclarationStatements,
`var ${node.id.name}; `
);
},
FunctionExpression: noop,
ArrowFunctionExpression: noop,
MethodDefinition: noop,
AwaitExpression(node, state, c) {
state.containsAwait = true;
walk.base.AwaitExpression(node, state, c);
},
ReturnStatement(node, state, c) {
state.containsReturn = true;
walk.base.ReturnStatement(node, state, c);
},
VariableDeclaration(node, state, c) {
const variableKind = node.kind;
const isIterableForDeclaration = ArrayPrototypeIncludes(
['ForOfStatement', 'ForInStatement'],
state.ancestors[state.ancestors.length - 2].type
);
if (variableKind === 'var' || isTopLevelDeclaration(state)) {
state.replace(
node.start,
node.start + variableKind.length + (isIterableForDeclaration ? 1 : 0),
variableKind === 'var' && isIterableForDeclaration ?
'' :
'void' + (node.declarations.length === 1 ? '' : ' (')
);
if (!isIterableForDeclaration) {
ArrayPrototypeForEach(node.declarations, (decl) => {
state.prepend(decl, '(');
state.append(decl, decl.init ? ')' : '=undefined)');
});
if (node.declarations.length !== 1) {
state.append(node.declarations[node.declarations.length - 1], ')');
}
}
const variableIdentifiersToHoist = [
['var', []],
['let', []],
];
function registerVariableDeclarationIdentifiers(node) {
switch (node.type) {
case 'Identifier':
ArrayPrototypePush(
variableIdentifiersToHoist[variableKind === 'var' ? 0 : 1][1],
node.name
);
break;
case 'ObjectPattern':
ArrayPrototypeForEach(node.properties, (property) => {
registerVariableDeclarationIdentifiers(property.value);
});
break;
case 'ArrayPattern':
ArrayPrototypeForEach(node.elements, (element) => {
registerVariableDeclarationIdentifiers(element);
});
break;
}
}
ArrayPrototypeForEach(node.declarations, (decl) => {
registerVariableDeclarationIdentifiers(decl.id);
});
ArrayPrototypeForEach(
variableIdentifiersToHoist,
({ 0: kind, 1: identifiers }) => {
if (identifiers.length > 0) {
ArrayPrototypePush(
state.hoistedDeclarationStatements,
`${kind} ${ArrayPrototypeJoin(identifiers, ', ')}; `
);
}
}
);
}
walk.base.VariableDeclaration(node, state, c);
}
};
const visitors = {};
for (const nodeType of ObjectKeys(walk.base)) {
const callback = visitorsWithoutAncestors[nodeType] || walk.base[nodeType];
visitors[nodeType] = (node, state, c) => {
const isNew = node !== state.ancestors[state.ancestors.length - 1];
if (isNew) {
ArrayPrototypePush(state.ancestors, node);
}
callback(node, state, c);
if (isNew) {
ArrayPrototypePop(state.ancestors);
}
};
}
function processTopLevelAwait(src) {
const wrapPrefix = '(async () => { ';
const wrapped = `${wrapPrefix}${src} })()`;
const wrappedArray = ArrayFrom(wrapped);
let root;
try {
root = parser.parse(wrapped, { ecmaVersion: 'latest' });
} catch (e) {
if (StringPrototypeStartsWith(e.message, 'Unterminated '))
throw new Recoverable(e);
// If the parse error is before the first "await", then use the execution
// error. Otherwise we must emit this parse error, making it look like a
// proper syntax error.
const awaitPos = StringPrototypeIndexOf(src, 'await');
const errPos = e.pos - wrapPrefix.length;
if (awaitPos > errPos)
return null;
// Convert keyword parse errors on await into their original errors when
// possible.
if (errPos === awaitPos + 6 &&
StringPrototypeIncludes(e.message, 'Expecting Unicode escape sequence'))
return null;
if (errPos === awaitPos + 7 &&
StringPrototypeIncludes(e.message, 'Unexpected token'))
return null;
const line = e.loc.line;
const column = line === 1 ? e.loc.column - wrapPrefix.length : e.loc.column;
let message = '\n' + StringPrototypeSplit(src, '\n')[line - 1] + '\n' +
StringPrototypeRepeat(' ', column) +
'^\n\n' + RegExpPrototypeSymbolReplace(/ \([^)]+\)/, e.message, '');
// V8 unexpected token errors include the token string.
if (StringPrototypeEndsWith(message, 'Unexpected token'))
message += " '" +
// Wrapper end may cause acorn to report error position after the source
((src.length - 1) >= (e.pos - wrapPrefix.length)
? src[e.pos - wrapPrefix.length]
: src[src.length - 1]) +
"'";
// eslint-disable-next-line no-restricted-syntax
throw new SyntaxError(message);
}
const body = root.body[0].expression.callee.body;
const state = {
body,
ancestors: [],
hoistedDeclarationStatements: [],
replace(from, to, str) {
for (let i = from; i < to; i++) {
wrappedArray[i] = '';
}
if (from === to) str += wrappedArray[from];
wrappedArray[from] = str;
},
prepend(node, str) {
wrappedArray[node.start] = str + wrappedArray[node.start];
},
append(node, str) {
wrappedArray[node.end - 1] += str;
},
containsAwait: false,
containsReturn: false
};
walk.recursive(body, state, visitors);
// Do not transform if
// 1. False alarm: there isn't actually an await expression.
// 2. There is a top-level return, which is not allowed.
if (!state.containsAwait || state.containsReturn) {
return null;
}
const last = body.body[body.body.length - 1];
if (last.type === 'ExpressionStatement') {
// For an expression statement of the form
// ( expr ) ;
// ^^^^^^^^^^ // last
// ^^^^ // last.expression
//
// We do not want the left parenthesis before the `return` keyword;
// therefore we prepend the `return (` to `last`.
//
// On the other hand, we do not want the right parenthesis after the
// semicolon. Since there can only be more right parentheses between
// last.expression.end and the semicolon, appending one more to
// last.expression should be fine.
state.prepend(last, 'return (');
state.append(last.expression, ')');
}
return (
ArrayPrototypeJoin(state.hoistedDeclarationStatements, '') +
ArrayPrototypeJoin(wrappedArray, '')
);
}
module.exports = {
processTopLevelAwait
};

View File

@ -0,0 +1,58 @@
const fs = require('fs');
const {versionGteLt} = require('../dist/util');
// In node's core, this is implemented in C
// https://github.com/nodejs/node/blob/v15.3.0/src/node_file.cc#L891-L985
/**
* @param {string} path
* @returns {[] | [string, boolean]}
*/
function internalModuleReadJSON(path) {
let string
try {
string = fs.readFileSync(path, 'utf8')
} catch (e) {
if (e.code === 'ENOENT') return []
throw e
}
// Node's implementation checks for the presence of relevant keys: main, name, type, exports, imports
// Node does this for performance to skip unnecessary parsing.
// This would slow us down and, based on our usage, we can skip it.
const containsKeys = true
return [string, containsKeys]
}
// In node's core, this is implemented in C
// https://github.com/nodejs/node/blob/63e7dc1e5c71b70c80ed9eda230991edb00811e2/src/node_file.cc#L987-L1005
/**
* @param {string} path
* @returns {number} 0 = file, 1 = dir, negative = error
*/
function internalModuleStat(path) {
const stat = fs.statSync(path, { throwIfNoEntry: false });
if(!stat) return -1;
if(stat.isFile()) return 0;
if(stat.isDirectory()) return 1;
}
/**
* @param {string} path
* @returns {number} 0 = file, 1 = dir, negative = error
*/
function internalModuleStatInefficient(path) {
try {
const stat = fs.statSync(path);
if(stat.isFile()) return 0;
if(stat.isDirectory()) return 1;
} catch(e) {
return -e.errno || -1;
}
}
const statSupportsThrowIfNoEntry = versionGteLt(process.versions.node, '15.3.0') ||
versionGteLt(process.versions.node, '14.17.0', '15.0.0');
module.exports = {
internalModuleReadJSON,
internalModuleStat: statSupportsThrowIfNoEntry ? internalModuleStat : internalModuleStatInefficient
};

9
node_modules/ts-node/dist-raw/node-nativemodule.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
// Node imports this from 'internal/bootstrap/loaders'
const Module = require('module');
const NativeModule = {
canBeRequiredByUsers(specifier) {
return Module.builtinModules.includes(specifier)
}
};
exports.NativeModule = NativeModule;

103
node_modules/ts-node/dist-raw/node-options.js generated vendored Normal file
View File

@ -0,0 +1,103 @@
// Replacement for node's internal 'internal/options' module
exports.getOptionValue = getOptionValue;
function getOptionValue(opt) {
parseOptions();
return options[opt];
}
let options;
function parseOptions() {
if (!options) {
options = {
'--preserve-symlinks': false,
'--preserve-symlinks-main': false,
'--input-type': undefined,
'--experimental-specifier-resolution': 'explicit',
'--experimental-policy': undefined,
'--conditions': [],
'--pending-deprecation': false,
...parseArgv(getNodeOptionsEnvArgv()),
...parseArgv(process.execArgv),
...getOptionValuesFromOtherEnvVars()
}
}
}
function parseArgv(argv) {
return require('arg')({
'--preserve-symlinks': Boolean,
'--preserve-symlinks-main': Boolean,
'--input-type': String,
'--experimental-specifier-resolution': String,
// Legacy alias for node versions prior to 12.16
'--es-module-specifier-resolution': '--experimental-specifier-resolution',
'--experimental-policy': String,
'--conditions': [String],
'--pending-deprecation': Boolean,
'--experimental-json-modules': Boolean,
'--experimental-wasm-modules': Boolean,
}, {
argv,
permissive: true
});
}
function getNodeOptionsEnvArgv() {
const errors = [];
const envArgv = ParseNodeOptionsEnvVar(process.env.NODE_OPTIONS || '', errors);
if (errors.length !== 0) {
// TODO: handle errors somehow
}
return envArgv;
}
// Direct JS port of C implementation: https://github.com/nodejs/node/blob/67ba825037b4082d5d16f922fb9ce54516b4a869/src/node_options.cc#L1024-L1063
function ParseNodeOptionsEnvVar(node_options, errors) {
const env_argv = [];
let is_in_string = false;
let will_start_new_arg = true;
for (let index = 0; index < node_options.length; ++index) {
let c = node_options[index];
// Backslashes escape the following character
if (c === '\\' && is_in_string) {
if (index + 1 === node_options.length) {
errors.push("invalid value for NODE_OPTIONS " +
"(invalid escape)\n");
return env_argv;
} else {
c = node_options[++index];
}
} else if (c === ' ' && !is_in_string) {
will_start_new_arg = true;
continue;
} else if (c === '"') {
is_in_string = !is_in_string;
continue;
}
if (will_start_new_arg) {
env_argv.push(c);
will_start_new_arg = false;
} else {
env_argv[env_argv.length - 1] += c;
}
}
if (is_in_string) {
errors.push("invalid value for NODE_OPTIONS " +
"(unterminated string)\n");
}
return env_argv;
}
// Get option values that can be specified via env vars besides NODE_OPTIONS
function getOptionValuesFromOtherEnvVars() {
const options = {};
if(process.env.NODE_PENDING_DEPRECATION === '1') {
options['--pending-deprecation'] = true;
}
return options;
}

37
node_modules/ts-node/dist-raw/node-primordials.js generated vendored Normal file
View File

@ -0,0 +1,37 @@
module.exports = {
ArrayFrom: Array.from,
ArrayIsArray: Array.isArray,
ArrayPrototypeShift: (obj) => Array.prototype.shift.call(obj),
ArrayPrototypeForEach: (arr, ...rest) => Array.prototype.forEach.apply(arr, rest),
ArrayPrototypeIncludes: (arr, ...rest) => Array.prototype.includes.apply(arr, rest),
ArrayPrototypeJoin: (arr, ...rest) => Array.prototype.join.apply(arr, rest),
ArrayPrototypePop: (arr, ...rest) => Array.prototype.pop.apply(arr, rest),
ArrayPrototypePush: (arr, ...rest) => Array.prototype.push.apply(arr, rest),
FunctionPrototype: Function.prototype,
JSONParse: JSON.parse,
JSONStringify: JSON.stringify,
ObjectFreeze: Object.freeze,
ObjectKeys: Object.keys,
ObjectGetOwnPropertyNames: Object.getOwnPropertyNames,
ObjectDefineProperty: Object.defineProperty,
ObjectPrototypeHasOwnProperty: (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop),
RegExpPrototypeExec: (obj, string) => RegExp.prototype.exec.call(obj, string),
RegExpPrototypeTest: (obj, string) => RegExp.prototype.test.call(obj, string),
RegExpPrototypeSymbolReplace: (obj, ...rest) => RegExp.prototype[Symbol.replace].apply(obj, rest),
SafeMap: Map,
SafeSet: Set,
SafeWeakMap: WeakMap,
StringPrototypeEndsWith: (str, ...rest) => String.prototype.endsWith.apply(str, rest),
StringPrototypeIncludes: (str, ...rest) => String.prototype.includes.apply(str, rest),
StringPrototypeLastIndexOf: (str, ...rest) => String.prototype.lastIndexOf.apply(str, rest),
StringPrototypeIndexOf: (str, ...rest) => String.prototype.indexOf.apply(str, rest),
StringPrototypeRepeat: (str, ...rest) => String.prototype.repeat.apply(str, rest),
StringPrototypeReplace: (str, ...rest) => String.prototype.replace.apply(str, rest),
StringPrototypeSlice: (str, ...rest) => String.prototype.slice.apply(str, rest),
StringPrototypeSplit: (str, ...rest) => String.prototype.split.apply(str, rest),
StringPrototypeStartsWith: (str, ...rest) => String.prototype.startsWith.apply(str, rest),
StringPrototypeSubstr: (str, ...rest) => String.prototype.substr.apply(str, rest),
StringPrototypeCharCodeAt: (str, ...rest) => String.prototype.charCodeAt.apply(str, rest),
StringPrototypeMatch: (str, ...rest) => String.prototype.match.apply(str, rest),
SyntaxError: SyntaxError
};

9
node_modules/ts-node/dist-raw/runmain-hack.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
const {pathToFileURL} = require('url');
// Hack to avoid Module.runMain on node 18.6.0
// Keeping it simple for now, isolated in this file.
// Could theoretically probe `getFormat` impl to determine if `import()` or `Module._load()` is best
// Note that I attempted a try-catch around `Module._load`, but it poisons some sort of cache such that subsequent `import()` is impossible.
exports.run = function(entryPointPath) {
import(pathToFileURL(entryPointPath));
}