初始化

This commit is contained in:
yziiy
2025-08-11 11:06:07 +08:00
parent 083bc37c00
commit 5607d11395
19772 changed files with 3108723 additions and 18 deletions

View File

@@ -0,0 +1,40 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { Options, ReducedTransformOptions, RequireAndTranspileModuleOptions, StringMap, TransformResult } from './types';
declare class ScriptTransformer {
private readonly _config;
private readonly _cacheFS;
private readonly _cache;
private readonly _transformCache;
private _transformsAreLoaded;
constructor(_config: Config.ProjectConfig, _cacheFS: StringMap);
private _buildCacheKeyFromFileInfo;
private _getCacheKey;
private _getCacheKeyAsync;
private _createFolderFromCacheKey;
private _getFileCachePath;
private _getFileCachePathAsync;
private _getTransformPath;
loadTransformers(): Promise<void>;
private _getTransformer;
private _instrumentFile;
private _buildTransformResult;
transformSource(filepath: Config.Path, content: string, options: ReducedTransformOptions): TransformResult;
transformSourceAsync(filepath: Config.Path, content: string, options: ReducedTransformOptions): Promise<TransformResult>;
private _transformAndBuildScriptAsync;
private _transformAndBuildScript;
transformAsync(filename: Config.Path, options: Options, fileSource?: string): Promise<TransformResult>;
transform(filename: Config.Path, options: Options, fileSource?: string): TransformResult;
transformJson(filename: Config.Path, options: Options, fileSource: string): string;
requireAndTranspileModule<ModuleType = unknown>(moduleName: string, callback?: (module: ModuleType) => void | Promise<void>, options?: RequireAndTranspileModuleOptions): Promise<ModuleType>;
shouldTransform(filename: Config.Path): boolean;
}
export declare function createTranspilingRequire(config: Config.ProjectConfig): Promise<(<TModuleType = unknown>(resolverPath: string, applyInteropRequireDefault?: boolean) => Promise<TModuleType>)>;
export declare type TransformerType = ScriptTransformer;
export declare function createScriptTransformer(config: Config.ProjectConfig, cacheFS?: StringMap): Promise<TransformerType>;
export {};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
interface ErrorWithCodeFrame extends Error {
codeFrame?: string;
}
export default function handlePotentialSyntaxError(e: ErrorWithCodeFrame): ErrorWithCodeFrame;
export declare function enhanceUnexpectedTokenMessage(e: Error): Error;
export {};

View File

@@ -0,0 +1,83 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = handlePotentialSyntaxError;
exports.enhanceUnexpectedTokenMessage = enhanceUnexpectedTokenMessage;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const DOT = ' \u2022 ';
function handlePotentialSyntaxError(e) {
if (e.codeFrame) {
e.stack = e.message + '\n' + e.codeFrame;
}
if (
// `instanceof` might come from the wrong context
e.name === 'SyntaxError' &&
!e.message.includes(' expected')
) {
throw enhanceUnexpectedTokenMessage(e);
}
return e;
}
function enhanceUnexpectedTokenMessage(e) {
e.stack =
`${_chalk().default.bold.red('Jest encountered an unexpected token')}
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
${DOT}If you are trying to use ECMAScript Modules, see ${_chalk().default.underline(
'https://jestjs.io/docs/ecmascript-modules'
)} for how to enable it.
${DOT}If you are trying to use TypeScript, see ${_chalk().default.underline(
'https://jestjs.io/docs/getting-started#using-typescript'
)}
${DOT}To have some of your "node_modules" files transformed, you can specify a custom ${_chalk().default.bold(
'"transformIgnorePatterns"'
)} in your config.
${DOT}If you need a custom transformation specify a ${_chalk().default.bold(
'"transform"'
)} option in your config.
${DOT}If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the ${_chalk().default.bold(
'"moduleNameMapper"'
)} config option.
You'll find more details and examples of these config options in the docs:
${_chalk().default.cyan('https://jestjs.io/docs/configuration')}
For information about custom transformations, see:
${_chalk().default.cyan('https://jestjs.io/docs/code-transformation')}
${_chalk().default.bold.red('Details:')}
` + e.stack;
return e;
}

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export { createScriptTransformer, createTranspilingRequire, } from './ScriptTransformer';
export type { TransformerType as ScriptTransformer } from './ScriptTransformer';
export { default as shouldInstrument } from './shouldInstrument';
export type { CallerTransformOptions, Transformer, SyncTransformer, AsyncTransformer, ShouldInstrumentOptions, Options as TransformationOptions, TransformOptions, TransformResult, TransformedSource, } from './types';
export { default as handlePotentialSyntaxError } from './enhanceUnexpectedTokenMessage';

View File

