Deployed the page to Github Pages.

This commit is contained in:
Batuhan Berk Başoğlu 2024-11-03 21:30:09 -05:00
parent 1d79754e93
commit 2c89899458
Signed by: batuhan-basoglu
SSH key fingerprint: SHA256:kEsnuHX+qbwhxSAXPUQ4ox535wFHu/hIRaa53FzxRpo
62797 changed files with 6551425 additions and 15279 deletions

2
node_modules/ts-node/dist/bin-script-deprecated.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};

7
node_modules/ts-node/dist/bin-script-deprecated.js generated vendored Executable file
View file

@ -0,0 +1,7 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bin_1 = require("./bin");
console.warn('ts-script has been deprecated and will be removed in the next major release.', 'Please use ts-node-script instead');
bin_1.main(['--script-mode', ...process.argv.slice(2)]);
//# sourceMappingURL=bin-script-deprecated.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"bin-script-deprecated.js","sourceRoot":"","sources":["../src/bin-script-deprecated.ts"],"names":[],"mappings":";;;AAEA,+BAA4B;AAE5B,OAAO,CAAC,IAAI,CACV,8EAA8E,EAC9E,mCAAmC,CACpC,CAAA;AAED,UAAI,CAAC,CAAC,eAAe,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA","sourcesContent":["#!/usr/bin/env node\n\nimport { main } from './bin'\n\nconsole.warn(\n 'ts-script has been deprecated and will be removed in the next major release.',\n 'Please use ts-node-script instead'\n)\n\nmain(['--script-mode', ...process.argv.slice(2)])\n"]}

2
node_modules/ts-node/dist/bin-script.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};

6
node_modules/ts-node/dist/bin-script.js generated vendored Executable file
View file

@ -0,0 +1,6 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bin_1 = require("./bin");
bin_1.main(['--script-mode', ...process.argv.slice(2)]);
//# sourceMappingURL=bin-script.js.map

1
node_modules/ts-node/dist/bin-script.js.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"bin-script.js","sourceRoot":"","sources":["../src/bin-script.ts"],"names":[],"mappings":";;;AAEA,+BAA4B;AAE5B,UAAI,CAAC,CAAC,eAAe,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA","sourcesContent":["#!/usr/bin/env node\n\nimport { main } from './bin'\n\nmain(['--script-mode', ...process.argv.slice(2)])\n"]}

2
node_modules/ts-node/dist/bin-transpile.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};

6
node_modules/ts-node/dist/bin-transpile.js generated vendored Executable file
View file

@ -0,0 +1,6 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bin_1 = require("./bin");
bin_1.main(['--transpile-only', ...process.argv.slice(2)]);
//# sourceMappingURL=bin-transpile.js.map

1
node_modules/ts-node/dist/bin-transpile.js.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"bin-transpile.js","sourceRoot":"","sources":["../src/bin-transpile.ts"],"names":[],"mappings":";;;AAEA,+BAA4B;AAE5B,UAAI,CAAC,CAAC,kBAAkB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA","sourcesContent":["#!/usr/bin/env node\n\nimport { main } from './bin'\n\nmain(['--transpile-only', ...process.argv.slice(2)])\n"]}

5
node_modules/ts-node/dist/bin.d.ts generated vendored Normal file
View file

@ -0,0 +1,5 @@
#!/usr/bin/env node
/**
* Main `bin` functionality.
*/
export declare function main(argv: string[]): void;

450
node_modules/ts-node/dist/bin.js generated vendored Executable file
View file

