id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
500 | function generateTarget(
project: Project,
p: FsProject,
options: GenerateTargetOptions
) {
const {
inSrc,
inOut,
srcExt,
targetPackageStyle,
packageTypeModule,
isIndex,
} = options;
const outExt = srcExt.replace('ts', 'js').replace('x', '');
let targetIdentifier = `target-${targetSeq()}-${
inOut && inSrc ? 'inboth' : inOut ? 'onlyout' : 'onlysrc'
}-${srcExt}`;
if (targetPackageStyle)
targetIdentifier = `${targetIdentifier}-${targetPackageStyle}-${
packageTypeModule ? 'module' : 'commonjs'
}`;
let prefix = targetPackageStyle ? `node_modules/${targetIdentifier}/` : '';
let suffix =
targetPackageStyle === 'empty-manifest'
? 'index'
: targetPackageStyle
? 'target'
: targetIdentifier;
if (isIndex) suffix += '-dir/index';
const srcDirInfix = targetPackageStyle === 'empty-manifest' ? '' : 'src/';
const outDirInfix = targetPackageStyle === 'empty-manifest' ? '' : 'out/';
const srcName = `${prefix}${srcDirInfix}${suffix}.${srcExt}`;
const srcDirOutExtName = `${prefix}${srcDirInfix}${suffix}.${outExt}`;
const outName = `${prefix}${outDirInfix}${suffix}.${outExt}`;
const selfImporterCjsName = `${prefix}self-import-cjs.cjs`;
const selfImporterMjsName = `${prefix}self-import-mjs.mjs`;
const target: Target = {
targetIdentifier,
srcName,
outName,
srcExt,
outExt,
inSrc,
inOut,
isNamedFile: !isIndex && !targetPackageStyle,
isIndex,
isPackage: !!targetPackageStyle,
packageStyle: targetPackageStyle,
typeModule: packageTypeModule,
};
const { isMjs: targetIsMjs } = fileInfo(
'.' + srcExt,
packageTypeModule,
project.allowJs
);
function targetContent(loc: string) {
let content = '';
if (targetIsMjs) {
content += String.raw`
const {fileURLToPath} = await import('url');
const filenameNative = fileURLToPath(import.meta.url);
export const directory = filenameNative.replace(/.*[\\\/](.*?)[\\\/]/, '$1');
export const filename = filenameNative.replace(/.*[\\\/]/, '');
export const targetIdentifier = '${targetIdentifier}';
export const ext = filenameNative.replace(/.*\./, '');
export const loc = '${loc}';
`;
} else {
content += String.raw`
const filenameNative = __filename;
exports.filename = filenameNative.replace(/.*[\\\/]/, '');
exports.directory = filenameNative.replace(/.*[\\\/](.*?)[\\\/].*/, '$1');
exports.targetIdentifier = '${targetIdentifier}';
exports.ext = filenameNative.replace(/.*\./, '');
exports.loc = '${loc}';
`;
}
return content;
}
if (inOut) {
p.addFile(outName, targetContent('out'));
// TODO so we can test multiple file extensions in a single directory, preferTsExt
p.addFile(srcDirOutExtName, targetContent('out'));
}
if (inSrc) {
p.addFile(srcName, targetContent('src'));
}
if (targetPackageStyle) {
const selfImporterIsCompiled = project.allowJs;
const cjsSelfImporterMustUseDynamicImportHack =
!project.useTsNodeNext && selfImporterIsCompiled && targetIsMjs;
p.addFile(
selfImporterCjsName,
targetIsMjs
? cjsSelfImporterMustUseDynamicImportHack
? `${declareDynamicImportFunction}\nmodule.exports = dynamicImport('${targetIdentifier}');`
: `module.exports = import("${targetIdentifier}");`
: `module.exports = require("${targetIdentifier}");`
);
p.addFile(
selfImporterMjsName,
`
export * from "${targetIdentifier}";
`
);
function writePackageJson(obj: any) {
p.addJsonFile(`${prefix}/package.json`, {
name: targetIdentifier,
type: packageTypeModule ? 'module' : undefined,
...obj,
});
}
switch (targetPackageStyle) {
case 'empty-manifest':
writePackageJson({});
break;
case 'exports-src-with-extension':
writePackageJson({
exports: {
'.': `./src/${suffix}.${srcExt}`,
},
});
break;
case 'exports-src-with-out-extension':
writePackageJson({
exports: {
'.': `./src/${suffix}.${outExt}`,
},
});
break;
case 'exports-out-with-extension':
writePackageJson({
exports: {
'.': `./out/${suffix}.${outExt}`,
},
});
break;
case 'main-src-extensionless':
writePackageJson({
main: `src/${suffix}`,
});
break;
case 'main-out-extensionless':
writePackageJson({
main: `out/${suffix}`,
});
break;
case 'main-src-with-extension':
writePackageJson({
main: `src/${suffix}.${srcExt}`,
});
break;
case 'main-src-with-out-extension':
writePackageJson({
main: `src/${suffix}.${outExt}`,
});
break;
case 'main-out-with-extension':
writePackageJson({
main: `src/${suffix}.${outExt}`,
});
break;
default:
const _assert: never = targetPackageStyle;
}
}
return target;
} | interface Project {
identifier: string;
allowJs: boolean;
preferSrc: boolean;
typeModule: boolean;
/** Use TS's new module: `nodenext` option */
useTsNodeNext: boolean;
experimentalSpecifierResolutionNode: boolean;
skipIgnore: boolean;
} |
501 | function generateTarget(
project: Project,
p: FsProject,
options: GenerateTargetOptions
) {
const {
inSrc,
inOut,
srcExt,
targetPackageStyle,
packageTypeModule,
isIndex,
} = options;
const outExt = srcExt.replace('ts', 'js').replace('x', '');
let targetIdentifier = `target-${targetSeq()}-${
inOut && inSrc ? 'inboth' : inOut ? 'onlyout' : 'onlysrc'
}-${srcExt}`;
if (targetPackageStyle)
targetIdentifier = `${targetIdentifier}-${targetPackageStyle}-${
packageTypeModule ? 'module' : 'commonjs'
}`;
let prefix = targetPackageStyle ? `node_modules/${targetIdentifier}/` : '';
let suffix =
targetPackageStyle === 'empty-manifest'
? 'index'
: targetPackageStyle
? 'target'
: targetIdentifier;
if (isIndex) suffix += '-dir/index';
const srcDirInfix = targetPackageStyle === 'empty-manifest' ? '' : 'src/';
const outDirInfix = targetPackageStyle === 'empty-manifest' ? '' : 'out/';
const srcName = `${prefix}${srcDirInfix}${suffix}.${srcExt}`;
const srcDirOutExtName = `${prefix}${srcDirInfix}${suffix}.${outExt}`;
const outName = `${prefix}${outDirInfix}${suffix}.${outExt}`;
const selfImporterCjsName = `${prefix}self-import-cjs.cjs`;
const selfImporterMjsName = `${prefix}self-import-mjs.mjs`;
const target: Target = {
targetIdentifier,
srcName,
outName,
srcExt,
outExt,
inSrc,
inOut,
isNamedFile: !isIndex && !targetPackageStyle,
isIndex,
isPackage: !!targetPackageStyle,
packageStyle: targetPackageStyle,
typeModule: packageTypeModule,
};
const { isMjs: targetIsMjs } = fileInfo(
'.' + srcExt,
packageTypeModule,
project.allowJs
);
function targetContent(loc: string) {
let content = '';
if (targetIsMjs) {
content += String.raw`
const {fileURLToPath} = await import('url');
const filenameNative = fileURLToPath(import.meta.url);
export const directory = filenameNative.replace(/.*[\\\/](.*?)[\\\/]/, '$1');
export const filename = filenameNative.replace(/.*[\\\/]/, '');
export const targetIdentifier = '${targetIdentifier}';
export const ext = filenameNative.replace(/.*\./, '');
export const loc = '${loc}';
`;
} else {
content += String.raw`
const filenameNative = __filename;
exports.filename = filenameNative.replace(/.*[\\\/]/, '');
exports.directory = filenameNative.replace(/.*[\\\/](.*?)[\\\/].*/, '$1');
exports.targetIdentifier = '${targetIdentifier}';
exports.ext = filenameNative.replace(/.*\./, '');
exports.loc = '${loc}';
`;
}
return content;
}
if (inOut) {
p.addFile(outName, targetContent('out'));
// TODO so we can test multiple file extensions in a single directory, preferTsExt
p.addFile(srcDirOutExtName, targetContent('out'));
}
if (inSrc) {
p.addFile(srcName, targetContent('src'));
}
if (targetPackageStyle) {
const selfImporterIsCompiled = project.allowJs;
const cjsSelfImporterMustUseDynamicImportHack =
!project.useTsNodeNext && selfImporterIsCompiled && targetIsMjs;
p.addFile(
selfImporterCjsName,
targetIsMjs
? cjsSelfImporterMustUseDynamicImportHack
? `${declareDynamicImportFunction}\nmodule.exports = dynamicImport('${targetIdentifier}');`
: `module.exports = import("${targetIdentifier}");`
: `module.exports = require("${targetIdentifier}");`
);
p.addFile(
selfImporterMjsName,
`
export * from "${targetIdentifier}";
`
);
function writePackageJson(obj: any) {
p.addJsonFile(`${prefix}/package.json`, {
name: targetIdentifier,
type: packageTypeModule ? 'module' : undefined,
...obj,
});
}
switch (targetPackageStyle) {
case 'empty-manifest':
writePackageJson({});
break;
case 'exports-src-with-extension':
writePackageJson({
exports: {
'.': `./src/${suffix}.${srcExt}`,
},
});
break;
case 'exports-src-with-out-extension':
writePackageJson({
exports: {
'.': `./src/${suffix}.${outExt}`,
},
});
break;
case 'exports-out-with-extension':
writePackageJson({
exports: {
'.': `./out/${suffix}.${outExt}`,
},
});
break;
case 'main-src-extensionless':
writePackageJson({
main: `src/${suffix}`,
});
break;
case 'main-out-extensionless':
writePackageJson({
main: `out/${suffix}`,
});
break;
case 'main-src-with-extension':
writePackageJson({
main: `src/${suffix}.${srcExt}`,
});
break;
case 'main-src-with-out-extension':
writePackageJson({
main: `src/${suffix}.${outExt}`,
});
break;
case 'main-out-with-extension':
writePackageJson({
main: `src/${suffix}.${outExt}`,
});
break;
default:
const _assert: never = targetPackageStyle;
}
}
return target;
} | type Project = ReturnType<typeof project>; |
502 | function generateEntrypoints(
project: Project,
p: FsProject,
targets: Target[]
) {
/** Array of entrypoint files to be imported during the test */
let entrypoints: string[] = [];
for (const entrypointExt of ['cjs', 'mjs'] as const) {
// TODO consider removing this logic; deferring to conditionals in the generateEntrypoint which emit meaningful comments
const withExtPermutations =
entrypointExt == 'mjs' &&
project.experimentalSpecifierResolutionNode === false
? [true]
: [false, true];
for (const withExt of withExtPermutations) {
// Location of the entrypoint
for (const entrypointLocation of ['src', 'out'] as const) {
// Target of the entrypoint's import statements
for (const entrypointTargetting of ['src', 'out'] as const) {
// TODO re-enable when we have out <-> src mapping
if (entrypointLocation !== 'src') continue;
if (entrypointTargetting !== 'src') continue;
entrypoints.push(
generateEntrypoint(project, p, targets, {
entrypointExt,
withExt,
entrypointLocation,
entrypointTargetting,
})
);
}
}
}
}
return entrypoints;
} | interface Project {
identifier: string;
allowJs: boolean;
preferSrc: boolean;
typeModule: boolean;
/** Use TS's new module: `nodenext` option */
useTsNodeNext: boolean;
experimentalSpecifierResolutionNode: boolean;
skipIgnore: boolean;
} |
503 | function generateEntrypoints(
project: Project,
p: FsProject,
targets: Target[]
) {
/** Array of entrypoint files to be imported during the test */
let entrypoints: string[] = [];
for (const entrypointExt of ['cjs', 'mjs'] as const) {
// TODO consider removing this logic; deferring to conditionals in the generateEntrypoint which emit meaningful comments
const withExtPermutations =
entrypointExt == 'mjs' &&
project.experimentalSpecifierResolutionNode === false
? [true]
: [false, true];
for (const withExt of withExtPermutations) {
// Location of the entrypoint
for (const entrypointLocation of ['src', 'out'] as const) {
// Target of the entrypoint's import statements
for (const entrypointTargetting of ['src', 'out'] as const) {
// TODO re-enable when we have out <-> src mapping
if (entrypointLocation !== 'src') continue;
if (entrypointTargetting !== 'src') continue;
entrypoints.push(
generateEntrypoint(project, p, targets, {
entrypointExt,
withExt,
entrypointLocation,
entrypointTargetting,
})
);
}
}
}
}
return entrypoints;
} | type Project = ReturnType<typeof project>; |
504 | function generateEntrypoint(
project: Project,
p: FsProject,
targets: Target[],
opts: EntrypointPermutation
) {
const { entrypointExt, withExt, entrypointLocation, entrypointTargetting } =
opts;
const entrypointFilename = `entrypoint-${entrypointSeq()}-${entrypointLocation}-to-${entrypointTargetting}${
withExt ? '-withext' : ''
}.${entrypointExt}`;
const { isMjs: entrypointIsMjs, isCompiled: entrypointIsCompiled } = fileInfo(
entrypointFilename,
project.typeModule,
project.allowJs
);
let entrypointContent = 'let mod;\n';
entrypointContent += 'let testsRun = 0;\n';
if (entrypointIsMjs) {
entrypointContent += `import assert from 'assert';\n`;
} else {
entrypointContent += `const assert = require('assert');\n`;
entrypointContent += `${declareDynamicImportFunction}\n`;
}
entrypointContent += `async function main() {\n`;
for (const target of targets) {
// TODO re-enable these when we have outDir <-> rootDir mapping
if (target.srcName.includes('onlyout') && entrypointTargetting === 'src')
continue;
if (target.srcName.includes('onlysrc') && entrypointTargetting === 'out')
continue;
const {
ext: targetSrcExt,
isMjs: targetIsMjs,
isCompiled: targetIsCompiled,
} = fileInfo(target.srcName, target.typeModule, project.allowJs);
let targetExtPermutations = [''];
if (!target.isPackage) {
if (entrypointTargetting === 'out' && target.outExt !== target.srcExt) {
// TODO re-enable when we have out <-> src mapping
targetExtPermutations = [target.outExt];
} else if (target.srcExt !== target.outExt) {
targetExtPermutations = [target.srcExt, target.outExt];
} else {
targetExtPermutations = [target.srcExt];
}
}
const externalPackageSelfImportPermutations = target.isPackage
? [false, true]
: [false];
for (const targetExt of targetExtPermutations) {
for (const externalPackageSelfImport of externalPackageSelfImportPermutations) {
entrypointContent += `\n// ${target.targetIdentifier}`;
if (target.isPackage) {
entrypointContent += ` node_modules package`;
if (externalPackageSelfImport) {
entrypointContent += ` self-import`;
}
} else {
entrypointContent += `.${targetExt}`;
}
entrypointContent += '\n';
// should specifier be relative or absolute?
let specifier: string;
if (externalPackageSelfImport) {
specifier = `../node_modules/${target.targetIdentifier}/self-import-${entrypointExt}.${entrypointExt}`;
} else if (target.isPackage) {
specifier = target.targetIdentifier;
} else {
if (entrypointTargetting === entrypointLocation) specifier = './';
else specifier = `../${entrypointTargetting}/`;
specifier += target.targetIdentifier;
if (target.isIndex) specifier += '-dir';
if (!target.isIndex && withExt) specifier += '.' + targetExt;
}
//#region SKIPPING
if (target.isNamedFile && !withExt) {
// Do not try to import cjs/cts without extension; node always requires these extensions
if (target.outExt === 'cjs') {
entrypointContent += `// skipping ${specifier} because we cannot omit extension from cjs / cts files; node always requires them\n`;
continue;
}
// Do not try to import mjs/mts unless experimental-specifier-resolution is turned on
if (
target.outExt === 'mjs' &&
!project.experimentalSpecifierResolutionNode
) {
entrypointContent += `// skipping ${specifier} because we cannot omit extension from mjs/mts unless experimental-specifier-resolution=node\n`;
continue;
}
// Do not try to import anything extensionless via ESM loader unless experimental-specifier-resolution is turned on
if (
(targetIsMjs || entrypointIsMjs) &&
!project.experimentalSpecifierResolutionNode
) {
entrypointContent += `// skipping ${specifier} because we cannot omit extension via esm loader unless experimental-specifier-resolution=node\n`;
continue;
}
}
if (
target.isPackage &&
isOneOf(target.packageStyle, [
'empty-manifest',
'main-out-extensionless',
'main-src-extensionless',
]) &&
isOneOf(target.outExt, ['cjs', 'mjs'])
) {
entrypointContent += `// skipping ${specifier} because it points to a node_modules package that tries to omit file extension, and node does not allow omitting cjs/mjs extension\n`;
continue;
}
// Do not try to import a transpiled file if compiler options disagree with node's extension-based classification
if (!project.useTsNodeNext && targetIsCompiled) {
if (targetIsMjs && !project.typeModule) {
entrypointContent += `// skipping ${specifier} because it is compiled and compiler options disagree with node's module classification: extension=${targetSrcExt}, tsconfig module=commonjs\n`;
continue;
}
if (!targetIsMjs && project.typeModule) {
entrypointContent += `// skipping ${specifier} because it is compiled and compiler options disagree with node's module classification: extension=${targetSrcExt}, tsconfig module=esnext\n`;
continue;
}
}
// Do not try to import index from a directory if is forbidden by node's ESM resolver
if (target.isIndex) {
if (
(targetIsMjs || entrypointIsMjs) &&
!project.experimentalSpecifierResolutionNode
) {
entrypointContent += `// skipping ${specifier} because esm loader does not allow directory ./index imports unless experimental-specifier-resolution=node\n`;
continue;
}
if (target.outExt === 'cjs') {
entrypointContent += `// skipping ${specifier} because it relies on node automatically resolving a directory to index.cjs/cts , but node does not support those extensions for index.* files, only .js (and equivalents), .node, .json\n`;
continue;
}
}
//#endregion
// NOTE: if you try to explicitly import foo.ts, we will load foo.ts, EVEN IF you have `preferTsExts` off
const assertIsSrcOrOut = !target.inSrc
? 'out'
: !target.inOut
? 'src'
: project.preferSrc ||
(!target.isIndex && targetExt === target.srcExt && withExt) ||
target.srcExt === target.outExt || // <-- TODO re-enable when we have src <-> out mapping
(target.isPackage &&
isOneOf(target.packageStyle, [
'main-src-with-extension',
'exports-src-with-extension',
]))
? 'src'
: 'out';
const assertHasExt =
assertIsSrcOrOut === 'src' ? target.srcExt : target.outExt;
// If entrypoint is compiled as CJS, and *not* with TS's nodenext, then TS transforms `import` into `require`,
// so we must hack around the compiler to get a true `import`.
const entrypointMustUseDynamicImportHack =
!project.useTsNodeNext &&
entrypointIsCompiled &&
!entrypointIsMjs &&
!externalPackageSelfImport;
entrypointContent +=
entrypointExt === 'cjs' && (externalPackageSelfImport || !targetIsMjs)
? ` mod = await require('${specifier}');\n`
: entrypointMustUseDynamicImportHack
? ` mod = await dynamicImport('${specifier}');\n`
: ` mod = await import('${specifier}');\n`;
entrypointContent += ` assert.equal(mod.loc, '${assertIsSrcOrOut}');\n`;
entrypointContent += ` assert.equal(mod.targetIdentifier, '${target.targetIdentifier}');\n`;
entrypointContent += ` assert.equal(mod.ext, '${assertHasExt}');\n`;
entrypointContent += ` testsRun++;\n`;
}
}
}
entrypointContent += `}\n`;
entrypointContent += `const result = main().then(() => {return testsRun});\n`;
entrypointContent += `result.mark = 'marked';\n`;
if (entrypointIsMjs) {
entrypointContent += `export {result};\n`;
} else {
entrypointContent += `exports.result = result;\n`;
}
p.dir(entrypointLocation).addFile(entrypointFilename, entrypointContent);
return entrypointLocation + '/' + entrypointFilename;
} | interface Project {
identifier: string;
allowJs: boolean;
preferSrc: boolean;
typeModule: boolean;
/** Use TS's new module: `nodenext` option */
useTsNodeNext: boolean;
experimentalSpecifierResolutionNode: boolean;
skipIgnore: boolean;
} |
505 | function generateEntrypoint(
project: Project,
p: FsProject,
targets: Target[],
opts: EntrypointPermutation
) {
const { entrypointExt, withExt, entrypointLocation, entrypointTargetting } =
opts;
const entrypointFilename = `entrypoint-${entrypointSeq()}-${entrypointLocation}-to-${entrypointTargetting}${
withExt ? '-withext' : ''
}.${entrypointExt}`;
const { isMjs: entrypointIsMjs, isCompiled: entrypointIsCompiled } = fileInfo(
entrypointFilename,
project.typeModule,
project.allowJs
);
let entrypointContent = 'let mod;\n';
entrypointContent += 'let testsRun = 0;\n';
if (entrypointIsMjs) {
entrypointContent += `import assert from 'assert';\n`;
} else {
entrypointContent += `const assert = require('assert');\n`;
entrypointContent += `${declareDynamicImportFunction}\n`;
}
entrypointContent += `async function main() {\n`;
for (const target of targets) {
// TODO re-enable these when we have outDir <-> rootDir mapping
if (target.srcName.includes('onlyout') && entrypointTargetting === 'src')
continue;
if (target.srcName.includes('onlysrc') && entrypointTargetting === 'out')
continue;
const {
ext: targetSrcExt,
isMjs: targetIsMjs,
isCompiled: targetIsCompiled,
} = fileInfo(target.srcName, target.typeModule, project.allowJs);
let targetExtPermutations = [''];
if (!target.isPackage) {
if (entrypointTargetting === 'out' && target.outExt !== target.srcExt) {
// TODO re-enable when we have out <-> src mapping
targetExtPermutations = [target.outExt];
} else if (target.srcExt !== target.outExt) {
targetExtPermutations = [target.srcExt, target.outExt];
} else {
targetExtPermutations = [target.srcExt];
}
}
const externalPackageSelfImportPermutations = target.isPackage
? [false, true]
: [false];
for (const targetExt of targetExtPermutations) {
for (const externalPackageSelfImport of externalPackageSelfImportPermutations) {
entrypointContent += `\n// ${target.targetIdentifier}`;
if (target.isPackage) {
entrypointContent += ` node_modules package`;
if (externalPackageSelfImport) {
entrypointContent += ` self-import`;
}
} else {
entrypointContent += `.${targetExt}`;
}
entrypointContent += '\n';
// should specifier be relative or absolute?
let specifier: string;
if (externalPackageSelfImport) {
specifier = `../node_modules/${target.targetIdentifier}/self-import-${entrypointExt}.${entrypointExt}`;
} else if (target.isPackage) {
specifier = target.targetIdentifier;
} else {
if (entrypointTargetting === entrypointLocation) specifier = './';
else specifier = `../${entrypointTargetting}/`;
specifier += target.targetIdentifier;
if (target.isIndex) specifier += '-dir';
if (!target.isIndex && withExt) specifier += '.' + targetExt;
}
//#region SKIPPING
if (target.isNamedFile && !withExt) {
// Do not try to import cjs/cts without extension; node always requires these extensions
if (target.outExt === 'cjs') {
entrypointContent += `// skipping ${specifier} because we cannot omit extension from cjs / cts files; node always requires them\n`;
continue;
}
// Do not try to import mjs/mts unless experimental-specifier-resolution is turned on
if (
target.outExt === 'mjs' &&
!project.experimentalSpecifierResolutionNode
) {
entrypointContent += `// skipping ${specifier} because we cannot omit extension from mjs/mts unless experimental-specifier-resolution=node\n`;
continue;
}
// Do not try to import anything extensionless via ESM loader unless experimental-specifier-resolution is turned on
if (
(targetIsMjs || entrypointIsMjs) &&
!project.experimentalSpecifierResolutionNode
) {
entrypointContent += `// skipping ${specifier} because we cannot omit extension via esm loader unless experimental-specifier-resolution=node\n`;
continue;
}
}
if (
target.isPackage &&
isOneOf(target.packageStyle, [
'empty-manifest',
'main-out-extensionless',
'main-src-extensionless',
]) &&
isOneOf(target.outExt, ['cjs', 'mjs'])
) {
entrypointContent += `// skipping ${specifier} because it points to a node_modules package that tries to omit file extension, and node does not allow omitting cjs/mjs extension\n`;
continue;
}
// Do not try to import a transpiled file if compiler options disagree with node's extension-based classification
if (!project.useTsNodeNext && targetIsCompiled) {
if (targetIsMjs && !project.typeModule) {
entrypointContent += `// skipping ${specifier} because it is compiled and compiler options disagree with node's module classification: extension=${targetSrcExt}, tsconfig module=commonjs\n`;
continue;
}
if (!targetIsMjs && project.typeModule) {
entrypointContent += `// skipping ${specifier} because it is compiled and compiler options disagree with node's module classification: extension=${targetSrcExt}, tsconfig module=esnext\n`;
continue;
}
}
// Do not try to import index from a directory if is forbidden by node's ESM resolver
if (target.isIndex) {
if (
(targetIsMjs || entrypointIsMjs) &&
!project.experimentalSpecifierResolutionNode
) {
entrypointContent += `// skipping ${specifier} because esm loader does not allow directory ./index imports unless experimental-specifier-resolution=node\n`;
continue;
}
if (target.outExt === 'cjs') {
entrypointContent += `// skipping ${specifier} because it relies on node automatically resolving a directory to index.cjs/cts , but node does not support those extensions for index.* files, only .js (and equivalents), .node, .json\n`;
continue;
}
}
//#endregion
// NOTE: if you try to explicitly import foo.ts, we will load foo.ts, EVEN IF you have `preferTsExts` off
const assertIsSrcOrOut = !target.inSrc
? 'out'
: !target.inOut
? 'src'
: project.preferSrc ||
(!target.isIndex && targetExt === target.srcExt && withExt) ||
target.srcExt === target.outExt || // <-- TODO re-enable when we have src <-> out mapping
(target.isPackage &&
isOneOf(target.packageStyle, [
'main-src-with-extension',
'exports-src-with-extension',
]))
? 'src'
: 'out';
const assertHasExt =
assertIsSrcOrOut === 'src' ? target.srcExt : target.outExt;
// If entrypoint is compiled as CJS, and *not* with TS's nodenext, then TS transforms `import` into `require`,
// so we must hack around the compiler to get a true `import`.
const entrypointMustUseDynamicImportHack =
!project.useTsNodeNext &&
entrypointIsCompiled &&
!entrypointIsMjs &&
!externalPackageSelfImport;
entrypointContent +=
entrypointExt === 'cjs' && (externalPackageSelfImport || !targetIsMjs)
? ` mod = await require('${specifier}');\n`
: entrypointMustUseDynamicImportHack
? ` mod = await dynamicImport('${specifier}');\n`
: ` mod = await import('${specifier}');\n`;
entrypointContent += ` assert.equal(mod.loc, '${assertIsSrcOrOut}');\n`;
entrypointContent += ` assert.equal(mod.targetIdentifier, '${target.targetIdentifier}');\n`;
entrypointContent += ` assert.equal(mod.ext, '${assertHasExt}');\n`;
entrypointContent += ` testsRun++;\n`;
}
}
}
entrypointContent += `}\n`;
entrypointContent += `const result = main().then(() => {return testsRun});\n`;
entrypointContent += `result.mark = 'marked';\n`;
if (entrypointIsMjs) {
entrypointContent += `export {result};\n`;
} else {
entrypointContent += `exports.result = result;\n`;
}
p.dir(entrypointLocation).addFile(entrypointFilename, entrypointContent);
return entrypointLocation + '/' + entrypointFilename;
} | type Project = ReturnType<typeof project>; |
506 | function generateEntrypoint(
project: Project,
p: FsProject,
targets: Target[],
opts: EntrypointPermutation
) {
const { entrypointExt, withExt, entrypointLocation, entrypointTargetting } =
opts;
const entrypointFilename = `entrypoint-${entrypointSeq()}-${entrypointLocation}-to-${entrypointTargetting}${
withExt ? '-withext' : ''
}.${entrypointExt}`;
const { isMjs: entrypointIsMjs, isCompiled: entrypointIsCompiled } = fileInfo(
entrypointFilename,
project.typeModule,
project.allowJs
);
let entrypointContent = 'let mod;\n';
entrypointContent += 'let testsRun = 0;\n';
if (entrypointIsMjs) {
entrypointContent += `import assert from 'assert';\n`;
} else {
entrypointContent += `const assert = require('assert');\n`;
entrypointContent += `${declareDynamicImportFunction}\n`;
}
entrypointContent += `async function main() {\n`;
for (const target of targets) {
// TODO re-enable these when we have outDir <-> rootDir mapping
if (target.srcName.includes('onlyout') && entrypointTargetting === 'src')
continue;
if (target.srcName.includes('onlysrc') && entrypointTargetting === 'out')
continue;
const {
ext: targetSrcExt,
isMjs: targetIsMjs,
isCompiled: targetIsCompiled,
} = fileInfo(target.srcName, target.typeModule, project.allowJs);
let targetExtPermutations = [''];
if (!target.isPackage) {
if (entrypointTargetting === 'out' && target.outExt !== target.srcExt) {
// TODO re-enable when we have out <-> src mapping
targetExtPermutations = [target.outExt];
} else if (target.srcExt !== target.outExt) {
targetExtPermutations = [target.srcExt, target.outExt];
} else {
targetExtPermutations = [target.srcExt];
}
}
const externalPackageSelfImportPermutations = target.isPackage
? [false, true]
: [false];
for (const targetExt of targetExtPermutations) {
for (const externalPackageSelfImport of externalPackageSelfImportPermutations) {
entrypointContent += `\n// ${target.targetIdentifier}`;
if (target.isPackage) {
entrypointContent += ` node_modules package`;
if (externalPackageSelfImport) {
entrypointContent += ` self-import`;
}
} else {
entrypointContent += `.${targetExt}`;
}
entrypointContent += '\n';
// should specifier be relative or absolute?
let specifier: string;
if (externalPackageSelfImport) {
specifier = `../node_modules/${target.targetIdentifier}/self-import-${entrypointExt}.${entrypointExt}`;
} else if (target.isPackage) {
specifier = target.targetIdentifier;
} else {
if (entrypointTargetting === entrypointLocation) specifier = './';
else specifier = `../${entrypointTargetting}/`;
specifier += target.targetIdentifier;
if (target.isIndex) specifier += '-dir';
if (!target.isIndex && withExt) specifier += '.' + targetExt;
}
//#region SKIPPING
if (target.isNamedFile && !withExt) {
// Do not try to import cjs/cts without extension; node always requires these extensions
if (target.outExt === 'cjs') {
entrypointContent += `// skipping ${specifier} because we cannot omit extension from cjs / cts files; node always requires them\n`;
continue;
}
// Do not try to import mjs/mts unless experimental-specifier-resolution is turned on
if (
target.outExt === 'mjs' &&
!project.experimentalSpecifierResolutionNode
) {
entrypointContent += `// skipping ${specifier} because we cannot omit extension from mjs/mts unless experimental-specifier-resolution=node\n`;
continue;
}
// Do not try to import anything extensionless via ESM loader unless experimental-specifier-resolution is turned on
if (
(targetIsMjs || entrypointIsMjs) &&
!project.experimentalSpecifierResolutionNode
) {
entrypointContent += `// skipping ${specifier} because we cannot omit extension via esm loader unless experimental-specifier-resolution=node\n`;
continue;
}
}
if (
target.isPackage &&
isOneOf(target.packageStyle, [
'empty-manifest',
'main-out-extensionless',
'main-src-extensionless',
]) &&
isOneOf(target.outExt, ['cjs', 'mjs'])
) {
entrypointContent += `// skipping ${specifier} because it points to a node_modules package that tries to omit file extension, and node does not allow omitting cjs/mjs extension\n`;
continue;
}
// Do not try to import a transpiled file if compiler options disagree with node's extension-based classification
if (!project.useTsNodeNext && targetIsCompiled) {
if (targetIsMjs && !project.typeModule) {
entrypointContent += `// skipping ${specifier} because it is compiled and compiler options disagree with node's module classification: extension=${targetSrcExt}, tsconfig module=commonjs\n`;
continue;
}
if (!targetIsMjs && project.typeModule) {
entrypointContent += `// skipping ${specifier} because it is compiled and compiler options disagree with node's module classification: extension=${targetSrcExt}, tsconfig module=esnext\n`;
continue;
}
}
// Do not try to import index from a directory if is forbidden by node's ESM resolver
if (target.isIndex) {
if (
(targetIsMjs || entrypointIsMjs) &&
!project.experimentalSpecifierResolutionNode
) {
entrypointContent += `// skipping ${specifier} because esm loader does not allow directory ./index imports unless experimental-specifier-resolution=node\n`;
continue;
}
if (target.outExt === 'cjs') {
entrypointContent += `// skipping ${specifier} because it relies on node automatically resolving a directory to index.cjs/cts , but node does not support those extensions for index.* files, only .js (and equivalents), .node, .json\n`;
continue;
}
}
//#endregion
// NOTE: if you try to explicitly import foo.ts, we will load foo.ts, EVEN IF you have `preferTsExts` off
const assertIsSrcOrOut = !target.inSrc
? 'out'
: !target.inOut
? 'src'
: project.preferSrc ||
(!target.isIndex && targetExt === target.srcExt && withExt) ||
target.srcExt === target.outExt || // <-- TODO re-enable when we have src <-> out mapping
(target.isPackage &&
isOneOf(target.packageStyle, [
'main-src-with-extension',
'exports-src-with-extension',
]))
? 'src'
: 'out';
const assertHasExt =
assertIsSrcOrOut === 'src' ? target.srcExt : target.outExt;
// If entrypoint is compiled as CJS, and *not* with TS's nodenext, then TS transforms `import` into `require`,
// so we must hack around the compiler to get a true `import`.
const entrypointMustUseDynamicImportHack =
!project.useTsNodeNext &&
entrypointIsCompiled &&
!entrypointIsMjs &&
!externalPackageSelfImport;
entrypointContent +=
entrypointExt === 'cjs' && (externalPackageSelfImport || !targetIsMjs)
? ` mod = await require('${specifier}');\n`
: entrypointMustUseDynamicImportHack
? ` mod = await dynamicImport('${specifier}');\n`
: ` mod = await import('${specifier}');\n`;
entrypointContent += ` assert.equal(mod.loc, '${assertIsSrcOrOut}');\n`;
entrypointContent += ` assert.equal(mod.targetIdentifier, '${target.targetIdentifier}');\n`;
entrypointContent += ` assert.equal(mod.ext, '${assertHasExt}');\n`;
entrypointContent += ` testsRun++;\n`;
}
}
}
entrypointContent += `}\n`;
entrypointContent += `const result = main().then(() => {return testsRun});\n`;
entrypointContent += `result.mark = 'marked';\n`;
if (entrypointIsMjs) {
entrypointContent += `export {result};\n`;
} else {
entrypointContent += `exports.result = result;\n`;
}
p.dir(entrypointLocation).addFile(entrypointFilename, entrypointContent);
return entrypointLocation + '/' + entrypointFilename;
} | interface EntrypointPermutation {
entrypointExt: 'cjs' | 'mjs';
withExt: boolean;
entrypointLocation: 'src' | 'out';
entrypointTargetting: 'src' | 'out';
} |
507 | async function execute(t: T, p: FsProject, entrypoints: Entrypoint[]) {
//
// Install ts-node and try to import all the index-* files
//
const service = t.context.tsNodeUnderTest.register({
projectSearchDir: p.cwd,
});
process.__test_setloader__(t.context.tsNodeUnderTest.createEsmHooks(service));
for (const entrypoint of entrypoints) {
t.log(`Importing ${join(p.cwd, entrypoint)}`);
try {
const { result } = await dynamicImport(
pathToFileURL(join(p.cwd, entrypoint))
);
expect(result).toBeInstanceOf(Promise);
expect(result.mark).toBe('marked');
const testsRun = await result;
t.log(`Entrypoint ran ${testsRun} tests.`);
} catch (e) {
try {
const launchJsonPath = Path.resolve(
__dirname,
'../../.vscode/launch.json'
);
const launchJson = JSON.parse(fs.readFileSync(launchJsonPath, 'utf8'));
const config = launchJson.configurations.find(
(c: any) => c.name === 'Debug resolver test'
);
config.cwd = Path.join(
'${workspaceFolder}',
Path.relative(Path.resolve(__dirname, '../..'), p.cwd)
);
config.program = `./${entrypoint}`;
fs.writeFileSync(launchJsonPath, JSON.stringify(launchJson, null, 2));
} catch {}
throw new Error(
[
(e as Error).message,
(e as Error).stack,
'',
'This is an error in a resolver test. It might be easier to investigate by running outside of the test suite.',
'To do that, try pasting this into your bash shell (windows invocation will be similar but maybe not identical):',
` ( cd ${p.cwd} ; node --loader ../../../esm.mjs ./${entrypoint} )`,
].join('\n')
);
}
}
} | type T = ExecutionContext<ctxTsNode.Ctx>; |
508 | add(file: File): File | interface File {
path: string;
content: string;
} |
509 | (dir: DirectoryApi) => void | interface DirectoryApi {
add(file: File): File;
addFile(...args: Parameters<typeof file>): File;
addJsonFile(...args: Parameters<typeof jsonFile>): JsonFile<any>;
dir(dirPath: string, cb?: (dir: DirectoryApi) => void): DirectoryApi;
} |
510 | function add(file: File) {
file.path = Path.join(dirPath, file.path);
files.push(file);
return file;
} | interface File {
path: string;
content: string;
} |
511 | function declareTest(test: Test, testParams: TestParams) {
const name = `package-json-type=${testParams.packageJsonType} allowJs=${testParams.allowJs} ${testParams.typecheckMode} tsconfig-module=${testParams.tsModuleMode}`;
test(name, async (t) => {
const proj = writeFixturesToFilesystem(name, testParams);
t.log(
`Running this command: ( cd ${proj.cwd} ; ${CMD_TS_NODE_WITHOUT_PROJECT_FLAG} --esm ./index.mjs )`
);
// All assertions happen within the fixture scripts
// Zero exit code indicates a passing test
const { stdout, stderr, err } = await exec(
`${CMD_TS_NODE_WITHOUT_PROJECT_FLAG} --esm ./index.mjs`,
{ cwd: proj.cwd }
);
t.log(stdout);
t.log(stderr);
expect(err).toBe(null);
expect(stdout).toMatch(/done\n$/);
});
} | interface TestParams {
packageJsonType: PackageJsonType;
typecheckMode: typeof typecheckModes[number];
allowJs: boolean;
tsModuleMode: 'NodeNext' | 'Node16';
} |
512 | function declareTest(test: Test, testParams: TestParams) {
const name = `package-json-type=${testParams.packageJsonType} allowJs=${testParams.allowJs} ${testParams.typecheckMode} tsconfig-module=${testParams.tsModuleMode}`;
test(name, async (t) => {
const proj = writeFixturesToFilesystem(name, testParams);
t.log(
`Running this command: ( cd ${proj.cwd} ; ${CMD_TS_NODE_WITHOUT_PROJECT_FLAG} --esm ./index.mjs )`
);
// All assertions happen within the fixture scripts
// Zero exit code indicates a passing test
const { stdout, stderr, err } = await exec(
`${CMD_TS_NODE_WITHOUT_PROJECT_FLAG} --esm ./index.mjs`,
{ cwd: proj.cwd }
);
t.log(stdout);
t.log(stderr);
expect(err).toBe(null);
expect(stdout).toMatch(/done\n$/);
});
} | type Test = TestInterface<ctxTsNode.Ctx>; |
513 | function declareTest(test: Test, testParams: TestParams) {
const name = `package-json-type=${testParams.packageJsonType} allowJs=${testParams.allowJs} ${testParams.typecheckMode} tsconfig-module=${testParams.tsModuleMode}`;
test(name, async (t) => {
const proj = writeFixturesToFilesystem(name, testParams);
t.log(
`Running this command: ( cd ${proj.cwd} ; ${CMD_TS_NODE_WITHOUT_PROJECT_FLAG} --esm ./index.mjs )`
);
// All assertions happen within the fixture scripts
// Zero exit code indicates a passing test
const { stdout, stderr, err } = await exec(
`${CMD_TS_NODE_WITHOUT_PROJECT_FLAG} --esm ./index.mjs`,
{ cwd: proj.cwd }
);
t.log(stdout);
t.log(stderr);
expect(err).toBe(null);
expect(stdout).toMatch(/done\n$/);
});
} | type Test = typeof test; |
514 | function getExtensionTreatment(ext: Extension, testParams: TestParams) {
// JSX and any TS extensions get compiled. Everything is compiled in allowJs mode
const isCompiled = testParams.allowJs || !ext.isJs || ext.isJsxExt;
const isExecutedAsEsm =
ext.forcesEsm ||
(!ext.forcesCjs && testParams.packageJsonType === 'module');
const isExecutedAsCjs = !isExecutedAsEsm;
// if allowJs:false, then .jsx files are not allowed
const isAllowed = !ext.isJsxExt || !ext.isJs || testParams.allowJs;
const canHaveJsxSyntax = ext.isJsxExt || (ext.supportsJsx && isCompiled);
return {
isCompiled,
isExecutedAsCjs,
isExecutedAsEsm,
isAllowed,
canHaveJsxSyntax,
};
} | interface Extension {
ext: string;
jsEquivalentExt?: string;
forcesCjs?: boolean;
forcesEsm?: boolean;
isJs?: boolean;
supportsJsx?: boolean;
isJsxExt?: boolean;
cjsAllowsOmittingExt?: boolean;
} |
515 | function getExtensionTreatment(ext: Extension, testParams: TestParams) {
// JSX and any TS extensions get compiled. Everything is compiled in allowJs mode
const isCompiled = testParams.allowJs || !ext.isJs || ext.isJsxExt;
const isExecutedAsEsm =
ext.forcesEsm ||
(!ext.forcesCjs && testParams.packageJsonType === 'module');
const isExecutedAsCjs = !isExecutedAsEsm;
// if allowJs:false, then .jsx files are not allowed
const isAllowed = !ext.isJsxExt || !ext.isJs || testParams.allowJs;
const canHaveJsxSyntax = ext.isJsxExt || (ext.supportsJsx && isCompiled);
return {
isCompiled,
isExecutedAsCjs,
isExecutedAsEsm,
isAllowed,
canHaveJsxSyntax,
};
} | interface TestParams {
packageJsonType: PackageJsonType;
typecheckMode: typeof typecheckModes[number];
allowJs: boolean;
tsModuleMode: 'NodeNext' | 'Node16';
} |
516 | function createImporter(
proj: ProjectAPI,
testParams: TestParams,
importerParams: ImporterParams
) {
const { importStyle, importerExtension } = importerParams;
const name = `${importStyle} from ${importerExtension.ext}`;
const importerTreatment = getExtensionTreatment(
importerExtension,
testParams
);
if (!importerTreatment.isAllowed) return;
// import = require only allowed in non-js files
if (importStyle === 'import = require' && importerExtension.isJs) return;
// const = require not allowed in ESM
if (importStyle === 'require' && importerTreatment.isExecutedAsEsm) return;
// swc bug: import = require will not work in ESM, because swc does not emit necessary `__require = createRequire()`
if (
testParams.typecheckMode === 'swc' &&
importStyle === 'import = require' &&
importerTreatment.isExecutedAsEsm
)
return;
const importer = {
path: `${name.replace(/ /g, '_')}.${importerExtension.ext}`,
imports: '',
assertions: '',
get content() {
return `
${this.imports}
async function main() {
${this.assertions}
}
main();
`;
},
};
proj.add(importer);
if (!importerExtension.isJs) importer.imports += `export {};\n`;
for (const importeeExtension of extensions) {
const ci = createImportee(testParams, { importeeExtension });
if (!ci) continue;
const { importee, treatment: importeeTreatment } = ci;
proj.add(importee);
// dynamic import is the only way to import ESM from CJS
if (
importeeTreatment.isExecutedAsEsm &&
importerTreatment.isExecutedAsCjs &&
importStyle !== 'dynamic import'
)
continue;
// Cannot import = require an ESM file
if (importeeTreatment.isExecutedAsEsm && importStyle === 'import = require')
continue;
// Cannot use static imports in non-compiled non-ESM
if (
importStyle === 'static import' &&
!importerTreatment.isCompiled &&
importerTreatment.isExecutedAsCjs
)
continue;
let importSpecifier = `./${importeeExtension.ext}`;
if (
!importeeExtension.cjsAllowsOmittingExt ||
isOneOf(importStyle, ['dynamic import', 'static import'])
)
importSpecifier +=
'.' + (importeeExtension.jsEquivalentExt ?? importeeExtension.ext);
switch (importStyle) {
case 'dynamic import':
importer.assertions += `const ${importeeExtension.ext} = await import('${importSpecifier}');\n`;
break;
case 'import = require':
importer.imports += `import ${importeeExtension.ext} = require('${importSpecifier}');\n`;
break;
case 'require':
importer.imports += `const ${importeeExtension.ext} = require('${importSpecifier}');\n`;
break;
case 'static import':
importer.imports += `import * as ${importeeExtension.ext} from '${importSpecifier}';\n`;
break;
}
// Check both namespace.ext and namespace.default.ext, because node can't detect named exports from files we transform
const namespaceAsAny = importerExtension.isJs
? importeeExtension.ext
: `(${importeeExtension.ext} as any)`;
importer.assertions += `if((${importeeExtension.ext}.ext ?? ${namespaceAsAny}.default.ext) !== '${importeeExtension.ext}')\n`;
importer.assertions += ` throw new Error('Wrong export from importee: expected ${importeeExtension.ext} but got ' + ${importeeExtension.ext}.ext + '(importee has these keys: ' + Object.keys(${importeeExtension.ext}) + ')');\n`;
}
return importer;
} | interface ImporterParams {
importStyle: typeof importStyles[number];
importerExtension: typeof extensions[number];
} |
517 | function createImporter(
proj: ProjectAPI,
testParams: TestParams,
importerParams: ImporterParams
) {
const { importStyle, importerExtension } = importerParams;
const name = `${importStyle} from ${importerExtension.ext}`;
const importerTreatment = getExtensionTreatment(
importerExtension,
testParams
);
if (!importerTreatment.isAllowed) return;
// import = require only allowed in non-js files
if (importStyle === 'import = require' && importerExtension.isJs) return;
// const = require not allowed in ESM
if (importStyle === 'require' && importerTreatment.isExecutedAsEsm) return;
// swc bug: import = require will not work in ESM, because swc does not emit necessary `__require = createRequire()`
if (
testParams.typecheckMode === 'swc' &&
importStyle === 'import = require' &&
importerTreatment.isExecutedAsEsm
)
return;
const importer = {
path: `${name.replace(/ /g, '_')}.${importerExtension.ext}`,
imports: '',
assertions: '',
get content() {
return `
${this.imports}
async function main() {
${this.assertions}
}
main();
`;
},
};
proj.add(importer);
if (!importerExtension.isJs) importer.imports += `export {};\n`;
for (const importeeExtension of extensions) {
const ci = createImportee(testParams, { importeeExtension });
if (!ci) continue;
const { importee, treatment: importeeTreatment } = ci;
proj.add(importee);
// dynamic import is the only way to import ESM from CJS
if (
importeeTreatment.isExecutedAsEsm &&
importerTreatment.isExecutedAsCjs &&
importStyle !== 'dynamic import'
)
continue;
// Cannot import = require an ESM file
if (importeeTreatment.isExecutedAsEsm && importStyle === 'import = require')
continue;
// Cannot use static imports in non-compiled non-ESM
if (
importStyle === 'static import' &&
!importerTreatment.isCompiled &&
importerTreatment.isExecutedAsCjs
)
continue;
let importSpecifier = `./${importeeExtension.ext}`;
if (
!importeeExtension.cjsAllowsOmittingExt ||
isOneOf(importStyle, ['dynamic import', 'static import'])
)
importSpecifier +=
'.' + (importeeExtension.jsEquivalentExt ?? importeeExtension.ext);
switch (importStyle) {
case 'dynamic import':
importer.assertions += `const ${importeeExtension.ext} = await import('${importSpecifier}');\n`;
break;
case 'import = require':
importer.imports += `import ${importeeExtension.ext} = require('${importSpecifier}');\n`;
break;
case 'require':
importer.imports += `const ${importeeExtension.ext} = require('${importSpecifier}');\n`;
break;
case 'static import':
importer.imports += `import * as ${importeeExtension.ext} from '${importSpecifier}';\n`;
break;
}
// Check both namespace.ext and namespace.default.ext, because node can't detect named exports from files we transform
const namespaceAsAny = importerExtension.isJs
? importeeExtension.ext
: `(${importeeExtension.ext} as any)`;
importer.assertions += `if((${importeeExtension.ext}.ext ?? ${namespaceAsAny}.default.ext) !== '${importeeExtension.ext}')\n`;
importer.assertions += ` throw new Error('Wrong export from importee: expected ${importeeExtension.ext} but got ' + ${importeeExtension.ext}.ext + '(importee has these keys: ' + Object.keys(${importeeExtension.ext}) + ')');\n`;
}
return importer;
} | interface TestParams {
packageJsonType: PackageJsonType;
typecheckMode: typeof typecheckModes[number];
allowJs: boolean;
tsModuleMode: 'NodeNext' | 'Node16';
} |
518 | function createImporter(
proj: ProjectAPI,
testParams: TestParams,
importerParams: ImporterParams
) {
const { importStyle, importerExtension } = importerParams;
const name = `${importStyle} from ${importerExtension.ext}`;
const importerTreatment = getExtensionTreatment(
importerExtension,
testParams
);
if (!importerTreatment.isAllowed) return;
// import = require only allowed in non-js files
if (importStyle === 'import = require' && importerExtension.isJs) return;
// const = require not allowed in ESM
if (importStyle === 'require' && importerTreatment.isExecutedAsEsm) return;
// swc bug: import = require will not work in ESM, because swc does not emit necessary `__require = createRequire()`
if (
testParams.typecheckMode === 'swc' &&
importStyle === 'import = require' &&
importerTreatment.isExecutedAsEsm
)
return;
const importer = {
path: `${name.replace(/ /g, '_')}.${importerExtension.ext}`,
imports: '',
assertions: '',
get content() {
return `
${this.imports}
async function main() {
${this.assertions}
}
main();
`;
},
};
proj.add(importer);
if (!importerExtension.isJs) importer.imports += `export {};\n`;
for (const importeeExtension of extensions) {
const ci = createImportee(testParams, { importeeExtension });
if (!ci) continue;
const { importee, treatment: importeeTreatment } = ci;
proj.add(importee);
// dynamic import is the only way to import ESM from CJS
if (
importeeTreatment.isExecutedAsEsm &&
importerTreatment.isExecutedAsCjs &&
importStyle !== 'dynamic import'
)
continue;
// Cannot import = require an ESM file
if (importeeTreatment.isExecutedAsEsm && importStyle === 'import = require')
continue;
// Cannot use static imports in non-compiled non-ESM
if (
importStyle === 'static import' &&
!importerTreatment.isCompiled &&
importerTreatment.isExecutedAsCjs
)
continue;
let importSpecifier = `./${importeeExtension.ext}`;
if (
!importeeExtension.cjsAllowsOmittingExt ||
isOneOf(importStyle, ['dynamic import', 'static import'])
)
importSpecifier +=
'.' + (importeeExtension.jsEquivalentExt ?? importeeExtension.ext);
switch (importStyle) {
case 'dynamic import':
importer.assertions += `const ${importeeExtension.ext} = await import('${importSpecifier}');\n`;
break;
case 'import = require':
importer.imports += `import ${importeeExtension.ext} = require('${importSpecifier}');\n`;
break;
case 'require':
importer.imports += `const ${importeeExtension.ext} = require('${importSpecifier}');\n`;
break;
case 'static import':
importer.imports += `import * as ${importeeExtension.ext} from '${importSpecifier}';\n`;
break;
}
// Check both namespace.ext and namespace.default.ext, because node can't detect named exports from files we transform
const namespaceAsAny = importerExtension.isJs
? importeeExtension.ext
: `(${importeeExtension.ext} as any)`;
importer.assertions += `if((${importeeExtension.ext}.ext ?? ${namespaceAsAny}.default.ext) !== '${importeeExtension.ext}')\n`;
importer.assertions += ` throw new Error('Wrong export from importee: expected ${importeeExtension.ext} but got ' + ${importeeExtension.ext}.ext + '(importee has these keys: ' + Object.keys(${importeeExtension.ext}) + ')');\n`;
}
return importer;
} | type ProjectAPI = ReturnType<typeof projectInternal>; |
519 | function createImportee(
testParams: TestParams,
importeeParams: ImporteeParams
) {
const { importeeExtension } = importeeParams;
const importee = file(`${importeeExtension.ext}.${importeeExtension.ext}`);
const treatment = getExtensionTreatment(importeeExtension, testParams);
if (!treatment.isAllowed) return;
if (treatment.isCompiled || treatment.isExecutedAsEsm) {
importee.content += `export const ext = '${importeeExtension.ext}';\n`;
} else {
importee.content += `exports.ext = '${importeeExtension.ext}';\n`;
}
if (!importeeExtension.isJs) {
importee.content += `const testTsTypeSyntax: string = 'a string';\n`;
}
if (treatment.isExecutedAsCjs) {
importee.content += `if(typeof __filename !== 'string') throw new Error('expected file to be CJS but __filename is not declared');\n`;
} else {
importee.content += `if(typeof __filename !== 'undefined') throw new Error('expected file to be ESM but __filename is declared');\n`;
importee.content += `if(typeof import.meta.url !== 'string') throw new Error('expected file to be ESM but import.meta.url is not declared');\n`;
}
if (treatment.canHaveJsxSyntax) {
importee.content += `
const React = {
createElement(tag, dunno, content) {
return {props: {children: [content]}};
}
};
const jsxTest = <a>Hello World</a>;
if(jsxTest?.props?.children[0] !== 'Hello World') throw new Error('Expected ${importeeExtension.ext} to support JSX but it did not.');
`;
}
return { importee, treatment };
} | interface TestParams {
packageJsonType: PackageJsonType;
typecheckMode: typeof typecheckModes[number];
allowJs: boolean;
tsModuleMode: 'NodeNext' | 'Node16';
} |
520 | function createImportee(
testParams: TestParams,
importeeParams: ImporteeParams
) {
const { importeeExtension } = importeeParams;
const importee = file(`${importeeExtension.ext}.${importeeExtension.ext}`);
const treatment = getExtensionTreatment(importeeExtension, testParams);
if (!treatment.isAllowed) return;
if (treatment.isCompiled || treatment.isExecutedAsEsm) {
importee.content += `export const ext = '${importeeExtension.ext}';\n`;
} else {
importee.content += `exports.ext = '${importeeExtension.ext}';\n`;
}
if (!importeeExtension.isJs) {
importee.content += `const testTsTypeSyntax: string = 'a string';\n`;
}
if (treatment.isExecutedAsCjs) {
importee.content += `if(typeof __filename !== 'string') throw new Error('expected file to be CJS but __filename is not declared');\n`;
} else {
importee.content += `if(typeof __filename !== 'undefined') throw new Error('expected file to be ESM but __filename is declared');\n`;
importee.content += `if(typeof import.meta.url !== 'string') throw new Error('expected file to be ESM but import.meta.url is not declared');\n`;
}
if (treatment.canHaveJsxSyntax) {
importee.content += `
const React = {
createElement(tag, dunno, content) {
return {props: {children: [content]}};
}
};
const jsxTest = <a>Hello World</a>;
if(jsxTest?.props?.children[0] !== 'Hello World') throw new Error('Expected ${importeeExtension.ext} to support JSX but it did not.');
`;
}
return { importee, treatment };
} | interface ImporteeParams {
importeeExtension: typeof extensions[number];
} |
521 | function createReplViaApi({
registerHooks,
createReplOpts,
createServiceOpts,
}: CreateReplViaApiOptions) {
const stdin = new PassThrough();
const stdout = new PassThrough();
const stderr = new PassThrough();
const replService = tsNodeUnderTest.createRepl({
stdin,
stdout,
stderr,
...createReplOpts,
});
const service = (
registerHooks ? tsNodeUnderTest.register : tsNodeUnderTest.create
)({
...replService.evalAwarePartialHost,
project: `${TEST_DIR}/tsconfig.json`,
...createServiceOpts,
tsTrace: replService.console.log.bind(replService.console),
});
replService.setService(service);
t.teardown(async () => {
service.enabled(false);
});
return { stdin, stdout, stderr, replService, service };
} | interface CreateReplViaApiOptions {
registerHooks: boolean;
createReplOpts?: Partial<tsNodeTypes.CreateReplOptions>;
createServiceOpts?: Partial<tsNodeTypes.CreateOptions>;
} |
522 | async function upstreamTopLevelAwaitTests({
TEST_DIR,
tsNodeUnderTest,
}: SharedObjects) {
const PROMPT = 'await repl > ';
const putIn = new REPLStream();
const replService = tsNodeUnderTest.createRepl({
// @ts-ignore
stdin: putIn,
// @ts-ignore
stdout: putIn,
// @ts-ignore
stderr: putIn,
});
const service = tsNodeUnderTest.create({
...replService.evalAwarePartialHost,
project: `${TEST_DIR}/tsconfig.json`,
experimentalReplAwait: true,
transpileOnly: true,
compilerOptions: {
target: 'es2018',
},
});
replService.setService(service);
(
replService.stdout as NodeJS.WritableStream & {
isTTY: boolean;
}
).isTTY = true;
const replServer = replService.startInternal({
prompt: PROMPT,
terminal: true,
useColors: true,
useGlobal: false,
});
function runAndWait(cmds: Array<string | Key>) {
const promise = putIn.wait();
for (const cmd of cmds) {
if (typeof cmd === 'string') {
putIn.run([cmd]);
} else {
replServer.write('', cmd);
}
}
return promise;
}
await runAndWait([
'function foo(x) { return x; }',
'function koo() { return Promise.resolve(4); }',
]);
const testCases = [
['await Promise.resolve(0)', '0'],
// issue: { a: await Promise.resolve(1) } is being interpreted as a block
// remove surrounding parenthesis once issue is fixed
['({ a: await Promise.resolve(1) })', '{ a: 1 }'],
['_', '{ a: 1 }'],
['let { aa, bb } = await Promise.resolve({ aa: 1, bb: 2 }), f = 5;'],
['aa', '1'],
['bb', '2'],
['f', '5'],
['let cc = await Promise.resolve(2)'],
['cc', '2'],
['let dd;'],
['dd'],
['let [ii, { abc: { kk } }] = [0, { abc: { kk: 1 } }];'],
['ii', '0'],
['kk', '1'],
['var ll = await Promise.resolve(2);'],
['ll', '2'],
['foo(await koo())', '4'],
['_', '4'],
['const m = foo(await koo());'],
['m', '4'],
// issue: REPL doesn't recognize end of input
// compile is returning TS1005 after second line even though
// it's valid syntax
// [
// 'const n = foo(await\nkoo());',
// ['const n = foo(await\r', '... koo());\r', 'undefined'],
// ],
[
'`status: ${(await Promise.resolve({ status: 200 })).status}`',
"'status: 200'",
],
['for (let i = 0; i < 2; ++i) await i'],
['for (let i = 0; i < 2; ++i) { await i }'],
['await 0', '0'],
['await 0; function foo() {}'],
['foo', '[Function: foo]'],
['class Foo {}; await 1;', '1'],
['Foo', '[class Foo]'],
['if (await true) { function fooz() {}; }'],
['fooz', '[Function: fooz]'],
['if (await true) { class Bar {}; }'],
[
'Bar',
'Uncaught ReferenceError: Bar is not defined',
// Line increased due to TS added lines
{
line: 4,
},
],
['await 0; function* gen(){}'],
['for (var i = 0; i < 10; ++i) { await i; }'],
['i', '10'],
['for (let j = 0; j < 5; ++j) { await j; }'],
[
'j',
'Uncaught ReferenceError: j is not defined',
// Line increased due to TS added lines
{
line: 4,
},
],
['gen', '[GeneratorFunction: gen]'],
[
'return 42; await 5;',
'Uncaught SyntaxError: Illegal return statement',
// Line increased due to TS added lines
{
line: 4,
},
],
['let o = await 1, p'],
['p'],
['let q = 1, s = await 2'],
['s', '2'],
[
'for await (let i of [1,2,3]) console.log(i)',
[
'for await (let i of [1,2,3]) console.log(i)\r',
'1',
'2',
'3',
'undefined',
],
],
// issue: REPL is expecting more input to finish execution
// compiler is returning TS1003 error
// [
// 'await Promise..resolve()',
// [
// 'await Promise..resolve()\r',
// 'Uncaught SyntaxError: ',
// 'await Promise..resolve()',
// ' ^',
// '',
// "Unexpected token '.'",
// ],
// ],
[
'for (const x of [1,2,3]) {\nawait x\n}',
['for (const x of [1,2,3]) {\r', '... await x\r', '... }\r', 'undefined'],
],
[
'for (const x of [1,2,3]) {\nawait x;\n}',
[
'for (const x of [1,2,3]) {\r',
'... await x;\r',
'... }\r',
'undefined',
],
],
[
'for await (const x of [1,2,3]) {\nconsole.log(x)\n}',
[
'for await (const x of [1,2,3]) {\r',
'... console.log(x)\r',
'... }\r',
'1',
'2',
'3',
'undefined',
],
],
[
'for await (const x of [1,2,3]) {\nconsole.log(x);\n}',
[
'for await (const x of [1,2,3]) {\r',
'... console.log(x);\r',
'... }\r',
'1',
'2',
'3',
'undefined',
],
],
] as const;
for (const [
input,
expected = [`${input}\r`],
options = {} as { line?: number },
] of testCases) {
const toBeRun = input.split('\n');
const lines = await runAndWait(toBeRun);
if (Array.isArray(expected)) {
if (expected.length === 1) expected.push('undefined');
if (lines[0] === input) lines.shift();
expect(lines).toEqual([...expected, PROMPT]);
} else if ('line' in options) {
expect(lines[toBeRun.length + options.line!]).toEqual(expected);
} else {
const echoed = toBeRun.map((a, i) => `${i > 0 ? '... ' : ''}${a}\r`);
expect(lines).toEqual([...echoed, expected, PROMPT]);
}
}
} | interface SharedObjects extends ctxTsNode.Ctx {
TEST_DIR: string;
} |
523 | (
options: CreateTranspilerOptions
) => Transpiler | interface CreateTranspilerOptions {
// TODO this is confusing because its only a partial Service. Rename?
// Careful: must avoid stripInternal breakage by guarding with Extract<>
service: Pick<
Service,
Extract<'config' | 'options' | 'projectLocalResolveHelper', keyof Service>
>;
/**
* If `"transpiler"` option is declared in an "extends" tsconfig, this path might be different than
* the `projectLocalResolveHelper`
*
* @internal
*/
transpilerConfigLocalResolveHelper: ProjectLocalResolveHelper;
/**
* When using `module: nodenext` or `module: node12`, there are two possible styles of emit:
* - CommonJS with dynamic imports preserved (not transformed into `require()` calls)
* - ECMAScript modules with `import foo = require()` transformed into `require = createRequire(); const foo = require()`
* @internal
*/
nodeModuleEmitKind?: NodeModuleEmitKind;
} |
524 | function create(createOptions: SwcTranspilerOptions): Transpiler {
const {
swc,
service: { config, projectLocalResolveHelper },
transpilerConfigLocalResolveHelper,
nodeModuleEmitKind,
} = createOptions;
// Load swc compiler
let swcInstance: SwcInstance;
// Used later in diagnostics; merely needs to be human-readable.
let swcDepName: string = 'swc';
if (typeof swc === 'string') {
swcDepName = swc;
swcInstance = require(transpilerConfigLocalResolveHelper(
swc,
true
)) as typeof swcWasm;
} else if (swc == null) {
let swcResolved;
try {
swcDepName = '@swc/core';
swcResolved = transpilerConfigLocalResolveHelper(swcDepName, true);
} catch (e) {
try {
swcDepName = '@swc/wasm';
swcResolved = transpilerConfigLocalResolveHelper(swcDepName, true);
} catch (e) {
throw new Error(
'swc compiler requires either @swc/core or @swc/wasm to be installed as a dependency. See https://typestrong.org/ts-node/docs/transpilers'
);
}
}
swcInstance = require(swcResolved) as typeof swcWasm;
} else {
swcInstance = swc;
}
// Prepare SWC options derived from typescript compiler options
const { nonTsxOptions, tsxOptions } = createSwcOptions(
config.options,
nodeModuleEmitKind,
swcInstance,
swcDepName
);
const transpile: Transpiler['transpile'] = (input, transpileOptions) => {
const { fileName } = transpileOptions;
const swcOptions =
fileName.endsWith('.tsx') || fileName.endsWith('.jsx')
? tsxOptions
: nonTsxOptions;
const { code, map } = swcInstance.transformSync(input, {
...swcOptions,
filename: fileName,
});
return { outputText: code, sourceMapText: map };
};
return {
transpile,
};
} | interface SwcTranspilerOptions extends CreateTranspilerOptions {
/**
* swc compiler to use for compilation
* Set to '@swc/wasm' to use swc's WASM compiler
* Default: '@swc/core', falling back to '@swc/wasm'
*/
swc?: string | typeof swcWasm;
} |
525 | function callInChild(state: BootstrapState) {
const child = spawn(
process.execPath,
[
'--require',
require.resolve('./child-require.js'),
'--loader',
// Node on Windows doesn't like `c:\` absolute paths here; must be `file:///c:/`
pathToFileURL(require.resolve('../../child-loader.mjs')).toString(),
require.resolve('./child-entrypoint.js'),
`${argPrefix}${compress(state)}`,
...state.parseArgvResult.restArgs,
],
{
stdio: 'inherit',
argv0: process.argv0,
}
);
child.on('error', (error) => {
console.error(error);
process.exit(1);
});
child.on('exit', (code) => {
child.removeAllListeners();
process.off('SIGINT', sendSignalToChild);
process.off('SIGTERM', sendSignalToChild);
process.exitCode = code === null ? 1 : code;
});
// Ignore sigint and sigterm in parent; pass them to child
process.on('SIGINT', sendSignalToChild);
process.on('SIGTERM', sendSignalToChild);
function sendSignalToChild(signal: string) {
process.kill(child.pid, signal);
}
} | interface BootstrapState {
isInChildProcess: boolean;
shouldUseChildProcess: boolean;
/**
* True if bootstrapping the ts-node CLI process or the direct child necessitated by `--esm`.
* false if bootstrapping a subsequently `fork()`ed child.
*/
isCli: boolean;
tsNodeScript: string;
parseArgvResult: ReturnType<typeof parseArgv>;
phase2Result?: ReturnType<typeof phase2>;
phase3Result?: ReturnType<typeof phase3>;
} |
526 | function setFooBar(fooBar: FooBar): void; | type FooBar = Merge<FooInterface, BarType>; |
527 | function setFooBar(fooBar: FooBar): void; | type FooBar = InvariantOf<{
foo: number;
bar: string;
}>; |
528 | function setFooBar(fooBar: FooBar): void; | type FooBar = Spread<Foo, Bar>; |
529 | function setFooBar(fooBar: FooBar): void; | type FooBar = Simplify<Foo & Bar>; |
530 | function mergeDeep<
Destination,
Source,
Options extends MergeDeepOptions = {},
>(destination: Destination, source: Source, options?: Options): MergeDeep<Destination, Source, Options>; | type Options = MergeExclusive<ExclusiveVariation1, ExclusiveVariation2>; |
531 | function mergeDeep<
Destination,
Source,
Options extends MergeDeepOptions = {},
>(destination: Destination, source: Source, options?: Options): MergeDeep<Destination, Source, Options>; | type Options = TupleToUnion<typeof options>; |
532 | <TProp extends keyof Variation6Config>(
config: Variation6Config,
prop: TProp,
): config is SetNonNullable<Variation6Config, TProp> => Boolean(config[prop]) | type Variation6Config = {a: boolean | null; b: boolean | null}; |
533 | function lastOf<V extends readonly unknown[]>(array: V): LastArrayElement<V>; | interface V {
a?: number;
} |
534 | function consumeExtraProps(extraProps: ExtraProps): void; | type ExtraProps = GlobalThis & {
readonly GLOBAL_TOKEN: string;
}; |
535 | function setConfig(config: JsonObject): void; | type JsonObject = {[Key in string]: JsonValue} & {[Key in string]?: JsonValue | undefined}; |
536 | (_: ValidMessages): void => {} | type ValidMessages = RequireAtLeastOne<
SystemMessages,
'macos' | 'linux' | 'windows'
>; |
537 | (_: ValidMessages): void => {} | type ValidMessages = RequireAllOrNone<SystemMessages, 'macos' | 'linux'>; |
538 | (_: ValidMessages): void => {} | type ValidMessages = RequireExactlyOne<SystemMessages, 'macos' | 'linux'>; |
539 | move(position: Position): Position | type Position = {top: number; left: number}; |
540 | move(position: Position) {
return position;
} | type Position = {top: number; left: number}; |
541 | (argument: Type) => Type | type Type = Array<{x: string}> & Array<{z: number; d: {e: string; f: boolean}}>; |
542 | (distributedUnion: Union) => void | type Union = EmptyObject | {id: number}; |
543 | function getStrippedPath(tryPath: TryPath): string {
return tryPath.type === "index"
? dirname(tryPath.path)
: tryPath.type === "file"
? tryPath.path
: tryPath.type === "extension"
? removeExtension(tryPath.path)
: tryPath.type === "package"
? tryPath.path
: exhaustiveTypeException(tryPath.type);
} | interface TryPath {
readonly type: "file" | "extension" | "index" | "package";
readonly path: string;
} |
544 | function configLoader({
cwd,
explicitParams,
tsConfigLoader = TsConfigLoader2.tsConfigLoader,
}: ConfigLoaderParams): ConfigLoaderResult {
if (explicitParams) {
const absoluteBaseUrl = path.isAbsolute(explicitParams.baseUrl)
? explicitParams.baseUrl
: path.join(cwd, explicitParams.baseUrl);
return {
resultType: "success",
configFileAbsolutePath: "",
baseUrl: explicitParams.baseUrl,
absoluteBaseUrl,
paths: explicitParams.paths,
mainFields: explicitParams.mainFields,
addMatchAll: explicitParams.addMatchAll,
};
}
// Load tsconfig and create path matching function
const loadResult = tsConfigLoader({
cwd,
getEnv: (key: string) => process.env[key],
});
if (!loadResult.tsConfigPath) {
return {
resultType: "failed",
message: "Couldn't find tsconfig.json",
};
}
return {
resultType: "success",
configFileAbsolutePath: loadResult.tsConfigPath,
baseUrl: loadResult.baseUrl,
absoluteBaseUrl: path.resolve(
path.dirname(loadResult.tsConfigPath),
loadResult.baseUrl || ""
),
paths: loadResult.paths || {},
addMatchAll: loadResult.baseUrl !== undefined,
};
} | interface ConfigLoaderParams {
cwd: string;
explicitParams?: ExplicitParams;
tsConfigLoader?: TsConfigLoader;
} |
545 | function tsConfigLoader({
getEnv,
cwd,
loadSync = loadSyncDefault,
}: TsConfigLoaderParams): TsConfigLoaderResult {
const TS_NODE_PROJECT = getEnv("TS_NODE_PROJECT");
const TS_NODE_BASEURL = getEnv("TS_NODE_BASEURL");
// tsconfig.loadSync handles if TS_NODE_PROJECT is a file or directory
// and also overrides baseURL if TS_NODE_BASEURL is available.
const loadResult = loadSync(cwd, TS_NODE_PROJECT, TS_NODE_BASEURL);
return loadResult;
} | interface TsConfigLoaderParams {
getEnv: (key: string) => string | undefined;
cwd: string;
loadSync?(
cwd: string,
filename?: string,
baseUrl?: string
): TsConfigLoaderResult;
} |
546 | function register(params?: RegisterParams): () => void {
let cwd: string | undefined;
let explicitParams: ExplicitParams | undefined;
if (params) {
cwd = params.cwd;
if (params.baseUrl || params.paths) {
explicitParams = params;
}
} else {
// eslint-disable-next-line
const minimist = require("minimist");
const argv = minimist(process.argv.slice(2), {
// eslint-disable-next-line id-denylist
string: ["project"],
alias: {
project: ["P"],
},
});
cwd = argv.project;
}
const configLoaderResult = configLoader({
cwd: cwd ?? process.cwd(),
explicitParams,
});
if (configLoaderResult.resultType === "failed") {
console.warn(
`${configLoaderResult.message}. tsconfig-paths will be skipped`
);
return noOp;
}
const matchPath = createMatchPath(
configLoaderResult.absoluteBaseUrl,
configLoaderResult.paths,
configLoaderResult.mainFields,
configLoaderResult.addMatchAll
);
// Patch node's module loading
// eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires
const Module = require("module");
// eslint-disable-next-line no-underscore-dangle
const originalResolveFilename = Module._resolveFilename;
const coreModules = getCoreModules(Module.builtinModules);
// eslint-disable-next-line @typescript-eslint/no-explicit-any,no-underscore-dangle
Module._resolveFilename = function (request: string, _parent: any): string {
const isCoreModule = coreModules.hasOwnProperty(request);
if (!isCoreModule) {
const found = matchPath(request);
if (found) {
const modifiedArguments = [found, ...[].slice.call(arguments, 1)]; // Passes all arguments. Even those that is not specified above.
return originalResolveFilename.apply(this, modifiedArguments);
}
}
return originalResolveFilename.apply(this, arguments);
};
return () => {
// Return node's module loading to original state.
// eslint-disable-next-line no-underscore-dangle
Module._resolveFilename = originalResolveFilename;
};
} | interface RegisterParams extends ExplicitParams {
/**
* Defaults to `--project` CLI flag or `process.cwd()`
*/
cwd?: string;
} |
547 | public runAsync(callback: StringCallback) {
try {
this.launchEditorAsync(() => {
try {
this.readTemporaryFile();
setImmediate(callback, null, this.text);
} catch (readError) {
setImmediate(callback, readError, null);
}
});
} catch (launchError) {
setImmediate(callback, launchError, null);
}
} | type StringCallback = (err: Error, result: string) => void; |
548 | public runAsync(callback: StringCallback) {
try {
this.launchEditorAsync(() => {
try {
this.readTemporaryFile();
setImmediate(callback, null, this.text);
} catch (readError) {
setImmediate(callback, readError, null);
}
});
} catch (launchError) {
setImmediate(callback, launchError, null);
}
} | type StringCallback = (err: Error, result: string) => void; |
549 | private launchEditorAsync(callback: VoidCallback) {
try {
const editorProcess = spawn(
this.editor.bin,
this.editor.args.concat([this.tempFile]),
{stdio: "inherit"});
editorProcess.on("exit", (code: number) => {
this.lastExitStatus = code;
setImmediate(callback);
});
} catch (launchError) {
throw new LaunchEditorError(launchError);
}
} | type VoidCallback = () => void; |
550 | private launchEditorAsync(callback: VoidCallback) {
try {
const editorProcess = spawn(
this.editor.bin,
this.editor.args.concat([this.tempFile]),
{stdio: "inherit"});
editorProcess.on("exit", (code: number) => {
this.lastExitStatus = code;
setImmediate(callback);
});
} catch (launchError) {
throw new LaunchEditorError(launchError);
}
} | type VoidCallback = () => void; |
551 | runAsync(callback: StringCallback): void | type StringCallback = (err: Error, result: string) => void; |
552 | runAsync(callback: StringCallback): void | type StringCallback = (err: Error, result: string) => void; |
553 | new (settings: Settings) => Provider<T> | class Settings {
public readonly absolute: boolean = this._getValue(this._options.absolute, false);
public readonly baseNameMatch: boolean = this._getValue(this._options.baseNameMatch, false);
public readonly braceExpansion: boolean = this._getValue(this._options.braceExpansion, true);
public readonly caseSensitiveMatch: boolean = this._getValue(this._options.caseSensitiveMatch, true);
public readonly concurrency: number = this._getValue(this._options.concurrency, CPU_COUNT);
public readonly cwd: string = this._getValue(this._options.cwd, process.cwd());
public readonly deep: number = this._getValue(this._options.deep, Infinity);
public readonly dot: boolean = this._getValue(this._options.dot, false);
public readonly extglob: boolean = this._getValue(this._options.extglob, true);
public readonly followSymbolicLinks: boolean = this._getValue(this._options.followSymbolicLinks, true);
public readonly fs: FileSystemAdapter = this._getFileSystemMethods(this._options.fs);
public readonly globstar: boolean = this._getValue(this._options.globstar, true);
public readonly ignore: Pattern[] = this._getValue(this._options.ignore, [] as Pattern[]);
public readonly markDirectories: boolean = this._getValue(this._options.markDirectories, false);
public readonly objectMode: boolean = this._getValue(this._options.objectMode, false);
public readonly onlyDirectories: boolean = this._getValue(this._options.onlyDirectories, false);
public readonly onlyFiles: boolean = this._getValue(this._options.onlyFiles, true);
public readonly stats: boolean = this._getValue(this._options.stats, false);
public readonly suppressErrors: boolean = this._getValue(this._options.suppressErrors, false);
public readonly throwErrorOnBrokenSymbolicLink: boolean = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
public readonly unique: boolean = this._getValue(this._options.unique, true);
constructor(private readonly _options: Options = {}) {
if (this.onlyDirectories) {
this.onlyFiles = false;
}
if (this.stats) {
this.objectMode = true;
}
}
private _getValue<T>(option: T | undefined, value: T): T {
return option === undefined ? value : option;
}
private _getFileSystemMethods(methods: Partial<FileSystemAdapter> = {}): FileSystemAdapter {
return {
...DEFAULT_FILE_SYSTEM_ADAPTER,
...methods
};
}
} |
554 | (error: ErrnoException) => assert.fail(error) | type ErrnoException = NodeJS.ErrnoException; |
555 | constructor(private readonly _options: Options = {}) {
if (this.onlyDirectories) {
this.onlyFiles = false;
}
if (this.stats) {
this.objectMode = true;
}
} | type Options = OptionsInternal; |
556 | constructor(private readonly _options: Options = {}) {
if (this.onlyDirectories) {
this.onlyFiles = false;
}
if (this.stats) {
this.objectMode = true;
}
} | type Options = {
/**
* Return the absolute path for entries.
*
* @default false
*/
absolute?: boolean;
/**
* If set to `true`, then patterns without slashes will be matched against
* the basename of the path if it contains slashes.
*
* @default false
*/
baseNameMatch?: boolean;
/**
* Enables Bash-like brace expansion.
*
* @default true
*/
braceExpansion?: boolean;
/**
* Enables a case-sensitive mode for matching files.
*
* @default true
*/
caseSensitiveMatch?: boolean;
/**
* Specifies the maximum number of concurrent requests from a reader to read
* directories.
*
* @default os.cpus().length
*/
concurrency?: number;
/**
* The current working directory in which to search.
*
* @default process.cwd()
*/
cwd?: string;
/**
* Specifies the maximum depth of a read directory relative to the start
* directory.
*
* @default Infinity
*/
deep?: number;
/**
* Allow patterns to match entries that begin with a period (`.`).
*
* @default false
*/
dot?: boolean;
/**
* Enables Bash-like `extglob` functionality.
*
* @default true
*/
extglob?: boolean;
/**
* Indicates whether to traverse descendants of symbolic link directories.
*
* @default true
*/
followSymbolicLinks?: boolean;
/**
* Custom implementation of methods for working with the file system.
*
* @default fs.*
*/
fs?: Partial<FileSystemAdapter>;
/**
* Enables recursively repeats a pattern containing `**`.
* If `false`, `**` behaves exactly like `*`.
*
* @default true
*/
globstar?: boolean;
/**
* An array of glob patterns to exclude matches.
* This is an alternative way to use negative patterns.
*
* @default []
*/
ignore?: Pattern[];
/**
* Mark the directory path with the final slash.
*
* @default false
*/
markDirectories?: boolean;
/**
* Returns objects (instead of strings) describing entries.
*
* @default false
*/
objectMode?: boolean;
/**
* Return only directories.
*
* @default false
*/
onlyDirectories?: boolean;
/**
* Return only files.
*
* @default true
*/
onlyFiles?: boolean;
/**
* Enables an object mode (`objectMode`) with an additional `stats` field.
*
* @default false
*/
stats?: boolean;
/**
* By default this package suppress only `ENOENT` errors.
* Set to `true` to suppress any error.
*
* @default false
*/
suppressErrors?: boolean;
/**
* Throw an error when symbolic link is broken if `true` or safely
* return `lstat` call if `false`.
*
* @default false
*/
throwErrorOnBrokenSymbolicLink?: boolean;
/**
* Ensures that the returned entries are unique.
*
* @default true
*/
unique?: boolean;
}; |
557 | public report(reporter: Reporter, result: SuitePackResult): void {
reporter.row(result);
reporter.display();
} | type SuitePackResult = {
name: string;
errors: number;
entries: number;
retries: number;
measures: SuitePackMeasures;
}; |
558 | public report(reporter: Reporter, result: SuitePackResult): void {
reporter.row(result);
reporter.display();
} | class Reporter {
private readonly _table: Table = new Table();
private readonly _log: logUpdate.LogUpdate = logUpdate.create(process.stdout);
public row(result: SuitePackResult): void {
this._table.cell('Name', result.name);
this._table.cell(`Time, ${result.measures.time.units}`, this._formatMeasureValue(result.measures.time));
this._table.cell('Time stdev, %', this._formatMeasureStdevValue(result.measures.time));
this._table.cell(`Memory, ${result.measures.memory.units}`, this._formatMeasureValue(result.measures.memory));
this._table.cell('Memory stdev, %', this._formatMeasureStdevValue(result.measures.memory));
this._table.cell('Entries', result.entries);
this._table.cell('Errors', result.errors);
this._table.cell('Retries', result.retries);
this._table.newRow();
}
public format(): string {
return this._table.toString();
}
public display(): void {
if (!isCi) {
this._log(this.format());
}
}
public reset(): void {
if (isCi) {
console.log(this.format());
}
this._log.done();
}
private _formatMeasureValue(measure: Measure): string {
return this._formatMeasure(measure.average);
}
private _formatMeasureStdevValue(measure: Measure): string {
return this._formatMeasure(measure.stdev);
}
private _formatMeasure(value: number): string {
return value.toFixed(FRACTION_DIGITS);
}
} |
559 | public report(_: Reporter, result: SuitePackResult): void {
this.results.push(result);
} | type SuitePackResult = {
name: string;
errors: number;
entries: number;
retries: number;
measures: SuitePackMeasures;
}; |
560 | public report(_: Reporter, result: SuitePackResult): void {
this.results.push(result);
} | class Reporter {
private readonly _table: Table = new Table();
private readonly _log: logUpdate.LogUpdate = logUpdate.create(process.stdout);
public row(result: SuitePackResult): void {
this._table.cell('Name', result.name);
this._table.cell(`Time, ${result.measures.time.units}`, this._formatMeasureValue(result.measures.time));
this._table.cell('Time stdev, %', this._formatMeasureStdevValue(result.measures.time));
this._table.cell(`Memory, ${result.measures.memory.units}`, this._formatMeasureValue(result.measures.memory));
this._table.cell('Memory stdev, %', this._formatMeasureStdevValue(result.measures.memory));
this._table.cell('Entries', result.entries);
this._table.cell('Errors', result.errors);
this._table.cell('Retries', result.retries);
this._table.newRow();
}
public format(): string {
return this._table.toString();
}
public display(): void {
if (!isCi) {
this._log(this.format());
}
}
public reset(): void {
if (isCi) {
console.log(this.format());
}
this._log.done();
}
private _formatMeasureValue(measure: Measure): string {
return this._formatMeasure(measure.average);
}
private _formatMeasureStdevValue(measure: Measure): string {
return this._formatMeasure(measure.stdev);
}
private _formatMeasure(value: number): string {
return value.toFixed(FRACTION_DIGITS);
}
} |
561 | public row(result: SuitePackResult): void {
this._table.cell('Name', result.name);
this._table.cell(`Time, ${result.measures.time.units}`, this._formatMeasureValue(result.measures.time));
this._table.cell('Time stdev, %', this._formatMeasureStdevValue(result.measures.time));
this._table.cell(`Memory, ${result.measures.memory.units}`, this._formatMeasureValue(result.measures.memory));
this._table.cell('Memory stdev, %', this._formatMeasureStdevValue(result.measures.memory));
this._table.cell('Entries', result.entries);
this._table.cell('Errors', result.errors);
this._table.cell('Retries', result.retries);
this._table.newRow();
} | type SuitePackResult = {
name: string;
errors: number;
entries: number;
retries: number;
measures: SuitePackMeasures;
}; |
562 | private _formatMeasureValue(measure: Measure): string {
return this._formatMeasure(measure.average);
} | type Measure = {
units: string;
raw: number[];
average: number;
stdev: number;
}; |
563 | private _formatMeasureStdevValue(measure: Measure): string {
return this._formatMeasure(measure.stdev);
} | type Measure = {
units: string;
raw: number[];
average: number;
stdev: number;
}; |
564 | function isEnoentCodeError(error: ErrnoException): boolean {
return error.code === 'ENOENT';
} | type ErrnoException = NodeJS.ErrnoException; |
565 | function escape(pattern: Pattern): Pattern {
return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
} | type Pattern = string; |
566 | function isStaticPattern(pattern: Pattern, options: PatternTypeOptions = {}): boolean {
return !isDynamicPattern(pattern, options);
} | type PatternTypeOptions = {
braceExpansion?: boolean;
caseSensitiveMatch?: boolean;
extglob?: boolean;
}; |
567 | function isStaticPattern(pattern: Pattern, options: PatternTypeOptions = {}): boolean {
return !isDynamicPattern(pattern, options);
} | type Pattern = string; |
568 | function isDynamicPattern(pattern: Pattern, options: PatternTypeOptions = {}): boolean {
/**
* A special case with an empty string is necessary for matching patterns that start with a forward slash.
* An empty string cannot be a dynamic pattern.
* For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
*/
if (pattern === '') {
return false;
}
/**
* When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
* filepath directly (without read directory).
*/
if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
return true;
}
if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
return true;
}
if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
return true;
}
if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
return true;
}
return false;
} | type PatternTypeOptions = {
braceExpansion?: boolean;
caseSensitiveMatch?: boolean;
extglob?: boolean;
}; |
569 | function isDynamicPattern(pattern: Pattern, options: PatternTypeOptions = {}): boolean {
/**
* A special case with an empty string is necessary for matching patterns that start with a forward slash.
* An empty string cannot be a dynamic pattern.
* For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
*/
if (pattern === '') {
return false;
}
/**
* When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
* filepath directly (without read directory).
*/
if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
return true;
}
if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
return true;
}
if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
return true;
}
if (options.braceExpansion !== false && hasBraceExpansion(pattern)) {
return true;
}
return false;
} | type Pattern = string; |
570 | function convertToPositivePattern(pattern: Pattern): Pattern {
return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
} | type Pattern = string; |
571 | function convertToNegativePattern(pattern: Pattern): Pattern {
return '!' + pattern;
} | type Pattern = string; |
572 | function isNegativePattern(pattern: Pattern): boolean {
return pattern.startsWith('!') && pattern[1] !== '(';
} | type Pattern = string; |
573 | function isPositivePattern(pattern: Pattern): boolean {
return !isNegativePattern(pattern);
} | type Pattern = string; |
574 | function isPatternRelatedToParentDirectory(pattern: Pattern): boolean {
return pattern.startsWith('..') || pattern.startsWith('./..');
} | type Pattern = string; |
575 | function getBaseDirectory(pattern: Pattern): string {
return globParent(pattern, { flipBackslashes: false });
} | type Pattern = string; |
576 | function hasGlobStar(pattern: Pattern): boolean {
return pattern.includes(GLOBSTAR);
} | type Pattern = string; |
577 | function endsWithSlashGlobStar(pattern: Pattern): boolean {
return pattern.endsWith('/' + GLOBSTAR);
} | type Pattern = string; |
578 | function isAffectDepthOfReadingPattern(pattern: Pattern): boolean {
const basename = path.basename(pattern);
return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
} | type Pattern = string; |
579 | function expandBraceExpansion(pattern: Pattern): Pattern[] {
return micromatch.braces(pattern, {
expand: true,
nodupes: true
});
} | type Pattern = string; |
580 | function getPatternParts(pattern: Pattern, options: MicromatchOptions): Pattern[] {
let { parts } = micromatch.scan(pattern, {
...options,
parts: true
});
/**
* The scan method returns an empty array in some cases.
* See micromatch/picomatch#58 for more details.
*/
if (parts.length === 0) {
parts = [pattern];
}
/**
* The scan method does not return an empty part for the pattern with a forward slash.
* This is another part of micromatch/picomatch#58.
*/
if (parts[0].startsWith('/')) {
parts[0] = parts[0].slice(1);
parts.unshift('');
}
return parts;
} | type Pattern = string; |
581 | function getPatternParts(pattern: Pattern, options: MicromatchOptions): Pattern[] {
let { parts } = micromatch.scan(pattern, {
...options,
parts: true
});
/**
* The scan method returns an empty array in some cases.
* See micromatch/picomatch#58 for more details.
*/
if (parts.length === 0) {
parts = [pattern];
}
/**
* The scan method does not return an empty part for the pattern with a forward slash.
* This is another part of micromatch/picomatch#58.
*/
if (parts[0].startsWith('/')) {
parts[0] = parts[0].slice(1);
parts.unshift('');
}
return parts;
} | type MicromatchOptions = {
dot?: boolean;
matchBase?: boolean;
nobrace?: boolean;
nocase?: boolean;
noext?: boolean;
noglobstar?: boolean;
posix?: boolean;
strictSlashes?: boolean;
}; |
582 | function makeRe(pattern: Pattern, options: MicromatchOptions): PatternRe {
return micromatch.makeRe(pattern, options);
} | type Pattern = string; |
583 | function makeRe(pattern: Pattern, options: MicromatchOptions): PatternRe {
return micromatch.makeRe(pattern, options);
} | type MicromatchOptions = {
dot?: boolean;
matchBase?: boolean;
nobrace?: boolean;
nocase?: boolean;
noext?: boolean;
noglobstar?: boolean;
posix?: boolean;
strictSlashes?: boolean;
}; |
584 | public pattern(pattern: Pattern): this {
this._segment.pattern = pattern;
return this;
} | type Pattern = string; |
585 | public build(options: MicromatchOptions = {}): PatternSegment {
if (!this._segment.dynamic) {
return this._segment;
}
return {
...this._segment,
patternRe: utils.pattern.makeRe(this._segment.pattern, options)
};
} | type MicromatchOptions = {
dot?: boolean;
matchBase?: boolean;
nobrace?: boolean;
nocase?: boolean;
noext?: boolean;
noglobstar?: boolean;
posix?: boolean;
strictSlashes?: boolean;
}; |
586 | public positive(pattern: Pattern): this {
this._task.patterns.push(pattern);
this._task.positive.push(pattern);
return this;
} | type Pattern = string; |
587 | public negative(pattern: Pattern): this {
this._task.patterns.push(`!${pattern}`);
this._task.negative.push(pattern);
return this;
} | type Pattern = string; |
588 | function getTestCaseTitle(test: SmokeTest): string {
let title = `pattern: '${test.pattern}'`;
if (test.ignore !== undefined) {
title += `, ignore: '${test.ignore}'`;
}
if (test.broken !== undefined) {
title += ` (broken - ${test.issue})`;
}
if (test.correct !== undefined) {
title += ' (correct)';
}
return title;
} | type SmokeTest = {
pattern: Pattern;
ignore?: Pattern;
cwd?: string;
globOptions?: glob.IOptions;
globFilter?: (entry: string, filepath: string) => boolean;
globTransform?: (entry: string) => string;
fgOptions?: Options;
/**
* Allow to run only one test case with debug information.
*/
debug?: boolean;
/**
* Mark test case as broken. This is requires a issue to repair.
*/
broken?: boolean;
issue?: number | number[];
/**
* Mark test case as correct. This is requires a reason why is true.
*/
correct?: boolean;
reason?: string;
/**
* The ability to conditionally run the test.
*/
condition?: () => boolean;
}; |
589 | function getTestCaseMochaDefinition(test: SmokeTest): MochaDefinition {
if (test.debug === true) {
return it.only;
}
if (test.condition?.() === false) {
return it.skip;
}
return it;
} | type SmokeTest = {
pattern: Pattern;
ignore?: Pattern;
cwd?: string;
globOptions?: glob.IOptions;
globFilter?: (entry: string, filepath: string) => boolean;
globTransform?: (entry: string) => string;
fgOptions?: Options;
/**
* Allow to run only one test case with debug information.
*/
debug?: boolean;
/**
* Mark test case as broken. This is requires a issue to repair.
*/
broken?: boolean;
issue?: number | number[];
/**
* Mark test case as correct. This is requires a reason why is true.
*/
correct?: boolean;
reason?: string;
/**
* The ability to conditionally run the test.
*/
condition?: () => boolean;
}; |
590 | async function testCaseRunner(test: SmokeTest, func: typeof getFastGlobEntriesSync | typeof getFastGlobEntriesAsync): Promise<void> {
const expected = getNodeGlobEntries(test);
const actual = await func(test.pattern, test.ignore, test.cwd, test.fgOptions);
if (test.debug === true) {
const report = generateDebugReport(expected, actual);
console.log(report);
}
if (test.broken === true && test.issue === undefined) {
assert.fail("This test is marked as «broken», but it doesn't have a issue key.");
}
if (test.correct === true && test.reason === undefined) {
assert.fail("This test is marked as «correct», but it doesn't have a reason.");
}
const isInvertedTest = test.broken === true || test.correct === true;
const assertAction: typeof assert.deepStrictEqual = isInvertedTest ? assert.notDeepStrictEqual : assert.deepStrictEqual;
assertAction(actual, expected);
} | type SmokeTest = {
pattern: Pattern;
ignore?: Pattern;
cwd?: string;
globOptions?: glob.IOptions;
globFilter?: (entry: string, filepath: string) => boolean;
globTransform?: (entry: string) => string;
fgOptions?: Options;
/**
* Allow to run only one test case with debug information.
*/
debug?: boolean;
/**
* Mark test case as broken. This is requires a issue to repair.
*/
broken?: boolean;
issue?: number | number[];
/**
* Mark test case as correct. This is requires a reason why is true.
*/
correct?: boolean;
reason?: string;
/**
* The ability to conditionally run the test.
*/
condition?: () => boolean;
}; |
591 | function getNodeGlobEntries(options: SmokeTest): string[] {
const pattern = options.pattern;
const cwd = options.cwd === undefined ? process.cwd() : options.cwd;
const ignore = options.ignore === undefined ? [] : [options.ignore];
const globFilter = options.globFilter;
const globTransform = options.globTransform;
let entries = glob.sync(pattern, { cwd, ignore, ...options.globOptions });
if (globFilter !== undefined) {
entries = entries.filter((entry) => {
const filepath = path.join(cwd, entry);
return globFilter(entry, filepath);
});
}
if (globTransform !== undefined) {
entries = entries.map((entry) => globTransform(entry));
}
entries.sort((a, b) => a.localeCompare(b));
return entries;
} | type SmokeTest = {
pattern: Pattern;
ignore?: Pattern;
cwd?: string;
globOptions?: glob.IOptions;
globFilter?: (entry: string, filepath: string) => boolean;
globTransform?: (entry: string) => string;
fgOptions?: Options;
/**
* Allow to run only one test case with debug information.
*/
debug?: boolean;
/**
* Mark test case as broken. This is requires a issue to repair.
*/
broken?: boolean;
issue?: number | number[];
/**
* Mark test case as correct. This is requires a reason why is true.
*/
correct?: boolean;
reason?: string;
/**
* The ability to conditionally run the test.
*/
condition?: () => boolean;
}; |
592 | function getFastGlobEntriesSync(pattern: Pattern, ignore?: Pattern, cwd?: string, options?: Options): string[] {
return fg.sync(pattern, getFastGlobOptions(ignore, cwd, options)).sort((a, b) => a.localeCompare(b));
} | type Pattern = string; |
593 | function getFastGlobEntriesSync(pattern: Pattern, ignore?: Pattern, cwd?: string, options?: Options): string[] {
return fg.sync(pattern, getFastGlobOptions(ignore, cwd, options)).sort((a, b) => a.localeCompare(b));
} | type Options = OptionsInternal; |
594 | function getFastGlobEntriesSync(pattern: Pattern, ignore?: Pattern, cwd?: string, options?: Options): string[] {
return fg.sync(pattern, getFastGlobOptions(ignore, cwd, options)).sort((a, b) => a.localeCompare(b));
} | type Options = {
/**
* Return the absolute path for entries.
*
* @default false
*/
absolute?: boolean;
/**
* If set to `true`, then patterns without slashes will be matched against
* the basename of the path if it contains slashes.
*
* @default false
*/
baseNameMatch?: boolean;
/**
* Enables Bash-like brace expansion.
*
* @default true
*/
braceExpansion?: boolean;
/**
* Enables a case-sensitive mode for matching files.
*
* @default true
*/
caseSensitiveMatch?: boolean;
/**
* Specifies the maximum number of concurrent requests from a reader to read
* directories.
*
* @default os.cpus().length
*/
concurrency?: number;
/**
* The current working directory in which to search.
*
* @default process.cwd()
*/
cwd?: string;
/**
* Specifies the maximum depth of a read directory relative to the start
* directory.
*
* @default Infinity
*/
deep?: number;
/**
* Allow patterns to match entries that begin with a period (`.`).
*
* @default false
*/
dot?: boolean;
/**
* Enables Bash-like `extglob` functionality.
*
* @default true
*/
extglob?: boolean;
/**
* Indicates whether to traverse descendants of symbolic link directories.
*
* @default true
*/
followSymbolicLinks?: boolean;
/**
* Custom implementation of methods for working with the file system.
*
* @default fs.*
*/
fs?: Partial<FileSystemAdapter>;
/**
* Enables recursively repeats a pattern containing `**`.
* If `false`, `**` behaves exactly like `*`.
*
* @default true
*/
globstar?: boolean;
/**
* An array of glob patterns to exclude matches.
* This is an alternative way to use negative patterns.
*
* @default []
*/
ignore?: Pattern[];
/**
* Mark the directory path with the final slash.
*
* @default false
*/
markDirectories?: boolean;
/**
* Returns objects (instead of strings) describing entries.
*
* @default false
*/
objectMode?: boolean;
/**
* Return only directories.
*
* @default false
*/
onlyDirectories?: boolean;
/**
* Return only files.
*
* @default true
*/
onlyFiles?: boolean;
/**
* Enables an object mode (`objectMode`) with an additional `stats` field.
*
* @default false
*/
stats?: boolean;
/**
* By default this package suppress only `ENOENT` errors.
* Set to `true` to suppress any error.
*
* @default false
*/
suppressErrors?: boolean;
/**
* Throw an error when symbolic link is broken if `true` or safely
* return `lstat` call if `false`.
*
* @default false
*/
throwErrorOnBrokenSymbolicLink?: boolean;
/**
* Ensures that the returned entries are unique.
*
* @default true
*/
unique?: boolean;
}; |
595 | function getFastGlobEntriesAsync(pattern: Pattern, ignore?: Pattern, cwd?: string, options?: Options): Promise<string[]> {
return fg(pattern, getFastGlobOptions(ignore, cwd, options)).then((entries) => {
entries.sort((a, b) => a.localeCompare(b));
return entries;
});
} | type Pattern = string; |
596 | function getFastGlobEntriesAsync(pattern: Pattern, ignore?: Pattern, cwd?: string, options?: Options): Promise<string[]> {
return fg(pattern, getFastGlobOptions(ignore, cwd, options)).then((entries) => {
entries.sort((a, b) => a.localeCompare(b));
return entries;
});
} | type Options = OptionsInternal; |
597 | function getFastGlobEntriesAsync(pattern: Pattern, ignore?: Pattern, cwd?: string, options?: Options): Promise<string[]> {
return fg(pattern, getFastGlobOptions(ignore, cwd, options)).then((entries) => {
entries.sort((a, b) => a.localeCompare(b));
return entries;
});
} | type Options = {
/**
* Return the absolute path for entries.
*
* @default false
*/
absolute?: boolean;
/**
* If set to `true`, then patterns without slashes will be matched against
* the basename of the path if it contains slashes.
*
* @default false
*/
baseNameMatch?: boolean;
/**
* Enables Bash-like brace expansion.
*
* @default true
*/
braceExpansion?: boolean;
/**
* Enables a case-sensitive mode for matching files.
*
* @default true
*/
caseSensitiveMatch?: boolean;
/**
* Specifies the maximum number of concurrent requests from a reader to read
* directories.
*
* @default os.cpus().length
*/
concurrency?: number;
/**
* The current working directory in which to search.
*
* @default process.cwd()
*/
cwd?: string;
/**
* Specifies the maximum depth of a read directory relative to the start
* directory.
*
* @default Infinity
*/
deep?: number;
/**
* Allow patterns to match entries that begin with a period (`.`).
*
* @default false
*/
dot?: boolean;
/**
* Enables Bash-like `extglob` functionality.
*
* @default true
*/
extglob?: boolean;
/**
* Indicates whether to traverse descendants of symbolic link directories.
*
* @default true
*/
followSymbolicLinks?: boolean;
/**
* Custom implementation of methods for working with the file system.
*
* @default fs.*
*/
fs?: Partial<FileSystemAdapter>;
/**
* Enables recursively repeats a pattern containing `**`.
* If `false`, `**` behaves exactly like `*`.
*
* @default true
*/
globstar?: boolean;
/**
* An array of glob patterns to exclude matches.
* This is an alternative way to use negative patterns.
*
* @default []
*/
ignore?: Pattern[];
/**
* Mark the directory path with the final slash.
*
* @default false
*/
markDirectories?: boolean;
/**
* Returns objects (instead of strings) describing entries.
*
* @default false
*/
objectMode?: boolean;
/**
* Return only directories.
*
* @default false
*/
onlyDirectories?: boolean;
/**
* Return only files.
*
* @default true
*/
onlyFiles?: boolean;
/**
* Enables an object mode (`objectMode`) with an additional `stats` field.
*
* @default false
*/
stats?: boolean;
/**
* By default this package suppress only `ENOENT` errors.
* Set to `true` to suppress any error.
*
* @default false
*/
suppressErrors?: boolean;
/**
* Throw an error when symbolic link is broken if `true` or safely
* return `lstat` call if `false`.
*
* @default false
*/
throwErrorOnBrokenSymbolicLink?: boolean;
/**
* Ensures that the returned entries are unique.
*
* @default true
*/
unique?: boolean;
}; |
598 | function getFastGlobEntriesStream(pattern: Pattern, ignore?: Pattern, cwd?: string, options?: Options): Promise<string[]> {
const entries: string[] = [];
const stream = fg.stream(pattern, getFastGlobOptions(ignore, cwd, options));
return new Promise((resolve, reject) => {
stream.on('data', (entry: string) => entries.push(entry));
stream.once('error', reject);
stream.once('end', () => {
entries.sort((a, b) => a.localeCompare(b));
resolve(entries);
});
});
} | type Pattern = string; |
599 | function getFastGlobEntriesStream(pattern: Pattern, ignore?: Pattern, cwd?: string, options?: Options): Promise<string[]> {
const entries: string[] = [];
const stream = fg.stream(pattern, getFastGlobOptions(ignore, cwd, options));
return new Promise((resolve, reject) => {
stream.on('data', (entry: string) => entries.push(entry));
stream.once('error', reject);
stream.once('end', () => {
entries.sort((a, b) => a.localeCompare(b));
resolve(entries);
});
});
} | type Options = OptionsInternal; |