@@ -0,0 +1,41 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
Object.defineProperty(exports, 'createScriptTransformer', {
enumerable: true,
get: function () {
return _ScriptTransformer.createScriptTransformer;
}
});
Object.defineProperty(exports, 'createTranspilingRequire', {
enumerable: true,
get: function () {
return _ScriptTransformer.createTranspilingRequire;
}
});
Object.defineProperty(exports, 'handlePotentialSyntaxError', {
enumerable: true,
get: function () {
return _enhanceUnexpectedTokenMessage.default;
}
});
Object.defineProperty(exports, 'shouldInstrument', {
enumerable: true,
get: function () {
return _shouldInstrument.default;
}
});
var _ScriptTransformer = require('./ScriptTransformer');
var _shouldInstrument = _interopRequireDefault(require('./shouldInstrument'));
var _enhanceUnexpectedTokenMessage = _interopRequireDefault(
require('./enhanceUnexpectedTokenMessage')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare const makeInvalidReturnValueError: () => string;
export declare const makeInvalidSourceMapWarning: (filename: string, transformPath: string) => string;
export declare const makeInvalidSyncTransformerError: (transformPath: string) => string;
export declare const makeInvalidTransformerError: (transformPath: string) => string;

View File

@@ -0,0 +1,101 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.makeInvalidTransformerError =
exports.makeInvalidSyncTransformerError =
exports.makeInvalidSourceMapWarning =
exports.makeInvalidReturnValueError =
void 0;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _slash() {
const data = _interopRequireDefault(require('slash'));
_slash = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const BULLET = '\u25cf ';
const DOCUMENTATION_NOTE = ` ${_chalk().default.bold(
'Code Transformation Documentation:'
)}
https://jestjs.io/docs/code-transformation
`;
const makeInvalidReturnValueError = () =>
_chalk().default.red(
[
_chalk().default.bold(BULLET + 'Invalid return value:'),
" Code transformer's `process` function must return a string or an object",
' with `code` key containing a string. If `processAsync` function is implemented,',
' it must return a Promise resolving to one of these values.',
''
].join('\n') + DOCUMENTATION_NOTE
);
exports.makeInvalidReturnValueError = makeInvalidReturnValueError;
const makeInvalidSourceMapWarning = (filename, transformPath) =>
_chalk().default.yellow(
[
_chalk().default.bold(BULLET + 'Invalid source map:'),
` The source map for "${(0, _slash().default)(
filename
)}" returned by "${(0, _slash().default)(transformPath)}" is invalid.`,
' Proceeding without source mapping for that file.'
].join('\n')
);
exports.makeInvalidSourceMapWarning = makeInvalidSourceMapWarning;
const makeInvalidSyncTransformerError = transformPath =>
_chalk().default.red(
[
_chalk().default.bold(BULLET + 'Invalid synchronous transformer module:'),
` "${(0, _slash().default)(
transformPath
)}" specified in the "transform" object of Jest configuration`,
' must export a `process` function.',
''
].join('\n') + DOCUMENTATION_NOTE
);
exports.makeInvalidSyncTransformerError = makeInvalidSyncTransformerError;
const makeInvalidTransformerError = transformPath =>
_chalk().default.red(
[
_chalk().default.bold(BULLET + 'Invalid transformer module:'),
` "${(0, _slash().default)(
transformPath
)}" specified in the "transform" object of Jest configuration`,
' must export a `process` or `processAsync` or `createTransformer` function.',
''
].join('\n') + DOCUMENTATION_NOTE
);
exports.makeInvalidTransformerError = makeInvalidTransformerError;

View File

@@ -0,0 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { ShouldInstrumentOptions } from './types';
export default function shouldInstrument(filename: Config.Path, options: ShouldInstrumentOptions, config: Config.ProjectConfig): boolean;

View File

@@ -0,0 +1,207 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = shouldInstrument;
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _micromatch() {
const data = _interopRequireDefault(require('micromatch'));
_micromatch = function () {
return data;
};
return data;
}
function _jestRegexUtil() {
const data = require('jest-regex-util');
_jestRegexUtil = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const MOCKS_PATTERN = new RegExp(
(0, _jestRegexUtil().escapePathForRegex)(
path().sep + '__mocks__' + path().sep
)
);
const cachedRegexes = new Map();
const getRegex = regexStr => {
if (!cachedRegexes.has(regexStr)) {
cachedRegexes.set(regexStr, new RegExp(regexStr));
}
const regex = cachedRegexes.get(regexStr); // prevent stateful regexes from breaking, just in case
regex.lastIndex = 0;
return regex;
};
function shouldInstrument(filename, options, config) {
if (!options.collectCoverage) {
return false;
}
if (
config.forceCoverageMatch.length &&
_micromatch().default.any(filename, config.forceCoverageMatch)
) {
return true;
}
if (
!config.testPathIgnorePatterns.some(pattern =>
getRegex(pattern).test(filename)
)
) {
if (config.testRegex.some(regex => new RegExp(regex).test(filename))) {
return false;
}
if (
(0, _jestUtil().globsToMatcher)(config.testMatch)(
(0, _jestUtil().replacePathSepForGlob)(filename)
)
) {
return false;
}
}
if (
// This configuration field contains an object in the form of:
// {'path/to/file.js': true}
options.collectCoverageOnlyFrom &&
!options.collectCoverageOnlyFrom[filename]
) {
return false;
}
if (
// still cover if `only` is specified
!options.collectCoverageOnlyFrom &&
options.collectCoverageFrom.length &&
!(0, _jestUtil().globsToMatcher)(options.collectCoverageFrom)(
(0, _jestUtil().replacePathSepForGlob)(
path().relative(config.rootDir, filename)
)
)
) {
return false;
}
if (
config.coveragePathIgnorePatterns.some(pattern => !!filename.match(pattern))
) {
return false;
}
if (config.globalSetup === filename) {
return false;
}
if (config.globalTeardown === filename) {
return false;
}
if (config.setupFiles.includes(filename)) {
return false;
}
if (config.setupFilesAfterEnv.includes(filename)) {
return false;
}
if (MOCKS_PATTERN.test(filename)) {
return false;
}
if (options.changedFiles && !options.changedFiles.has(filename)) {
if (!options.sourcesRelatedToTestsInChangedFiles) {
return false;
}
if (!options.sourcesRelatedToTestsInChangedFiles.has(filename)) {
return false;
}
}
return true;
}

View File

@@ -0,0 +1,75 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { RawSourceMap } from 'source-map';
import type { Config, TransformTypes } from '@jest/types';
export interface ShouldInstrumentOptions extends Pick<Config.GlobalConfig, 'collectCoverage' | 'collectCoverageFrom' | 'collectCoverageOnlyFrom' | 'coverageProvider'> {
changedFiles?: Set<Config.Path>;
sourcesRelatedToTestsInChangedFiles?: Set<Config.Path>;
}
export interface Options extends ShouldInstrumentOptions, CallerTransformOptions {
isInternalModule?: boolean;
}
interface FixedRawSourceMap extends Omit<RawSourceMap, 'version'> {
version: number;
}
export declare type TransformedSource = {
code: string;
map?: FixedRawSourceMap | string | null;
} | string;
export declare type TransformResult = TransformTypes.TransformResult;
export interface CallerTransformOptions {
supportsDynamicImport: boolean;
supportsExportNamespaceFrom: boolean;
supportsStaticESM: boolean;
supportsTopLevelAwait: boolean;
}
export interface ReducedTransformOptions extends CallerTransformOptions {
instrument: boolean;
}
export interface RequireAndTranspileModuleOptions extends ReducedTransformOptions {
applyInteropRequireDefault: boolean;
}
export declare type StringMap = Map<string, string>;
export interface TransformOptions<OptionType = unknown> extends ReducedTransformOptions {
/** a cached file system which is used in jest-runtime - useful to improve performance */
cacheFS: StringMap;
config: Config.ProjectConfig;
/** A stringified version of the configuration - useful in cache busting */
configString: string;
/** the options passed through Jest's config by the user */
transformerConfig: OptionType;
}
export interface SyncTransformer<OptionType = unknown> {
/**
* Indicates if the transformer is capable of instrumenting the code for code coverage.
*
* If V8 coverage is _not_ active, and this is `true`, Jest will assume the code is instrumented.
* If V8 coverage is _not_ active, and this is `false`. Jest will instrument the code returned by this transformer using Babel.
*/
canInstrument?: boolean;
createTransformer?: (options?: OptionType) => SyncTransformer<OptionType>;
getCacheKey?: (sourceText: string, sourcePath: Config.Path, options: TransformOptions<OptionType>) => string;
getCacheKeyAsync?: (sourceText: string, sourcePath: Config.Path, options: TransformOptions<OptionType>) => Promise<string>;
process: (sourceText: string, sourcePath: Config.Path, options: TransformOptions<OptionType>) => TransformedSource;
processAsync?: (sourceText: string, sourcePath: Config.Path, options: TransformOptions<OptionType>) => Promise<TransformedSource>;
}
export interface AsyncTransformer<OptionType = unknown> {
/**
* Indicates if the transformer is capable of instrumenting the code for code coverage.
*
* If V8 coverage is _not_ active, and this is `true`, Jest will assume the code is instrumented.
* If V8 coverage is _not_ active, and this is `false`. Jest will instrument the code returned by this transformer using Babel.
*/
canInstrument?: boolean;
createTransformer?: (options?: OptionType) => AsyncTransformer<OptionType>;
getCacheKey?: (sourceText: string, sourcePath: Config.Path, options: TransformOptions<OptionType>) => string;
getCacheKeyAsync?: (sourceText: string, sourcePath: Config.Path, options: TransformOptions<OptionType>) => Promise<string>;
process?: (sourceText: string, sourcePath: Config.Path, options: TransformOptions<OptionType>) => TransformedSource;
processAsync: (sourceText: string, sourcePath: Config.Path, options: TransformOptions<OptionType>) => Promise<TransformedSource>;
}
export declare type Transformer<OptionType = unknown> = SyncTransformer<OptionType> | AsyncTransformer<OptionType>;
export {};

View File

@@ -0,0 +1 @@
'use strict';