@ -0,0 +1,450 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.main = void 0;
const path_1 = require("path");
const repl_1 = require("repl");
const util_1 = require("util");
const Module = require("module");
const arg = require("arg");
const diff_1 = require("diff");
const vm_1 = require("vm");
const fs_1 = require("fs");
const os_1 = require("os");
const index_1 = require("./index");
/**
* Eval filename for REPL/debug.
*/
const EVAL_FILENAME = `[eval].ts`;
/**
* Eval state management.
*/
class EvalState {
constructor(path) {
this.path = path;
this.input = '';
this.output = '';
this.version = 0;
this.lines = 0;
}
}
/**
* Main `bin` functionality.
*/
function main(argv) {
const args = arg({
// Node.js-like options.
'--eval': String,
'--interactive': Boolean,
'--print': Boolean,
'--require': [String],
// CLI options.
'--help': Boolean,
'--script-mode': Boolean,
'--version': arg.COUNT,
// Project options.
'--dir': String,
'--files': Boolean,
'--compiler': String,
'--compiler-options': index_1.parse,
'--project': String,
'--ignore-diagnostics': [String],
'--ignore': [String],
'--transpile-only': Boolean,
'--type-check': Boolean,
'--compiler-host': Boolean,
'--pretty': Boolean,
'--skip-project': Boolean,
'--skip-ignore': Boolean,
'--prefer-ts-exts': Boolean,
'--log-error': Boolean,
'--emit': Boolean,
// Aliases.
'-e': '--eval',
'-i': '--interactive',
'-p': '--print',
'-r': '--require',
'-h': '--help',
'-s': '--script-mode',
'-v': '--version',
'-T': '--transpile-only',
'-H': '--compiler-host',
'-I': '--ignore',
'-P': '--project',
'-C': '--compiler',
'-D': '--ignore-diagnostics',
'-O': '--compiler-options'
}, {
argv,
stopAtPositional: true
});
// Only setting defaults for CLI-specific flags
// Anything passed to `register()` can be `undefined`; `create()` will apply
// defaults.
const { '--dir': dir, '--help': help = false, '--script-mode': scriptMode = false, '--version': version = 0, '--require': argsRequire = [], '--eval': code = undefined, '--print': print = false, '--interactive': interactive = false, '--files': files, '--compiler': compiler, '--compiler-options': compilerOptions, '--project': project, '--ignore-diagnostics': ignoreDiagnostics, '--ignore': ignore, '--transpile-only': transpileOnly, '--type-check': typeCheck, '--compiler-host': compilerHost, '--pretty': pretty, '--skip-project': skipProject, '--skip-ignore': skipIgnore, '--prefer-ts-exts': preferTsExts, '--log-error': logError, '--emit': emit } = args;
if (help) {
console.log(`
Usage: ts-node [options] [ -e script | script.ts ] [arguments]
Options:
-e, --eval [code] Evaluate code
-p, --print Print result of \`--eval\`
-r, --require [path] Require a node module before execution
-i, --interactive Opens the REPL even if stdin does not appear to be a terminal
-h, --help Print CLI usage
-v, --version Print module version information
-s, --script-mode Use cwd from <script.ts> instead of current directory
-T, --transpile-only Use TypeScript's faster \`transpileModule\`
-H, --compiler-host Use TypeScript's compiler host API
-I, --ignore [pattern] Override the path patterns to skip compilation
-P, --project [path] Path to TypeScript JSON project file
-C, --compiler [name] Specify a custom TypeScript compiler
-D, --ignore-diagnostics [code] Ignore TypeScript warnings by diagnostic code
-O, --compiler-options [opts] JSON object to merge with compiler options
--dir Specify working directory for config resolution
--scope Scope compiler to files within \`cwd\` only
--files Load \`files\`, \`include\` and \`exclude\` from \`tsconfig.json\` on startup
--pretty Use pretty diagnostic formatter (usually enabled by default)
--skip-project Skip reading \`tsconfig.json\`
--skip-ignore Skip \`--ignore\` checks
--prefer-ts-exts Prefer importing TypeScript files over JavaScript files
--log-error Logs TypeScript errors to stderr instead of throwing exceptions
`);
process.exit(0);
}
// Output project information.
if (version === 1) {
console.log(`v${index_1.VERSION}`);
process.exit(0);
}
const cwd = dir || process.cwd();
/** Unresolved. May point to a symlink, not realpath. May be missing file extension */
const scriptPath = args._.length ? path_1.resolve(cwd, args._[0]) : undefined;
const state = new EvalState(scriptPath || path_1.join(cwd, EVAL_FILENAME));
// Register the TypeScript compiler instance.
const service = index_1.register({
dir: getCwd(dir, scriptMode, scriptPath),
emit,
files,
pretty,
transpileOnly,
typeCheck,
compilerHost,
ignore,
preferTsExts,
logError,
project,
skipProject,
skipIgnore,
compiler,
ignoreDiagnostics,
compilerOptions,
require: argsRequire,
readFile: code !== undefined
? (path) => {
if (path === state.path)
return state.input;
try {
return fs_1.readFileSync(path, 'utf8');
}
catch (err) { /* Ignore. */ }
}
: undefined,
fileExists: code !== undefined
? (path) => {
if (path === state.path)
return true;
try {
const stats = fs_1.statSync(path);
return stats.isFile() || stats.isFIFO();
}
catch (err) {
return false;
}
}
: undefined
});
// Output project information.
if (version >= 2) {
console.log(`ts-node v${index_1.VERSION}`);
console.log(`node ${process.version}`);
console.log(`compiler v${service.ts.version}`);
process.exit(0);
}
// Create a local module instance based on `cwd`.
const module = new Module(state.path);
module.filename = state.path;
module.paths = Module._nodeModulePaths(cwd);
// Prepend `ts-node` arguments to CLI for child processes.
process.execArgv.unshift(__filename, ...process.argv.slice(2, process.argv.length - args._.length));
process.argv = [process.argv[1]].concat(scriptPath || []).concat(args._.slice(1));
// Execute the main contents (either eval, script or piped).
if (code !== undefined && !interactive) {
evalAndExit(service, state, module, code, print);
}
else {
if (args._.length) {
Module.runMain();
}
else {
// Piping of execution _only_ occurs when no other script is specified.
// --interactive flag forces REPL
if (interactive || process.stdin.isTTY) {
startRepl(service, state, code);
}
else {
let buffer = code || '';
process.stdin.on('data', (chunk) => buffer += chunk);
process.stdin.on('end', () => evalAndExit(service, state, module, buffer, print));
}
}
}
}
exports.main = main;
/**
* Get project path from args.
*/
function getCwd(dir, scriptMode, scriptPath) {
// Validate `--script-mode` usage is correct.
if (scriptMode) {
if (!scriptPath) {
throw new TypeError('Script mode must be used with a script name, e.g. `ts-node -s <script.ts>`');
}
if (dir) {
throw new TypeError('Script mode cannot be combined with `--dir`');
}
// Use node's own resolution behavior to ensure we follow symlinks.
// scriptPath may omit file extension or point to a directory with or without package.json.
// This happens before we are registered, so we tell node's resolver to consider ts, tsx, and jsx files.
// In extremely rare cases, is is technically possible to resolve the wrong directory,
// because we do not yet know preferTsExts, jsx, nor allowJs.
// See also, justification why this will not happen in real-world situations:
// https://github.com/TypeStrong/ts-node/pull/1009#issuecomment-613017081
const exts = ['.js', '.jsx', '.ts', '.tsx'];
const extsTemporarilyInstalled = [];
for (const ext of exts) {
if (!hasOwnProperty(require.extensions, ext)) { // tslint:disable-line
extsTemporarilyInstalled.push(ext);
require.extensions[ext] = function () { }; // tslint:disable-line
}
}
try {
return path_1.dirname(require.resolve(scriptPath));
}
finally {
for (const ext of extsTemporarilyInstalled) {
delete require.extensions[ext]; // tslint:disable-line
}
}
}
return dir;
}
/**
* Evaluate a script.
*/
function evalAndExit(service, state, module, code, isPrinted) {
let result;
global.__filename = module.filename;
global.__dirname = path_1.dirname(module.filename);
global.exports = module.exports;
global.module = module;
global.require = module.require.bind(module);
try {
result = _eval(service, state, code);
}
catch (error) {
if (error instanceof index_1.TSError) {
console.error(error);
process.exit(1);
}
throw error;
}
if (isPrinted) {
console.log(typeof result === 'string' ? result : util_1.inspect(result));
}
}
/**
* Evaluate the code snippet.
*/
function _eval(service, state, input) {
const lines = state.lines;
const isCompletion = !/\n$/.test(input);
const undo = appendEval(state, input);
let output;
try {
output = service.compile(state.input, state.path, -lines);
}
catch (err) {
undo();
throw err;
}
// Use `diff` to check for new JavaScript to execute.
const changes = diff_1.diffLines(state.output, output);
if (isCompletion) {
undo();
}
else {
state.output = output;
}
return changes.reduce((result, change) => {
return change.added ? exec(change.value, state.path) : result;
}, undefined);
}
/**
* Execute some code.
*/
function exec(code, filename) {
const script = new vm_1.Script(code, { filename: filename });
return script.runInThisContext();
}
/**
* Start a CLI REPL.
*/
function startRepl(service, state, code) {
// Eval incoming code before the REPL starts.
if (code) {
try {
_eval(service, state, `${code}\n`);
}
catch (err) {
console.error(err);
process.exit(1);
}
}
const repl = repl_1.start({
prompt: '> ',
input: process.stdin,
output: process.stdout,
// Mimicking node's REPL implementation: https://github.com/nodejs/node/blob/168b22ba073ee1cbf8d0bcb4ded7ff3099335d04/lib/internal/repl.js#L28-L30
terminal: process.stdout.isTTY && !parseInt(process.env.NODE_NO_READLINE, 10),
eval: replEval,
useGlobal: true
});
/**
* Eval code from the REPL.
*/
function replEval(code, _context, _filename, callback) {
let err = null;
let result;
// TODO: Figure out how to handle completion here.
if (code === '.scope') {
callback(err);
return;
}
try {
result = _eval(service, state, code);
}
catch (error) {
if (error instanceof index_1.TSError) {
// Support recoverable compilations using >= node 6.
if (repl_1.Recoverable && isRecoverable(error)) {
err = new repl_1.Recoverable(error);
}
else {
console.error(error);
}
}
else {
err = error;
}
}
return callback(err, result);
}
// Bookmark the point where we should reset the REPL state.
const resetEval = appendEval(state, '');
function reset() {
resetEval();
// Hard fix for TypeScript forcing `Object.defineProperty(exports, ...)`.
exec('exports = module.exports', state.path);
}
reset();
repl.on('reset', reset);
repl.defineCommand('type', {
help: 'Check the type of a TypeScript identifier',
action: function (identifier) {
if (!identifier) {
repl.displayPrompt();
return;
}
const undo = appendEval(state, identifier);
const { name, comment } = service.getTypeInfo(state.input, state.path, state.input.length);
undo();
if (name)
repl.outputStream.write(`${name}\n`);
if (comment)
repl.outputStream.write(`${comment}\n`);
repl.displayPrompt();
}
});
// Set up REPL history when available natively via node.js >= 11.
if (repl.setupHistory) {
const historyPath = process.env.TS_NODE_HISTORY || path_1.join(os_1.homedir(), '.ts_node_repl_history');
repl.setupHistory(historyPath, err => {
if (!err)
return;
console.error(err);
process.exit(1);
});
}
}
/**
* Append to the eval instance and return an undo function.
*/
function appendEval(state, input) {
const undoInput = state.input;
const undoVersion = state.version;
const undoOutput = state.output;
const undoLines = state.lines;
// Handle ASI issues with TypeScript re-evaluation.
if (undoInput.charAt(undoInput.length - 1) === '\n' && /^\s*[\/\[(`-]/.test(input) && !/;\s*$/.test(undoInput)) {
state.input = `${state.input.slice(0, -1)};\n`;
}
state.input += input;
state.lines += lineCount(input);
state.version++;
return function () {
state.input = undoInput;
state.output = undoOutput;
state.version = undoVersion;
state.lines = undoLines;
};
}
/**
* Count the number of lines.
*/
function lineCount(value) {
let count = 0;
for (const char of value) {
if (char === '\n') {
count++;
}
}
return count;
}
const RECOVERY_CODES = new Set([
1003,
1005,
1109,
1126,
1160,
1161,
2355 // "A function whose declared type is neither 'void' nor 'any' must return a value."
]);
/**
* Check if a function can recover gracefully.
*/
function isRecoverable(error) {
return error.diagnosticCodes.every(code => RECOVERY_CODES.has(code));
}
/** Safe `hasOwnProperty` */
function hasOwnProperty(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
}
if (require.main === module) {
main(process.argv.slice(2));
}
//# sourceMappingURL=bin.js.map

1
node_modules/ts-node/dist/bin.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

18
node_modules/ts-node/dist/esm.d.ts generated vendored Normal file
View file

@ -0,0 +1,18 @@
/// <reference types="node" />
import { RegisterOptions } from './index';
export declare function registerAndCreateEsmHooks(opts?: RegisterOptions): {
resolve: (specifier: string, context: {
parentURL: string;
}, defaultResolve: any) => Promise<{
url: string;
}>;
getFormat: (url: string, context: {}, defaultGetFormat: any) => Promise<{
format: "json" | "module" | "builtin" | "commonjs" | "dynamic" | "wasm";
}>;
transformSource: (source: string | Buffer, context: {
url: string;
format: "json" | "module" | "builtin" | "commonjs" | "dynamic" | "wasm";
}, defaultTransformSource: any) => Promise<{
source: string | Buffer;
}>;
};

90
node_modules/ts-node/dist/esm.js generated vendored Normal file
View file

@ -0,0 +1,90 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerAndCreateEsmHooks = void 0;
const index_1 = require("./index");
const url_1 = require("url");
const path_1 = require("path");
const assert = require("assert");
const { createResolve } = require('../dist-raw/node-esm-resolve-implementation');
// Note: On Windows, URLs look like this: file:///D:/dev/@TypeStrong/ts-node-examples/foo.ts
function registerAndCreateEsmHooks(opts) {
// Automatically performs registration just like `-r ts-node/register`
const tsNodeInstance = index_1.register(Object.assign(Object.assign({}, opts), { experimentalEsmLoader: true }));
// Custom implementation that considers additional file extensions and automatically adds file extensions
const nodeResolveImplementation = createResolve(Object.assign(Object.assign({}, index_1.getExtensions(tsNodeInstance.config)), { preferTsExts: tsNodeInstance.options.preferTsExts }));
return { resolve, getFormat, transformSource };
function isFileUrlOrNodeStyleSpecifier(parsed) {
// We only understand file:// URLs, but in node, the specifier can be a node-style `./foo` or `foo`
const { protocol } = parsed;
return protocol === null || protocol === 'file:';
}
function resolve(specifier, context, defaultResolve) {
return __awaiter(this, void 0, void 0, function* () {
const defer = () => __awaiter(this, void 0, void 0, function* () {
const r = yield defaultResolve(specifier, context, defaultResolve);
return r;
});
const parsed = url_1.parse(specifier);
const { pathname, protocol, hostname } = parsed;
if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
return defer();
}
if (protocol !== null && protocol !== 'file:') {
return defer();
}
// Malformed file:// URL? We should always see `null` or `''`
if (hostname) {
// TODO file://./foo sets `hostname` to `'.'`. Perhaps we should special-case this.
return defer();
}
// pathname is the path to be resolved
return nodeResolveImplementation.defaultResolve(specifier, context, defaultResolve);
});
}
function getFormat(url, context, defaultGetFormat) {
return __awaiter(this, void 0, void 0, function* () {
const defer = (overrideUrl = url) => defaultGetFormat(overrideUrl, context, defaultGetFormat);
const parsed = url_1.parse(url);
if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
return defer();
}
const { pathname } = parsed;
assert(pathname !== null, 'ESM getFormat() hook: URL should never have null pathname');
const nativePath = url_1.fileURLToPath(url);
// If file has .ts, .tsx, or .jsx extension, then ask node how it would treat this file if it were .js
const ext = path_1.extname(nativePath);
if (ext !== '.js' && !tsNodeInstance.ignored(nativePath)) {
return defer(url_1.format(url_1.pathToFileURL(nativePath + '.js')));
}
return defer();
});
}
function transformSource(source, context, defaultTransformSource) {
return __awaiter(this, void 0, void 0, function* () {
const defer = () => defaultTransformSource(source, context, defaultTransformSource);
const sourceAsString = typeof source === 'string' ? source : source.toString('utf8');
const { url } = context;
const parsed = url_1.parse(url);
if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
return defer();
}
const nativePath = url_1.fileURLToPath(url);
if (tsNodeInstance.ignored(nativePath)) {
return defer();
}
const emittedJs = tsNodeInstance.compile(sourceAsString, nativePath);
return { source: emittedJs };
});
}
}
exports.registerAndCreateEsmHooks = registerAndCreateEsmHooks;
//# sourceMappingURL=esm.js.map

1
node_modules/ts-node/dist/esm.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

220
node_modules/ts-node/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,220 @@
import { BaseError } from 'make-error';
import type * as _ts from 'typescript';
/**
* Registered `ts-node` instance information.
*/
export declare const REGISTER_INSTANCE: unique symbol;
/**
* Expose `REGISTER_INSTANCE` information on node.js `process`.
*/
declare global {
namespace NodeJS {
interface Process {
[REGISTER_INSTANCE]?: Register;
}
}
}
/**
* Common TypeScript interfaces between versions.
*/
export interface TSCommon {
version: typeof _ts.version;
sys: typeof _ts.sys;
ScriptSnapshot: typeof _ts.ScriptSnapshot;
displayPartsToString: typeof _ts.displayPartsToString;
createLanguageService: typeof _ts.createLanguageService;
getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath;
getPreEmitDiagnostics: typeof _ts.getPreEmitDiagnostics;
flattenDiagnosticMessageText: typeof _ts.flattenDiagnosticMessageText;
transpileModule: typeof _ts.transpileModule;
ModuleKind: typeof _ts.ModuleKind;
ScriptTarget: typeof _ts.ScriptTarget;
findConfigFile: typeof _ts.findConfigFile;
readConfigFile: typeof _ts.readConfigFile;
parseJsonConfigFileContent: typeof _ts.parseJsonConfigFileContent;
formatDiagnostics: typeof _ts.formatDiagnostics;
formatDiagnosticsWithColorAndContext: typeof _ts.formatDiagnosticsWithColorAndContext;
}
/**
* Export the current version.
*/
export declare const VERSION: any;
/**
* Options for creating a new TypeScript compiler instance.
*/
export interface CreateOptions {
/**
* Specify working directory for config resolution.
*
* @default process.cwd()
*/
dir?: string;
/**
* Emit output files into `.ts-node` directory.
*
* @default false
*/
emit?: boolean;
/**
* Scope compiler to files within `cwd`.
*
* @default false
*/
scope?: boolean;
/**
* Use pretty diagnostic formatter.
*
* @default false
*/
pretty?: boolean;
/**
* Use TypeScript's faster `transpileModule`.
*
* @default false
*/
transpileOnly?: boolean;
/**
* **DEPRECATED** Specify type-check is enabled (e.g. `transpileOnly == false`).
*
* @default true
*/
typeCheck?: boolean;
/**
* Use TypeScript's compiler host API.
*
* @default false
*/
compilerHost?: boolean;
/**
* Logs TypeScript errors to stderr instead of throwing exceptions.
*
* @default false
*/
logError?: boolean;
/**
* Load files from `tsconfig.json` on startup.
*
* @default false
*/
files?: boolean;
/**
* Specify a custom TypeScript compiler.
*
* @default "typescript"
*/
compiler?: string;
/**
* Override the path patterns to skip compilation.
*
* @default /node_modules/
* @docsDefault "/node_modules/"
*/
ignore?: string[];
/**
* Path to TypeScript JSON project file.
*/
project?: string;
/**
* Skip project config resolution and loading.
*
* @default false
*/
skipProject?: boolean;
/**
* Skip ignore check.
*
* @default false
*/
skipIgnore?: boolean;
/**
* JSON object to merge with compiler options.
*
* @allOf [{"$ref": "https://schemastore.azurewebsites.net/schemas/json/tsconfig.json#definitions/compilerOptionsDefinition/properties/compilerOptions"}]
*/
compilerOptions?: object;
/**
* Ignore TypeScript warnings by diagnostic code.
*/
ignoreDiagnostics?: Array<number | string>;
/**
* Modules to require, like node's `--require` flag.
*
* If specified in tsconfig.json, the modules will be resolved relative to the tsconfig.json file.
*
* If specified programmatically, each input string should be pre-resolved to an absolute path for
* best results.
*/
require?: Array<string>;
readFile?: (path: string) => string | undefined;
fileExists?: (path: string) => boolean;
transformers?: _ts.CustomTransformers | ((p: _ts.Program) => _ts.CustomTransformers);
}
/**
* Options for registering a TypeScript compiler instance globally.
*/
export interface RegisterOptions extends CreateOptions {
/**
* Re-order file extensions so that TypeScript imports are preferred.
*
* @default false
*/
preferTsExts?: boolean;
}
/**
* Must be an interface to support `typescript-json-schema`.
*/
export interface TsConfigOptions extends Omit<RegisterOptions, 'transformers' | 'readFile' | 'fileExists' | 'skipProject' | 'project' | 'dir'> {
}
/**
* Information retrieved from type info check.
*/
export interface TypeInfo {
name: string;
comment: string;
}
/**
* Default register options, including values specified via environment
* variables.
*/
export declare const DEFAULTS: RegisterOptions;
/**
* Split a string array of values.
*/
export declare function split(value: string | undefined): string[] | undefined;
/**
* Parse a string as JSON.
*/
export declare function parse(value: string | undefined): object | undefined;
/**
* Replace backslashes with forward slashes.
*/
export declare function normalizeSlashes(value: string): string;
/**
* TypeScript diagnostics error.
*/
export declare class TSError extends BaseError {
diagnosticText: string;
diagnosticCodes: number[];
name: string;
constructor(diagnosticText: string, diagnosticCodes: number[]);
}
/**
* Return type for registering `ts-node`.
*/
export interface Register {
ts: TSCommon;
config: _ts.ParsedCommandLine;
options: RegisterOptions;
enabled(enabled?: boolean): boolean;
ignored(fileName: string): boolean;
compile(code: string, fileName: string, lineOffset?: number): string;
getTypeInfo(code: string, fileName: string, position: number): TypeInfo;
}
/**
* Register TypeScript compiler instance onto node.js
*/
export declare function register(opts?: RegisterOptions): Register;
/**
* Create TypeScript compiler instance.
*/
export declare function create(rawOptions?: CreateOptions): Register;

835
node_modules/ts-node/dist/index.js generated vendored Normal file
View file

@ -0,0 +1,835 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = exports.register = exports.getExtensions = exports.TSError = exports.normalizeSlashes = exports.parse = exports.split = exports.DEFAULTS = exports.VERSION = exports.debug = exports.INSPECT_CUSTOM = exports.REGISTER_INSTANCE = void 0;
const path_1 = require("path");
const sourceMapSupport = require("source-map-support");
const ynModule = require("yn");
const make_error_1 = require("make-error");
const util = require("util");
const url_1 = require("url");
const Module = require("module");
/**
* Does this version of node obey the package.json "type" field
* and throw ERR_REQUIRE_ESM when attempting to require() an ESM modules.
*/
const engineSupportsPackageTypeField = parseInt(process.versions.node.split('.')[0], 10) >= 12;
// Loaded conditionally so we don't need to support older node versions
let assertScriptCanLoadAsCJSImpl;
/**
* Assert that script can be loaded as CommonJS when we attempt to require it.
* If it should be loaded as ESM, throw ERR_REQUIRE_ESM like node does.
*/
function assertScriptCanLoadAsCJS(filename) {
if (!engineSupportsPackageTypeField)
return;
if (!assertScriptCanLoadAsCJSImpl)
assertScriptCanLoadAsCJSImpl = require('../dist-raw/node-cjs-loader-utils').assertScriptCanLoadAsCJSImpl;
assertScriptCanLoadAsCJSImpl(filename);
}
/**
* Registered `ts-node` instance information.
*/
exports.REGISTER_INSTANCE = Symbol.for('ts-node.register.instance');
/**
* @internal
*/
exports.INSPECT_CUSTOM = util.inspect.custom || 'inspect';
/**
* Wrapper around yn module that returns `undefined` instead of `null`.
* This is implemented by yn v4, but we're staying on v3 to avoid v4's node 10 requirement.
*/
function yn(value) {
var _a;
return (_a = ynModule(value)) !== null && _a !== void 0 ? _a : undefined;
}
/**
* Debugging `ts-node`.
*/
const shouldDebug = yn(process.env.TS_NODE_DEBUG);
/** @internal */
exports.debug = shouldDebug ?
(...args) => console.log(`[ts-node ${new Date().toISOString()}]`, ...args)
: () => undefined;
const debugFn = shouldDebug ?
(key, fn) => {
let i = 0;
return (x) => {
exports.debug(key, x, ++i);
return fn(x);
};
} :
(_, fn) => fn;
/**
* Export the current version.
*/
exports.VERSION = require('../package.json').version;
/**
* Like `Object.assign`, but ignores `undefined` properties.
*/
function assign(initialValue, ...sources) {
for (const source of sources) {
for (const key of Object.keys(source)) {
const value = source[key];
if (value !== undefined)
initialValue[key] = value;
}
}
return initialValue;
}
/**
* Default register options, including values specified via environment
* variables.
*/
exports.DEFAULTS = {
dir: process.env.TS_NODE_DIR,
emit: yn(process.env.TS_NODE_EMIT),
scope: yn(process.env.TS_NODE_SCOPE),
files: yn(process.env.TS_NODE_FILES),
pretty: yn(process.env.TS_NODE_PRETTY),
compiler: process.env.TS_NODE_COMPILER,
compilerOptions: parse(process.env.TS_NODE_COMPILER_OPTIONS),
ignore: split(process.env.TS_NODE_IGNORE),
project: process.env.TS_NODE_PROJECT,
skipProject: yn(process.env.TS_NODE_SKIP_PROJECT),
skipIgnore: yn(process.env.TS_NODE_SKIP_IGNORE),
preferTsExts: yn(process.env.TS_NODE_PREFER_TS_EXTS),
ignoreDiagnostics: split(process.env.TS_NODE_IGNORE_DIAGNOSTICS),
transpileOnly: yn(process.env.TS_NODE_TRANSPILE_ONLY),
typeCheck: yn(process.env.TS_NODE_TYPE_CHECK),
compilerHost: yn(process.env.TS_NODE_COMPILER_HOST),
logError: yn(process.env.TS_NODE_LOG_ERROR),
experimentalEsmLoader: false
};
/**
* Default TypeScript compiler options required by `ts-node`.
*/
const TS_NODE_COMPILER_OPTIONS = {
sourceMap: true,
inlineSourceMap: false,
inlineSources: true,
declaration: false,
noEmit: false,
outDir: '.ts-node'
};
/**
* Split a string array of values.
*/
function split(value) {
return typeof value === 'string' ? value.split(/ *, */g) : undefined;
}
exports.split = split;
/**
* Parse a string as JSON.
*/
function parse(value) {
return typeof value === 'string' ? JSON.parse(value) : undefined;
}
exports.parse = parse;
/**
* Replace backslashes with forward slashes.
*/
function normalizeSlashes(value) {
return value.replace(/\\/g, '/');
}
exports.normalizeSlashes = normalizeSlashes;
/**
* TypeScript diagnostics error.
*/
class TSError extends make_error_1.BaseError {
constructor(diagnosticText, diagnosticCodes) {
super(` Unable to compile TypeScript:\n${diagnosticText}`);
this.diagnosticText = diagnosticText;
this.diagnosticCodes = diagnosticCodes;
this.name = 'TSError';
}
/**
* @internal
*/
[exports.INSPECT_CUSTOM]() {
return this.diagnosticText;
}
}
exports.TSError = TSError;
/**
* Cached fs operation wrapper.
*/
function cachedLookup(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) {
cache.set(arg, fn(arg));
}
return cache.get(arg);
};
}
/** @internal */
function getExtensions(config) {
const tsExtensions = ['.ts'];
const jsExtensions = [];
// Enable additional extensions when JSX or `allowJs` is enabled.
if (config.options.jsx)
tsExtensions.push('.tsx');
if (config.options.allowJs)
jsExtensions.push('.js');
if (config.options.jsx && config.options.allowJs)
jsExtensions.push('.jsx');
return { tsExtensions, jsExtensions };
}
exports.getExtensions = getExtensions;
/**
* Register TypeScript compiler instance onto node.js
*/
function register(opts = {}) {
const originalJsHandler = require.extensions['.js']; // tslint:disable-line
const service = create(opts);
const { tsExtensions, jsExtensions } = getExtensions(service.config);
const extensions = [...tsExtensions, ...jsExtensions];
// Expose registered instance globally.
process[exports.REGISTER_INSTANCE] = service;
// Register the extensions.
registerExtensions(service.options.preferTsExts, extensions, service, originalJsHandler);
Module._preloadModules(service.options.require);
return service;
}
exports.register = register;
/**
* Create TypeScript compiler instance.
*/
function create(rawOptions = {}) {
var _a, _b;
const dir = (_a = rawOptions.dir) !== null && _a !== void 0 ? _a : exports.DEFAULTS.dir;
const compilerName = (_b = rawOptions.compiler) !== null && _b !== void 0 ? _b : exports.DEFAULTS.compiler;
const cwd = dir ? path_1.resolve(dir) : process.cwd();
/**
* Load the typescript compiler. It is required to load the tsconfig but might
* be changed by the tsconfig, so we sometimes have to do this twice.
*/
function loadCompiler(name) {
const compiler = require.resolve(name || 'typescript', { paths: [cwd, __dirname] });
const ts = require(compiler);
return { compiler, ts };
}
// Compute minimum options to read the config file.
let { compiler, ts } = loadCompiler(compilerName);
// Read config file and merge new options between env and CLI options.
const { config, options: tsconfigOptions } = readConfig(cwd, ts, rawOptions);
const options = assign({}, exports.DEFAULTS, tsconfigOptions || {}, rawOptions);
options.require = [
...tsconfigOptions.require || [],
...rawOptions.require || []
];
// If `compiler` option changed based on tsconfig, re-load the compiler.
if (options.compiler !== compilerName) {
({ compiler, ts } = loadCompiler(options.compiler));
}
const readFile = options.readFile || ts.sys.readFile;
const fileExists = options.fileExists || ts.sys.fileExists;
const transpileOnly = options.transpileOnly === true || options.typeCheck === false;
const transformers = options.transformers || undefined;
const ignoreDiagnostics = [
6059,
18002,
18003,
...(options.ignoreDiagnostics || [])
].map(Number);
const configDiagnosticList = filterDiagnostics(config.errors, ignoreDiagnostics);
const outputCache = new Map();
const isScoped = options.scope ? (relname) => relname.charAt(0) !== '.' : () => true;
const shouldIgnore = createIgnore(options.skipIgnore ? [] : (options.ignore || ['(?:^|/)node_modules/']).map(str => new RegExp(str)));
const diagnosticHost = {
getNewLine: () => ts.sys.newLine,
getCurrentDirectory: () => cwd,
getCanonicalFileName: ts.sys.useCaseSensitiveFileNames ? x => x : x => x.toLowerCase()
};
// Install source map support and read from memory cache.
sourceMapSupport.install({
environment: 'node',
retrieveFile(pathOrUrl) {
var _a;
let path = pathOrUrl;
// If it's a file URL, convert to local path
// Note: fileURLToPath does not exist on early node v10
// I could not find a way to handle non-URLs except to swallow an error
if (options.experimentalEsmLoader && path.startsWith('file://')) {
try {
path = url_1.fileURLToPath(path);
}
catch (e) { /* swallow error */ }
}
path = normalizeSlashes(path);
return ((_a = outputCache.get(path)) === null || _a === void 0 ? void 0 : _a.content) || '';
}
});
const formatDiagnostics = process.stdout.isTTY || options.pretty
? (ts.formatDiagnosticsWithColorAndContext || ts.formatDiagnostics)
: ts.formatDiagnostics;
function createTSError(diagnostics) {
const diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
const diagnosticCodes = diagnostics.map(x => x.code);
return new TSError(diagnosticText, diagnosticCodes);
}
function reportTSError(configDiagnosticList) {
const error = createTSError(configDiagnosticList);
if (options.logError) {
// Print error in red color and continue execution.
console.error('\x1b[31m%s\x1b[0m', error);
}
else {
// Throw error and exit the script.
throw error;
}
}
// Render the configuration errors.
if (configDiagnosticList.length)
reportTSError(configDiagnosticList);
/**
* Get the extension for a transpiled file.
*/
const getExtension = config.options.jsx === ts.JsxEmit.Preserve ?
((path) => /\.[tj]sx$/.test(path) ? '.jsx' : '.js') :
((_) => '.js');
/**
* Create the basic required function using transpile mode.
*/
let getOutput;
let getTypeInfo;
const getCanonicalFileName = ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames);
// In a factory because these are shared across both CompilerHost and LanguageService codepaths
function createResolverFunctions(serviceHost) {
const moduleResolutionCache = ts.createModuleResolutionCache(cwd, getCanonicalFileName, config.options);
const knownInternalFilenames = new Set();
/** "Buckets" (module directories) whose contents should be marked "internal" */
const internalBuckets = new Set();
// Get bucket for a source filename. Bucket is the containing `./node_modules/*/` directory
// For '/project/node_modules/foo/node_modules/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/bar/'
// For '/project/node_modules/foo/node_modules/@scope/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/@scope/bar/'
const moduleBucketRe = /.*\/node_modules\/(?:@[^\/]+\/)?[^\/]+\//;
function getModuleBucket(filename) {
const find = moduleBucketRe.exec(filename);
if (find)
return find[0];
return '';
}
// Mark that this file and all siblings in its bucket should be "internal"
function markBucketOfFilenameInternal(filename) {
internalBuckets.add(getModuleBucket(filename));
}
function isFileInInternalBucket(filename) {
return internalBuckets.has(getModuleBucket(filename));
}
function isFileKnownToBeInternal(filename) {
return knownInternalFilenames.has(filename);
}
/**
* If we need to emit JS for a file, force TS to consider it non-external
*/
const fixupResolvedModule = (resolvedModule) => {
const { resolvedFileName } = resolvedModule;
if (resolvedFileName === undefined)
return;
// .ts is always switched to internal
// .js is switched on-demand
if (resolvedModule.isExternalLibraryImport && ((resolvedFileName.endsWith('.ts') && !resolvedFileName.endsWith('.d.ts')) ||
isFileKnownToBeInternal(resolvedFileName) ||
isFileInInternalBucket(resolvedFileName))) {
resolvedModule.isExternalLibraryImport = false;
}
if (!resolvedModule.isExternalLibraryImport) {
knownInternalFilenames.add(resolvedFileName);
}
};
/*
* NOTE:
* Older ts versions do not pass `redirectedReference` nor `options`.
* We must pass `redirectedReference` to newer ts versions, but cannot rely on `options`, hence the weird argument name
*/
const resolveModuleNames = (moduleNames, containingFile, reusedNames, redirectedReference, optionsOnlyWithNewerTsVersions) => {
return moduleNames.map(moduleName => {
const { resolvedModule } = ts.resolveModuleName(moduleName, containingFile, config.options, serviceHost, moduleResolutionCache, redirectedReference);
if (resolvedModule) {
fixupResolvedModule(resolvedModule);
}
return resolvedModule;
});
};
// language service never calls this, but TS docs recommend that we implement it
const getResolvedModuleWithFailedLookupLocationsFromCache = (moduleName, containingFile) => {
const ret = ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
if (ret && ret.resolvedModule) {
fixupResolvedModule(ret.resolvedModule);
}
return ret;
};
const resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile, redirectedReference, options) => {
// Note: seems to be called with empty typeDirectiveNames array for all files.
return typeDirectiveNames.map(typeDirectiveName => {
const { resolvedTypeReferenceDirective } = ts.resolveTypeReferenceDirective(typeDirectiveName, containingFile, config.options, serviceHost, redirectedReference);
if (resolvedTypeReferenceDirective) {
fixupResolvedModule(resolvedTypeReferenceDirective);
}
return resolvedTypeReferenceDirective;
});
};
return {
resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives,
isFileKnownToBeInternal,
markBucketOfFilenameInternal
};
}
// Use full language services when the fast option is disabled.
if (!transpileOnly) {
const fileContents = new Map();
const rootFileNames = new Set(config.fileNames);
const cachedReadFile = cachedLookup(debugFn('readFile', readFile));
// Use language services by default (TODO: invert next major version).
if (!options.compilerHost) {
let projectVersion = 1;
const fileVersions = new Map(Array.from(rootFileNames).map(fileName => [fileName, 0]));
const getCustomTransformers = () => {
if (typeof transformers === 'function') {
const program = service.getProgram();
return program ? transformers(program) : undefined;
}
return transformers;
};
// Create the compiler host for type checking.
const serviceHost = {
getProjectVersion: () => String(projectVersion),
getScriptFileNames: () => Array.from(rootFileNames),
getScriptVersion: (fileName) => {
const version = fileVersions.get(fileName);
return version ? version.toString() : '';
},
getScriptSnapshot(fileName) {
// TODO ordering of this with getScriptVersion? Should they sync up?
let contents = fileContents.get(fileName);
// Read contents into TypeScript memory cache.
if (contents === undefined) {
contents = cachedReadFile(fileName);
if (contents === undefined)
return;
fileVersions.set(fileName, 1);
fileContents.set(fileName, contents);
projectVersion++;
}
return ts.ScriptSnapshot.fromString(contents);
},
readFile: cachedReadFile,
readDirectory: ts.sys.readDirectory,
getDirectories: cachedLookup(debugFn('getDirectories', ts.sys.getDirectories)),
fileExists: cachedLookup(debugFn('fileExists', fileExists)),
directoryExists: cachedLookup(debugFn('directoryExists', ts.sys.directoryExists)),
realpath: ts.sys.realpath ? cachedLookup(debugFn('realpath', ts.sys.realpath)) : undefined,
getNewLine: () => ts.sys.newLine,
useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
getCurrentDirectory: () => cwd,
getCompilationSettings: () => config.options,
getDefaultLibFileName: () => ts.getDefaultLibFilePath(config.options),
getCustomTransformers: getCustomTransformers
};
const { resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives, isFileKnownToBeInternal, markBucketOfFilenameInternal } = createResolverFunctions(serviceHost);
serviceHost.resolveModuleNames = resolveModuleNames;
serviceHost.getResolvedModuleWithFailedLookupLocationsFromCache = getResolvedModuleWithFailedLookupLocationsFromCache;
serviceHost.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives;
const registry = ts.createDocumentRegistry(ts.sys.useCaseSensitiveFileNames, cwd);
const service = ts.createLanguageService(serviceHost, registry);
const updateMemoryCache = (contents, fileName) => {
// Add to `rootFiles` as necessary, either to make TS include a file it has not seen,
// or to trigger a re-classification of files from external to internal.
if (!rootFileNames.has(fileName) && !isFileKnownToBeInternal(fileName)) {
markBucketOfFilenameInternal(fileName);
rootFileNames.add(fileName);
// Increment project version for every change to rootFileNames.
projectVersion++;
}
const previousVersion = fileVersions.get(fileName) || 0;
const previousContents = fileContents.get(fileName);
// Avoid incrementing cache when nothing has changed.
if (contents !== previousContents) {
fileVersions.set(fileName, previousVersion + 1);
fileContents.set(fileName, contents);
// Increment project version for every file change.
projectVersion++;
}
};
let previousProgram = undefined;
getOutput = (code, fileName) => {
updateMemoryCache(code, fileName);
const programBefore = service.getProgram();
if (programBefore !== previousProgram) {
exports.debug(`compiler rebuilt Program instance when getting output for ${fileName}`);
}
const output = service.getEmitOutput(fileName);
// Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.
const diagnostics = service.getSemanticDiagnostics(fileName)
.concat(service.getSyntacticDiagnostics(fileName));
const programAfter = service.getProgram();
exports.debug('invariant: Is service.getProject() identical before and after getting emit output and diagnostics? (should always be true) ', programBefore === programAfter);
previousProgram = programAfter;
const diagnosticList = filterDiagnostics(diagnostics, ignoreDiagnostics);
if (diagnosticList.length)
reportTSError(diagnosticList);
if (output.emitSkipped) {
throw new TypeError(`${path_1.relative(cwd, fileName)}: Emit skipped`);
}
// Throw an error when requiring `.d.ts` files.
if (output.outputFiles.length === 0) {
throw new TypeError(`Unable to require file: ${path_1.relative(cwd, fileName)}\n` +
'This is usually the result of a faulty configuration or import. ' +
'Make sure there is a `.js`, `.json` or other executable extension with ' +
'loader attached before `ts-node` available.');
}
return [output.outputFiles[1].text, output.outputFiles[0].text];
};
getTypeInfo = (code, fileName, position) => {
updateMemoryCache(code, fileName);
const info = service.getQuickInfoAtPosition(fileName, position);
const name = ts.displayPartsToString(info ? info.displayParts : []);
const comment = ts.displayPartsToString(info ? info.documentation : []);
return { name, comment };
};
}
else {
const sys = Object.assign(Object.assign(Object.assign({}, ts.sys), diagnosticHost), { readFile: (fileName) => {
const cacheContents = fileContents.get(fileName);
if (cacheContents !== undefined)
return cacheContents;
const contents = cachedReadFile(fileName);
if (contents)
fileContents.set(fileName, contents);
return contents;
}, readDirectory: ts.sys.readDirectory, getDirectories: cachedLookup(debugFn('getDirectories', ts.sys.getDirectories)), fileExists: cachedLookup(debugFn('fileExists', fileExists)), directoryExists: cachedLookup(debugFn('directoryExists', ts.sys.directoryExists)), resolvePath: cachedLookup(debugFn('resolvePath', ts.sys.resolvePath)), realpath: ts.sys.realpath ? cachedLookup(debugFn('realpath', ts.sys.realpath)) : undefined });
const host = ts.createIncrementalCompilerHost
? ts.createIncrementalCompilerHost(config.options, sys)
: Object.assign(Object.assign({}, sys), { getSourceFile: (fileName, languageVersion) => {
const contents = sys.readFile(fileName);
if (contents === undefined)
return;
return ts.createSourceFile(fileName, contents, languageVersion);
}, getDefaultLibLocation: () => normalizeSlashes(path_1.dirname(compiler)), getDefaultLibFileName: () => normalizeSlashes(path_1.join(path_1.dirname(compiler), ts.getDefaultLibFileName(config.options))), useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames });
const { resolveModuleNames, resolveTypeReferenceDirectives, isFileKnownToBeInternal, markBucketOfFilenameInternal } = createResolverFunctions(host);
host.resolveModuleNames = resolveModuleNames;
host.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives;
// Fallback for older TypeScript releases without incremental API.
let builderProgram = ts.createIncrementalProgram
? ts.createIncrementalProgram({
rootNames: Array.from(rootFileNames),
options: config.options,
host: host,
configFileParsingDiagnostics: config.errors,
projectReferences: config.projectReferences
})
: ts.createEmitAndSemanticDiagnosticsBuilderProgram(Array.from(rootFileNames), config.options, host, undefined, config.errors, config.projectReferences);
// Read and cache custom transformers.
const customTransformers = typeof transformers === 'function'
? transformers(builderProgram.getProgram())
: transformers;
// Set the file contents into cache manually.
const updateMemoryCache = (contents, fileName) => {
const previousContents = fileContents.get(fileName);
const contentsChanged = previousContents !== contents;
if (contentsChanged) {
fileContents.set(fileName, contents);
}
// Add to `rootFiles` when discovered by compiler for the first time.
let addedToRootFileNames = false;
if (!rootFileNames.has(fileName) && !isFileKnownToBeInternal(fileName)) {
markBucketOfFilenameInternal(fileName);
rootFileNames.add(fileName);
addedToRootFileNames = true;
}
// Update program when file changes.
if (addedToRootFileNames || contentsChanged) {
builderProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram(Array.from(rootFileNames), config.options, host, builderProgram, config.errors, config.projectReferences);
}
};
getOutput = (code, fileName) => {
const output = ['', ''];
updateMemoryCache(code, fileName);
const sourceFile = builderProgram.getSourceFile(fileName);
if (!sourceFile)
throw new TypeError(`Unable to read file: ${fileName}`);
const program = builderProgram.getProgram();
const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);
const diagnosticList = filterDiagnostics(diagnostics, ignoreDiagnostics);
if (diagnosticList.length)
reportTSError(diagnosticList);
const result = builderProgram.emit(sourceFile, (path, file, writeByteOrderMark) => {
if (path.endsWith('.map')) {
output[1] = file;
}
else {
output[0] = file;
}
if (options.emit)
sys.writeFile(path, file, writeByteOrderMark);
}, undefined, undefined, customTransformers);
if (result.emitSkipped) {
throw new TypeError(`${path_1.relative(cwd, fileName)}: Emit skipped`);
}
// Throw an error when requiring files that cannot be compiled.
if (output[0] === '') {
if (program.isSourceFileFromExternalLibrary(sourceFile)) {
throw new TypeError(`Unable to compile file from external library: ${path_1.relative(cwd, fileName)}`);
}
throw new TypeError(`Unable to require file: ${path_1.relative(cwd, fileName)}\n` +
'This is usually the result of a faulty configuration or import. ' +
'Make sure there is a `.js`, `.json` or other executable extension with ' +
'loader attached before `ts-node` available.');
}
return output;
};
getTypeInfo = (code, fileName, position) => {
updateMemoryCache(code, fileName);
const sourceFile = builderProgram.getSourceFile(fileName);
if (!sourceFile)
throw new TypeError(`Unable to read file: ${fileName}`);
const node = getTokenAtPosition(ts, sourceFile, position);
const checker = builderProgram.getProgram().getTypeChecker();
const symbol = checker.getSymbolAtLocation(node);
if (!symbol)
return { name: '', comment: '' };
const type = checker.getTypeOfSymbolAtLocation(symbol, node);
const signatures = [...type.getConstructSignatures(), ...type.getCallSignatures()];
return {
name: signatures.length ? signatures.map(x => checker.signatureToString(x)).join('\n') : checker.typeToString(type),
comment: ts.displayPartsToString(symbol ? symbol.getDocumentationComment(checker) : [])
};
};
// Write `.tsbuildinfo` when `--build` is enabled.
if (options.emit && config.options.incremental) {
process.on('exit', () => {
// Emits `.tsbuildinfo` to filesystem.
builderProgram.getProgram().emitBuildInfo();
});
}
}
}
else {
if (typeof transformers === 'function') {
throw new TypeError('Transformers function is unavailable in "--transpile-only"');
}
getOutput = (code, fileName) => {
const result = ts.transpileModule(code, {
fileName,
compilerOptions: config.options,
reportDiagnostics: true,
transformers: transformers
});
const diagnosticList = filterDiagnostics(result.diagnostics || [], ignoreDiagnostics);
if (diagnosticList.length)
reportTSError(diagnosticList);
return [result.outputText, result.sourceMapText];
};
getTypeInfo = () => {
throw new TypeError('Type information is unavailable in "--transpile-only"');
};
}
// Create a simple TypeScript compiler proxy.
function compile(code, fileName, lineOffset = 0) {
const normalizedFileName = normalizeSlashes(fileName);
const [value, sourceMap] = getOutput(code, normalizedFileName);
const output = updateOutput(value, normalizedFileName, sourceMap, getExtension);
outputCache.set(normalizedFileName, { content: output });
return output;
}
let active = true;
const enabled = (enabled) => enabled === undefined ? active : (active = !!enabled);
const extensions = getExtensions(config);
const ignored = (fileName) => {
if (!active)
return true;
const ext = path_1.extname(fileName);
if (extensions.tsExtensions.includes(ext) || extensions.jsExtensions.includes(ext)) {
const relname = path_1.relative(cwd, fileName);
return !isScoped(relname) || shouldIgnore(relname);
}
return true;
};
return { ts, config, compile, getTypeInfo, ignored, enabled, options };
}
exports.create = create;
/**
* Check if the filename should be ignored.
*/
function createIgnore(ignore) {
return (relname) => {
const path = normalizeSlashes(relname);
return ignore.some(x => x.test(path));
};
}
/**
* "Refreshes" an extension on `require.extensions`.
*
* @param {string} ext
*/
function reorderRequireExtension(ext) {
const old = require.extensions[ext]; // tslint:disable-line
delete require.extensions[ext]; // tslint:disable-line
require.extensions[ext] = old; // tslint:disable-line
}
/**
* Register the extensions to support when importing files.
*/
function registerExtensions(preferTsExts, extensions, register, originalJsHandler) {
// Register new extensions.
for (const ext of extensions) {
registerExtension(ext, register, originalJsHandler);
}
if (preferTsExts) {
// tslint:disable-next-line
const preferredExtensions = new Set([...extensions, ...Object.keys(require.extensions)]);
for (const ext of preferredExtensions)
reorderRequireExtension(ext);
}
}
/**
* Register the extension for node.
*/
function registerExtension(ext, register, originalHandler) {
const old = require.extensions[ext] || originalHandler; // tslint:disable-line
require.extensions[ext] = function (m, filename) {
if (register.ignored(filename))
return old(m, filename);
if (register.options.experimentalEsmLoader) {
assertScriptCanLoadAsCJS(filename);
}
const _compile = m._compile;
m._compile = function (code, fileName) {
exports.debug('module._compile', fileName);
return _compile.call(this, register.compile(code, fileName), fileName);
};
return old(m, filename);
};
}
/**
* Do post-processing on config options to support `ts-node`.
*/
function fixConfig(ts, config) {
// Delete options that *should not* be passed through.
delete config.options.out;
delete config.options.outFile;
delete config.options.composite;
delete config.options.declarationDir;
delete config.options.declarationMap;
delete config.options.emitDeclarationOnly;
// Target ES5 output by default (instead of ES3).
if (config.options.target === undefined) {
config.options.target = ts.ScriptTarget.ES5;
}
// Target CommonJS modules by default (instead of magically switching to ES6 when the target is ES6).
if (config.options.module === undefined) {
config.options.module = ts.ModuleKind.CommonJS;
}
return config;
}
/**
* Load TypeScript configuration. Returns the parsed TypeScript config and
* any `ts-node` options specified in the config file.
*/
function readConfig(cwd, ts, rawOptions) {
var _a, _b;
let config = { compilerOptions: {} };
let basePath = cwd;
let configFileName = undefined;
const { fileExists = ts.sys.fileExists, readFile = ts.sys.readFile, skipProject = exports.DEFAULTS.skipProject, project = exports.DEFAULTS.project } = rawOptions;
// Read project configuration when available.
if (!skipProject) {
configFileName = project
? path_1.resolve(cwd, project)
: ts.findConfigFile(cwd, fileExists);
if (configFileName) {
const result = ts.readConfigFile(configFileName, readFile);
// Return diagnostics.
if (result.error) {
return {
config: { errors: [result.error], fileNames: [], options: {} },
options: {}
};
}
config = result.config;
basePath = path_1.dirname(configFileName);
}
}
// Fix ts-node options that come from tsconfig.json
const tsconfigOptions = Object.assign({}, config['ts-node']);
// Remove resolution of "files".
const files = (_b = (_a = rawOptions.files) !== null && _a !== void 0 ? _a : tsconfigOptions.files) !== null && _b !== void 0 ? _b : exports.DEFAULTS.files;
if (!files) {
config.files = [];
config.include = [];
}
// Override default configuration options `ts-node` requires.
config.compilerOptions = Object.assign({}, config.compilerOptions, exports.DEFAULTS.compilerOptions, tsconfigOptions.compilerOptions, rawOptions.compilerOptions, TS_NODE_COMPILER_OPTIONS);
const fixedConfig = fixConfig(ts, ts.parseJsonConfigFileContent(config, {
fileExists,
readFile,
readDirectory: ts.sys.readDirectory,
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames
}, basePath, undefined, configFileName));
if (tsconfigOptions.require) {
// Modules are found relative to the tsconfig file, not the `dir` option
const tsconfigRelativeRequire = createRequire(configFileName);
tsconfigOptions.require = tsconfigOptions.require.map((path) => {
return tsconfigRelativeRequire.resolve(path);
});
}
return { config: fixedConfig, options: tsconfigOptions };
}
/**
* Update the output remapping the source map.
*/
function updateOutput(outputText, fileName, sourceMap, getExtension) {
const base64Map = Buffer.from(updateSourceMap(sourceMap, fileName), 'utf8').toString('base64');
const sourceMapContent = `data:application/json;charset=utf-8;base64,${base64Map}`;
const sourceMapLength = `${path_1.basename(fileName)}.map`.length + (getExtension(fileName).length - path_1.extname(fileName).length);
return outputText.slice(0, -sourceMapLength) + sourceMapContent;
}
/**
* Update the source map contents for improved output.
*/
function updateSourceMap(sourceMapText, fileName) {
const sourceMap = JSON.parse(sourceMapText);
sourceMap.file = fileName;
sourceMap.sources = [fileName];
delete sourceMap.sourceRoot;
return JSON.stringify(sourceMap);
}
/**
* Filter diagnostics.
*/
function filterDiagnostics(diagnostics, ignore) {
return diagnostics.filter(x => ignore.indexOf(x.code) === -1);
}
/**
* Get token at file position.
*
* Reference: https://github.com/microsoft/TypeScript/blob/fcd9334f57d85b73dd66ad2d21c02e84822f4841/src/services/utilities.ts#L705-L731
*/
function getTokenAtPosition(ts, sourceFile, position) {
let current = sourceFile;
outer: while (true) {
for (const child of current.getChildren(sourceFile)) {
const start = child.getFullStart();
if (start > position)
break;
const end = child.getEnd();
if (position <= end) {
current = child;
continue outer;
}
}
return current;
}
}
let nodeCreateRequire;
function createRequire(filename) {
if (!nodeCreateRequire) {
// tslint:disable-next-line
nodeCreateRequire = Module.createRequire || Module.createRequireFromPath || require('../dist-raw/node-createrequire').createRequireFromPath;
}
return nodeCreateRequire(filename);
}
//# sourceMappingURL=index.js.map

1
node_modules/ts-node/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

1
node_modules/ts-node/dist/index.spec.d.ts generated vendored Normal file
View file

@ -0,0 +1 @@
export {};

778
node_modules/ts-node/dist/index.spec.js generated vendored Normal file
View file

@ -0,0 +1,778 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const child_process_1 = require("child_process");
const path_1 = require("path");
const semver = require("semver");
const ts = require("typescript");
const proxyquire = require("proxyquire");
const fs_1 = require("fs");
const promisify = require("util.promisify");
const rimraf_1 = require("rimraf");
const module_1 = require("module");
const url_1 = require("url");
const execP = promisify(child_process_1.exec);
const TEST_DIR = path_1.join(__dirname, '../tests');
const PROJECT = path_1.join(TEST_DIR, 'tsconfig.json');
const BIN_PATH = path_1.join(TEST_DIR, 'node_modules/.bin/ts-node');
const BIN_SCRIPT_PATH = path_1.join(TEST_DIR, 'node_modules/.bin/ts-node-script');
const SOURCE_MAP_REGEXP = /\/\/# sourceMappingURL=data:application\/json;charset=utf\-8;base64,[\w\+]+=*$/;
// `createRequire` does not exist on older node versions
const testsDirRequire = (module_1.createRequire || module_1.createRequireFromPath)(path_1.join(TEST_DIR, 'index.js')); // tslint:disable-line
// Set after ts-node is installed locally
let { register, create, VERSION } = {};
// Pack and install ts-node locally, necessary to test package "exports"
before(function () {
return __awaiter(this, void 0, void 0, function* () {
this.timeout(5 * 60e3);
rimraf_1.sync(path_1.join(TEST_DIR, 'node_modules'));
yield execP(`npm install`, { cwd: TEST_DIR });
const packageLockPath = path_1.join(TEST_DIR, 'package-lock.json');
fs_1.existsSync(packageLockPath) && fs_1.unlinkSync(packageLockPath);
({ register, create, VERSION } = testsDirRequire('ts-node'));
});
});
describe('ts-node', function () {
const cmd = `"${BIN_PATH}" --project "${PROJECT}"`;
const cmdNoProject = `"${BIN_PATH}"`;
this.timeout(10000);
it('should export the correct version', function () {
chai_1.expect(VERSION).to.equal(require('../package.json').version);
});
it('should export all CJS entrypoints', function () {
// Ensure our package.json "exports" declaration allows `require()`ing all our entrypoints
// https://github.com/TypeStrong/ts-node/pull/1026
testsDirRequire.resolve('ts-node');
// only reliably way to ask node for the root path of a dependency is Path.resolve(require.resolve('ts-node/package'), '..')
testsDirRequire.resolve('ts-node/package');
testsDirRequire.resolve('ts-node/package.json');
// All bin entrypoints for people who need to augment our CLI: `node -r otherstuff ./node_modules/ts-node/dist/bin`
testsDirRequire.resolve('ts-node/dist/bin');
testsDirRequire.resolve('ts-node/dist/bin.js');
testsDirRequire.resolve('ts-node/dist/bin-transpile');
testsDirRequire.resolve('ts-node/dist/bin-transpile.js');
testsDirRequire.resolve('ts-node/dist/bin-script');
testsDirRequire.resolve('ts-node/dist/bin-script.js');
// Must be `require()`able obviously
testsDirRequire.resolve('ts-node/register');
testsDirRequire.resolve('ts-node/register/files');
testsDirRequire.resolve('ts-node/register/transpile-only');
testsDirRequire.resolve('ts-node/register/type-check');
// `node --loader ts-node/esm`
testsDirRequire.resolve('ts-node/esm');
testsDirRequire.resolve('ts-node/esm.mjs');
testsDirRequire.resolve('ts-node/esm/transpile-only');
testsDirRequire.resolve('ts-node/esm/transpile-only.mjs');
});
describe('cli', function () {
this.slow(1000);
it('should execute cli', function (done) {
child_process_1.exec(`${cmd} tests/hello-world`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, world!\n');
return done();
});
});
it('shows usage via --help', function (done) {
child_process_1.exec(`${cmdNoProject} --help`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.match(/Usage: ts-node /);
return done();
});
});
it('shows version via -v', function (done) {
child_process_1.exec(`${cmdNoProject} -v`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout.trim()).to.equal('v' + testsDirRequire('ts-node/package').version);
return done();
});
});
it('shows version of compiler via -vv', function (done) {
child_process_1.exec(`${cmdNoProject} -vv`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout.trim()).to.equal(`ts-node v${testsDirRequire('ts-node/package').version}\n` +
`node ${process.version}\n` +
`compiler v${testsDirRequire('typescript/package').version}`);
return done();
});
});
it('should register via cli', function (done) {
child_process_1.exec(`node -r ts-node/register hello-world.ts`, {
cwd: TEST_DIR
}, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, world!\n');
return done();
});
});
it('should execute cli with absolute path', function (done) {
child_process_1.exec(`${cmd} "${path_1.join(TEST_DIR, 'hello-world')}"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, world!\n');
return done();
});
});
it('should print scripts', function (done) {
child_process_1.exec(`${cmd} -pe "import { example } from './tests/complex/index';example()"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('example\n');
return done();
});
});
it('should provide registered information globally', function (done) {
child_process_1.exec(`${cmd} tests/env`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('object\n');
return done();
});
});
it('should provide registered information on register', function (done) {
child_process_1.exec(`node -r ts-node/register env.ts`, {
cwd: TEST_DIR
}, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('object\n');
return done();
});
});
if (semver.gte(ts.version, '1.8.0')) {
it('should allow js', function (done) {
child_process_1.exec([
cmd,
'-O "{\\\"allowJs\\\":true}"',
'-pe "import { main } from \'./tests/allow-js/run\';main()"'
].join(' '), function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('hello world\n');
return done();
});
});
it('should include jsx when `allow-js` true', function (done) {
child_process_1.exec([
cmd,
'-O "{\\\"allowJs\\\":true}"',
'-pe "import { Foo2 } from \'./tests/allow-js/with-jsx\'; Foo2.sayHi()"'
].join(' '), function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('hello world\n');
return done();
});
});
}
it('should eval code', function (done) {
child_process_1.exec(`${cmd} -e "import * as m from './tests/module';console.log(m.example('test'))"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('TEST\n');
return done();
});
});
it('should import empty files', function (done) {
child_process_1.exec(`${cmd} -e "import './tests/empty'"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('');
return done();
});
});
it('should throw errors', function (done) {
child_process_1.exec(`${cmd} -e "import * as m from './tests/module';console.log(m.example(123))"`, function (err) {
if (err === null) {
return done('Command was expected to fail, but it succeeded.');
}
chai_1.expect(err.message).to.match(new RegExp('TS2345: Argument of type \'(?:number|123)\' ' +
'is not assignable to parameter of type \'string\'\\.'));
return done();
});
});
it('should be able to ignore diagnostic', function (done) {
child_process_1.exec(`${cmd} --ignore-diagnostics 2345 -e "import * as m from './tests/module';console.log(m.example(123))"`, function (err) {
if (err === null) {
return done('Command was expected to fail, but it succeeded.');
}
chai_1.expect(err.message).to.match(/TypeError: (?:(?:undefined|foo\.toUpperCase) is not a function|.*has no method \'toUpperCase\')/);
return done();
});
});
it('should work with source maps', function (done) {
child_process_1.exec(`${cmd} tests/throw`, function (err) {
if (err === null) {
return done('Command was expected to fail, but it succeeded.');
}
chai_1.expect(err.message).to.contain([
`${path_1.join(__dirname, '../tests/throw.ts')}:100`,
' bar () { throw new Error(\'this is a demo\') }',
' ^',
'Error: this is a demo'
].join('\n'));
return done();
});
});
it('eval should work with source maps', function (done) {
child_process_1.exec(`${cmd} -pe "import './tests/throw'"`, function (err) {
if (err === null) {
return done('Command was expected to fail, but it succeeded.');
}
chai_1.expect(err.message).to.contain([
`${path_1.join(__dirname, '../tests/throw.ts')}:100`,
' bar () { throw new Error(\'this is a demo\') }',
' ^'
].join('\n'));
return done();
});
});
it('should support transpile only mode', function (done) {
child_process_1.exec(`${cmd} --transpile-only -pe "x"`, function (err) {
if (err === null) {
return done('Command was expected to fail, but it succeeded.');
}
chai_1.expect(err.message).to.contain('ReferenceError: x is not defined');
return done();
});
});
it('should throw error even in transpileOnly mode', function (done) {
child_process_1.exec(`${cmd} --transpile-only -pe "console."`, function (err) {
if (err === null) {
return done('Command was expected to fail, but it succeeded.');
}
chai_1.expect(err.message).to.contain('error TS1003: Identifier expected');
return done();
});
});
it('should pipe into `ts-node` and evaluate', function (done) {
const cp = child_process_1.exec(cmd, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('hello\n');
return done();
});
cp.stdin.end("console.log('hello')");
});
it('should pipe into `ts-node`', function (done) {
const cp = child_process_1.exec(`${cmd} -p`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('true\n');
return done();
});
cp.stdin.end('true');
});
it('should pipe into an eval script', function (done) {
const cp = child_process_1.exec(`${cmd} --transpile-only -pe "process.stdin.isTTY"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('undefined\n');
return done();
});
cp.stdin.end('true');
});
it('should run REPL when --interactive passed and stdin is not a TTY', function (done) {
const cp = child_process_1.exec(`${cmd} --interactive`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('> 123\n' +
'undefined\n' +
'> ');
return done();
});
cp.stdin.end('console.log("123")\n');
});
it('REPL has command to get type information', function (done) {
const cp = child_process_1.exec(`${cmd} --interactive`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('> undefined\n' +
'> undefined\n' +
'> const a: 123\n' +
'> ');
return done();
});
cp.stdin.end('\nconst a = 123\n.type a');
});
it('should support require flags', function (done) {
child_process_1.exec(`${cmd} -r ./tests/hello-world -pe "console.log('success')"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, world!\nsuccess\nundefined\n');
return done();
});
});
it('should support require from node modules', function (done) {
child_process_1.exec(`${cmd} -r typescript -e "console.log('success')"`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('success\n');
return done();
});
});
it('should use source maps with react tsx', function (done) {
child_process_1.exec(`${cmd} tests/throw-react-tsx.tsx`, function (err, stdout) {
chai_1.expect(err).not.to.equal(null);
chai_1.expect(err.message).to.contain([
`${path_1.join(__dirname, '../tests/throw-react-tsx.tsx')}:100`,
' bar () { throw new Error(\'this is a demo\') }',
' ^',
'Error: this is a demo'
].join('\n'));
return done();
});
});
it('should allow custom typings', function (done) {
child_process_1.exec(`${cmd} tests/custom-types`, function (err, stdout) {
chai_1.expect(err).to.match(/Error: Cannot find module 'does-not-exist'/);
return done();
});
});
it('should preserve `ts-node` context with child process', function (done) {
child_process_1.exec(`${cmd} tests/child-process`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, world!\n');
return done();
});
});
it('should import js before ts by default', function (done) {
child_process_1.exec(`${cmd} tests/import-order/compiled`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, JavaScript!\n');
return done();
});
});
it('should import ts before js when --prefer-ts-exts flag is present', function (done) {
child_process_1.exec(`${cmd} --prefer-ts-exts tests/import-order/compiled`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, TypeScript!\n');
return done();
});
});
it('should import ts before js when TS_NODE_PREFER_TS_EXTS env is present', function (done) {
child_process_1.exec(`${cmd} tests/import-order/compiled`, { env: Object.assign(Object.assign({}, process.env), { TS_NODE_PREFER_TS_EXTS: 'true' }) }, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, TypeScript!\n');
return done();
});
});
it('should ignore .d.ts files', function (done) {
child_process_1.exec(`${cmd} tests/import-order/importer`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, World!\n');
return done();
});
});
describe('issue #884', function () {
it('should compile', function (done) {
// TODO disabled because it consistently fails on Windows on TS 2.7
if (process.platform === 'win32' && semver.satisfies(ts.version, '2.7')) {
this.skip();
}
else {
child_process_1.exec(`"${BIN_PATH}" --project tests/issue-884/tsconfig.json tests/issue-884`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('');
return done();
});
}
});
});
describe('issue #986', function () {
it('should not compile', function (done) {
child_process_1.exec(`"${BIN_PATH}" --project tests/issue-986/tsconfig.json tests/issue-986`, function (err, stdout, stderr) {
chai_1.expect(err).not.to.equal(null);
chai_1.expect(stderr).to.contain('Cannot find name \'TEST\''); // TypeScript error.
chai_1.expect(stdout).to.equal('');
return done();
});
});
it('should compile with `--files`', function (done) {
child_process_1.exec(`"${BIN_PATH}" --files --project tests/issue-986/tsconfig.json tests/issue-986`, function (err, stdout, stderr) {
chai_1.expect(err).not.to.equal(null);
chai_1.expect(stderr).to.contain('ReferenceError: TEST is not defined'); // Runtime error.
chai_1.expect(stdout).to.equal('');
return done();
});
});
});
if (semver.gte(ts.version, '2.7.0')) {
it('should support script mode', function (done) {
child_process_1.exec(`${BIN_SCRIPT_PATH} tests/scope/a/log`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('.ts\n');
return done();
});
});
it('should read tsconfig relative to realpath, not symlink, in scriptMode', function (done) {
if (fs_1.lstatSync(path_1.join(TEST_DIR, 'main-realpath/symlink/symlink.tsx')).isSymbolicLink()) {
child_process_1.exec(`${BIN_SCRIPT_PATH} tests/main-realpath/symlink/symlink.tsx`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('');
return done();
});
}
else {
this.skip();
}
});
}
describe('should read ts-node options from tsconfig.json', function () {
const BIN_EXEC = `"${BIN_PATH}" --project tests/tsconfig-options/tsconfig.json`;
it('should override compiler options from env', function (done) {
child_process_1.exec(`${BIN_EXEC} tests/tsconfig-options/log-options1.js`, {
env: Object.assign(Object.assign({}, process.env), { TS_NODE_COMPILER_OPTIONS: '{"typeRoots": ["env-typeroots"]}' })
}, function (err, stdout) {
chai_1.expect(err).to.equal(null);
const { config } = JSON.parse(stdout);
chai_1.expect(config.options.typeRoots).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/env-typeroots').replace(/\\/g, '/')]);
return done();
});
});
it('should use options from `tsconfig.json`', function (done) {
child_process_1.exec(`${BIN_EXEC} tests/tsconfig-options/log-options1.js`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
const { options, config } = JSON.parse(stdout);
chai_1.expect(config.options.typeRoots).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/tsconfig-typeroots').replace(/\\/g, '/')]);
chai_1.expect(config.options.types).to.deep.equal(['tsconfig-tsnode-types']);
chai_1.expect(options.pretty).to.equal(undefined);
chai_1.expect(options.skipIgnore).to.equal(false);
chai_1.expect(options.transpileOnly).to.equal(true);
chai_1.expect(options.require).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/required1.js')]);
return done();
});
});
it('should have flags override / merge with `tsconfig.json`', function (done) {
child_process_1.exec(`${BIN_EXEC} --skip-ignore --compiler-options "{\\"types\\":[\\"flags-types\\"]}" --require ./tests/tsconfig-options/required2.js tests/tsconfig-options/log-options2.js`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
const { options, config } = JSON.parse(stdout);
chai_1.expect(config.options.typeRoots).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/tsconfig-typeroots').replace(/\\/g, '/')]);
chai_1.expect(config.options.types).to.deep.equal(['flags-types']);
chai_1.expect(options.pretty).to.equal(undefined);
chai_1.expect(options.skipIgnore).to.equal(true);
chai_1.expect(options.transpileOnly).to.equal(true);
chai_1.expect(options.require).to.deep.equal([
path_1.join(__dirname, '../tests/tsconfig-options/required1.js'),
'./tests/tsconfig-options/required2.js'
]);
return done();
});
});
it('should have `tsconfig.json` override environment', function (done) {
child_process_1.exec(`${BIN_EXEC} tests/tsconfig-options/log-options1.js`, {
env: Object.assign(Object.assign({}, process.env), { TS_NODE_PRETTY: 'true', TS_NODE_SKIP_IGNORE: 'true' })
}, function (err, stdout) {
chai_1.expect(err).to.equal(null);
const { options, config } = JSON.parse(stdout);
chai_1.expect(config.options.typeRoots).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/tsconfig-typeroots').replace(/\\/g, '/')]);
chai_1.expect(config.options.types).to.deep.equal(['tsconfig-tsnode-types']);
chai_1.expect(options.pretty).to.equal(true);
chai_1.expect(options.skipIgnore).to.equal(false);
chai_1.expect(options.transpileOnly).to.equal(true);
chai_1.expect(options.require).to.deep.equal([path_1.join(__dirname, '../tests/tsconfig-options/required1.js')]);
return done();
});
});
});
describe('compiler host', function () {
it('should execute cli', function (done) {
child_process_1.exec(`${cmd} --compiler-host tests/hello-world`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('Hello, world!\n');
return done();
});
});
});
it('should transpile files inside a node_modules directory when not ignored', function (done) {
child_process_1.exec(`${cmdNoProject} --script-mode tests/from-node-modules/from-node-modules`, function (err, stdout, stderr) {
if (err)
return done(`Unexpected error: ${err}\nstdout:\n${stdout}\nstderr:\n${stderr}`);
chai_1.expect(JSON.parse(stdout)).to.deep.equal({
external: {
tsmri: { name: 'typescript-module-required-internally' },
jsmri: { name: 'javascript-module-required-internally' },
tsmii: { name: 'typescript-module-imported-internally' },
jsmii: { name: 'javascript-module-imported-internally' }
},
tsmie: { name: 'typescript-module-imported-externally' },
jsmie: { name: 'javascript-module-imported-externally' },
tsmre: { name: 'typescript-module-required-externally' },
jsmre: { name: 'javascript-module-required-externally' }
});
done();
});
});
describe('should respect maxNodeModulesJsDepth', function () {
it('for unscoped modules', function (done) {
child_process_1.exec(`${cmdNoProject} --script-mode tests/maxnodemodulesjsdepth`, function (err, stdout, stderr) {
chai_1.expect(err).to.not.equal(null);
chai_1.expect(stderr.replace(/\r\n/g, '\n')).to.contain('TSError: Unable to compile TypeScript:\n' +
"other.ts(4,7): error TS2322: Type 'string' is not assignable to type 'boolean'.\n" +
'\n');
done();
});
});
it('for @scoped modules', function (done) {
child_process_1.exec(`${cmdNoProject} --script-mode tests/maxnodemodulesjsdepth-scoped`, function (err, stdout, stderr) {
chai_1.expect(err).to.not.equal(null);
chai_1.expect(stderr.replace(/\r\n/g, '\n')).to.contain('TSError: Unable to compile TypeScript:\n' +
"other.ts(7,7): error TS2322: Type 'string' is not assignable to type 'boolean'.\n" +
'\n');
done();
});
});
});
});
describe('register', function () {
let registered;
let moduleTestPath;
before(() => {
registered = register({
project: PROJECT,
compilerOptions: {
jsx: 'preserve'
}
});
moduleTestPath = require.resolve('../tests/module');
});
afterEach(() => {
// Re-enable project after every test.
registered.enabled(true);
});
it('should be able to require typescript', function () {
const m = require(moduleTestPath);
chai_1.expect(m.example('foo')).to.equal('FOO');
});
it('should support dynamically disabling', function () {
delete require.cache[moduleTestPath];
chai_1.expect(registered.enabled(false)).to.equal(false);
chai_1.expect(() => require(moduleTestPath)).to.throw(/Unexpected token/);
delete require.cache[moduleTestPath];
chai_1.expect(registered.enabled()).to.equal(false);
chai_1.expect(() => require(moduleTestPath)).to.throw(/Unexpected token/);
delete require.cache[moduleTestPath];
chai_1.expect(registered.enabled(true)).to.equal(true);
chai_1.expect(() => require(moduleTestPath)).to.not.throw();
delete require.cache[moduleTestPath];
chai_1.expect(registered.enabled()).to.equal(true);
chai_1.expect(() => require(moduleTestPath)).to.not.throw();
});
if (semver.gte(ts.version, '2.7.0')) {
it('should support compiler scopes', function () {
const calls = [];
registered.enabled(false);
const compilers = [
register({ dir: path_1.join(TEST_DIR, 'scope/a'), scope: true }),
register({ dir: path_1.join(TEST_DIR, 'scope/b'), scope: true })
];
compilers.forEach(c => {
const old = c.compile;
c.compile = (code, fileName, lineOffset) => {
calls.push(fileName);
return old(code, fileName, lineOffset);
};
});
try {
chai_1.expect(require('../tests/scope/a').ext).to.equal('.ts');
chai_1.expect(require('../tests/scope/b').ext).to.equal('.ts');
}
finally {
compilers.forEach(c => c.enabled(false));
}
chai_1.expect(calls).to.deep.equal([
path_1.join(TEST_DIR, 'scope/a/index.ts'),
path_1.join(TEST_DIR, 'scope/b/index.ts')
]);
delete require.cache[moduleTestPath];
chai_1.expect(() => require(moduleTestPath)).to.throw();
});
}
it('should compile through js and ts', function () {
const m = require('../tests/complex');
chai_1.expect(m.example()).to.equal('example');
});
it('should work with proxyquire', function () {
const m = proxyquire('../tests/complex', {
'./example': 'hello'
});
chai_1.expect(m.example()).to.equal('hello');
});
it('should work with `require.cache`', function () {
const { example1, example2 } = require('../tests/require-cache');
chai_1.expect(example1).to.not.equal(example2);
});
it('should use source maps', function (done) {
try {
require('../tests/throw');
}
catch (error) {
chai_1.expect(error.stack).to.contain([
'Error: this is a demo',
` at Foo.bar (${path_1.join(__dirname, '../tests/throw.ts')}:100:18)`
].join('\n'));
done();
}
});
describe('JSX preserve', () => {
let old;
let compiled;
before(function () {
old = require.extensions['.tsx']; // tslint:disable-line
require.extensions['.tsx'] = (m, fileName) => {
const _compile = m._compile;
m._compile = (code, fileName) => {
compiled = code;
return _compile.call(this, code, fileName);
};
return old(m, fileName);
};
});
after(function () {
require.extensions['.tsx'] = old; // tslint:disable-line
});
it('should use source maps', function (done) {
try {
require('../tests/with-jsx.tsx');
}
catch (error) {
chai_1.expect(error.stack).to.contain('SyntaxError: Unexpected token');
}
chai_1.expect(compiled).to.match(SOURCE_MAP_REGEXP);
done();
});
});
});
describe('create', () => {
let service;
before(() => {
service = create({ compilerOptions: { target: 'es5' }, skipProject: true });
});
it('should create generic compiler instances', () => {
const output = service.compile('const x = 10', 'test.ts');
chai_1.expect(output).to.contain('var x = 10;');
});
describe('should get type information', () => {
it('given position of identifier', () => {
chai_1.expect(service.getTypeInfo('/**jsdoc here*/const x = 10', 'test.ts', 21)).to.deep.equal({
comment: 'jsdoc here',
name: 'const x: 10'
});
});
it('given position that does not point to an identifier', () => {
chai_1.expect(service.getTypeInfo('/**jsdoc here*/const x = 10', 'test.ts', 0)).to.deep.equal({
comment: '',
name: ''
});
});
});
});
describe('issue #1098', () => {
function testIgnored(ignored, allowed, disallowed) {
for (const ext of allowed) {
chai_1.expect(ignored(path_1.join(__dirname, `index${ext}`))).equal(false, `should accept ${ext} files`);
}
for (const ext of disallowed) {
chai_1.expect(ignored(path_1.join(__dirname, `index${ext}`))).equal(true, `should ignore ${ext} files`);
}
}
it('correctly filters file extensions from the compiler when allowJs=false and jsx=false', () => {
const { ignored } = create({ compilerOptions: {}, skipProject: true });
testIgnored(ignored, ['.ts', '.d.ts'], ['.js', '.tsx', '.jsx', '.mjs', '.cjs', '.xyz', '']);
});
it('correctly filters file extensions from the compiler when allowJs=true and jsx=false', () => {
const { ignored } = create({ compilerOptions: { allowJs: true }, skipProject: true });
testIgnored(ignored, ['.ts', '.js', '.d.ts'], ['.tsx', '.jsx', '.mjs', '.cjs', '.xyz', '']);
});
it('correctly filters file extensions from the compiler when allowJs=false and jsx=true', () => {
const { ignored } = create({ compilerOptions: { allowJs: false, jsx: 'preserve' }, skipProject: true });
testIgnored(ignored, ['.ts', '.tsx', '.d.ts'], ['.js', '.jsx', '.mjs', '.cjs', '.xyz', '']);
});
it('correctly filters file extensions from the compiler when allowJs=true and jsx=true', () => {
const { ignored } = create({ compilerOptions: { allowJs: true, jsx: 'preserve' }, skipProject: true });
testIgnored(ignored, ['.ts', '.tsx', '.js', '.jsx', '.d.ts'], ['.mjs', '.cjs', '.xyz', '']);
});
});
describe('esm', () => {
this.slow(1000);
const cmd = `node --loader ts-node/esm`;
if (semver.gte(process.version, '13.0.0')) {
it('should compile and execute as ESM', (done) => {
child_process_1.exec(`${cmd} index.ts`, { cwd: path_1.join(__dirname, '../tests/esm') }, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('foo bar baz biff\n');
return done();
});
});
it('should use source maps', function (done) {
child_process_1.exec(`${cmd} throw.ts`, { cwd: path_1.join(__dirname, '../tests/esm') }, function (err, stdout) {
chai_1.expect(err).not.to.equal(null);
chai_1.expect(err.message).to.contain([
`${url_1.pathToFileURL(path_1.join(__dirname, '../tests/esm/throw.ts'))}:100`,
' bar () { throw new Error(\'this is a demo\') }',
' ^',
'Error: this is a demo'
].join('\n'));
return done();
});
});
describe('supports experimental-specifier-resolution=node', () => {
it('via --experimental-specifier-resolution', (done) => {
child_process_1.exec(`${cmd} --experimental-specifier-resolution=node index.ts`, { cwd: path_1.join(__dirname, '../tests/esm-node-resolver') }, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('foo bar baz biff\n');
return done();
});
});
it('via NODE_OPTIONS', (done) => {
child_process_1.exec(`${cmd} index.ts`, {
cwd: path_1.join(__dirname, '../tests/esm-node-resolver'),
env: Object.assign(Object.assign({}, process.env), { NODE_OPTIONS: '--experimental-specifier-resolution=node' })
}, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('foo bar baz biff\n');
return done();
});
});
});
it('throws ERR_REQUIRE_ESM when attempting to require() an ESM script while ESM loader is enabled', function (done) {
child_process_1.exec(`${cmd} ./index.js`, { cwd: path_1.join(__dirname, '../tests/esm-err-require-esm') }, function (err, stdout, stderr) {
chai_1.expect(err).to.not.equal(null);
chai_1.expect(stderr).to.contain('Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:');
return done();
});
});
it('defers to fallback loaders when URL should not be handled by ts-node', function (done) {
child_process_1.exec(`${cmd} index.mjs`, {
cwd: path_1.join(__dirname, '../tests/esm-import-http-url')
}, function (err, stdout, stderr) {
chai_1.expect(err).to.not.equal(null);
// expect error from node's default resolver
chai_1.expect(stderr).to.match(/Error \[ERR_UNSUPPORTED_ESM_URL_SCHEME\]:.*\n *at defaultResolve/);
return done();
});
});
it('should support transpile only mode via dedicated loader entrypoint', (done) => {
child_process_1.exec(`${cmd}/transpile-only index.ts`, { cwd: path_1.join(__dirname, '../tests/esm-transpile-only') }, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('');
return done();
});
});
it('should throw type errors without transpile-only enabled', (done) => {
child_process_1.exec(`${cmd} index.ts`, { cwd: path_1.join(__dirname, '../tests/esm-transpile-only') }, function (err, stdout) {
if (err === null) {
return done('Command was expected to fail, but it succeeded.');
}
chai_1.expect(err.message).to.contain('Unable to compile TypeScript');
chai_1.expect(err.message).to.match(new RegExp('TS2345: Argument of type \'(?:number|1101)\' is not assignable to parameter of type \'string\'\\.'));
chai_1.expect(err.message).to.match(new RegExp('TS2322: Type \'(?:"hello world"|string)\' is not assignable to type \'number\'\\.'));
chai_1.expect(stdout).to.equal('');
return done();
});
});
}
it('executes ESM as CJS, ignoring package.json "types" field (for backwards compatibility; should be changed in next major release to throw ERR_REQUIRE_ESM)', function (done) {
child_process_1.exec(`${BIN_PATH} ./tests/esm-err-require-esm/index.js`, function (err, stdout) {
chai_1.expect(err).to.equal(null);
chai_1.expect(stdout).to.equal('CommonJS\n');
return done();
});
});
});
});
//# sourceMappingURL=index.spec.js.map

1
node_modules/ts-node/dist/index.spec.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

13
node_modules/ts-node/dist/tsconfig-schema.d.ts generated vendored Normal file
View file

@ -0,0 +1,13 @@
import { TsConfigOptions } from '.';
/**
* tsconfig schema which includes "ts-node" options.
* @allOf [{"$ref": "https://schemastore.azurewebsites.net/schemas/json/tsconfig.json"}]
*/
export interface TsConfigSchema {
/**
* ts-node options. See also: https://github.com/TypeStrong/ts-node#configuration-options
*
* ts-node offers TypeScript execution and REPL for node.js, with source map support.
*/
'ts-node': TsConfigOptions;
}

3
node_modules/ts-node/dist/tsconfig-schema.js generated vendored Normal file
View file

@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=tsconfig-schema.js.map

1
node_modules/ts-node/dist/tsconfig-schema.js.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"tsconfig-schema.js","sourceRoot":"","sources":["../src/tsconfig-schema.ts"],"names":[],"mappings":"","sourcesContent":["import { TsConfigOptions } from '.'\n\n/*\n * This interface exists solely for generating a JSON schema for tsconfig.json.\n * We do *not* extend the compiler's tsconfig interface. Instead we handle that\n * on a schema level, via \"allOf\", so we pull in the same schema that VSCode\n * already uses.\n */\n/**\n * tsconfig schema which includes \"ts-node\" options.\n * @allOf [{\"$ref\": \"https://schemastore.azurewebsites.net/schemas/json/tsconfig.json\"}]\n */\nexport interface TsConfigSchema {\n /**\n * ts-node options. See also: https://github.com/TypeStrong/ts-node#configuration-options\n *\n * ts-node offers TypeScript execution and REPL for node.js, with source map support.\n */\n 'ts-node': TsConfigOptions\n}\n"]}