2021-06-06 17:09:53 -07:00
|
|
|
/**
|
|
|
|
* Copyright (c) Microsoft Corporation.
|
|
|
|
*
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
*
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
*
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2022-04-18 20:47:18 -08:00
|
|
|
import crypto from 'crypto';
|
|
|
|
import os from 'os';
|
|
|
|
import path from 'path';
|
|
|
|
import fs from 'fs';
|
|
|
|
import { sourceMapSupport, pirates } from './utilsBundle';
|
|
|
|
import url from 'url';
|
2021-06-23 10:30:54 -07:00
|
|
|
import type { Location } from './types';
|
2022-04-06 13:57:14 -08:00
|
|
|
import type { TsConfigLoaderResult } from './third_party/tsconfig-loader';
|
|
|
|
import { tsConfigLoader } from './third_party/tsconfig-loader';
|
2022-02-25 15:43:58 -08:00
|
|
|
import Module from 'module';
|
2022-04-18 16:50:25 -08:00
|
|
|
import type { BabelTransformFunction } from './babelBundle';
|
2021-06-06 17:09:53 -07:00
|
|
|
|
2022-03-11 08:00:46 -08:00
|
|
|
const version = 8;
|
2021-06-06 17:09:53 -07:00
|
|
|
const cacheDir = process.env.PWTEST_CACHE_DIR || path.join(os.tmpdir(), 'playwright-transform-cache');
|
|
|
|
const sourceMaps: Map<string, string> = new Map();
|
|
|
|
|
2022-01-26 18:28:42 -08:00
|
|
|
type ParsedTsConfigData = {
|
2022-02-25 15:43:58 -08:00
|
|
|
absoluteBaseUrl: string;
|
|
|
|
paths: { key: string, values: string[] }[];
|
2022-01-26 18:28:42 -08:00
|
|
|
};
|
|
|
|
const cachedTSConfigs = new Map<string, ParsedTsConfigData | undefined>();
|
|
|
|
|
2021-06-23 10:30:54 -07:00
|
|
|
const kStackTraceLimit = 15;
|
|
|
|
Error.stackTraceLimit = kStackTraceLimit;
|
|
|
|
|
2021-06-06 17:09:53 -07:00
|
|
|
sourceMapSupport.install({
|
|
|
|
environment: 'node',
|
|
|
|
handleUncaughtExceptions: false,
|
|
|
|
retrieveSourceMap(source) {
|
|
|
|
if (!sourceMaps.has(source))
|
|
|
|
return null;
|
|
|
|
const sourceMapPath = sourceMaps.get(source)!;
|
|
|
|
if (!fs.existsSync(sourceMapPath))
|
|
|
|
return null;
|
|
|
|
return {
|
|
|
|
map: JSON.parse(fs.readFileSync(sourceMapPath, 'utf-8')),
|
|
|
|
url: source
|
|
|
|
};
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2022-03-10 14:48:33 -08:00
|
|
|
function calculateCachePath(content: string, filePath: string, isModule: boolean): string {
|
2022-01-20 18:11:56 -08:00
|
|
|
const hash = crypto.createHash('sha1')
|
2022-01-27 14:32:23 -08:00
|
|
|
.update(process.env.PW_TEST_SOURCE_TRANSFORM || '')
|
2022-03-10 14:48:33 -08:00
|
|
|
.update(isModule ? 'esm' : 'no_esm')
|
2022-01-20 18:11:56 -08:00
|
|
|
.update(content)
|
|
|
|
.update(filePath)
|
|
|
|
.update(String(version))
|
|
|
|
.digest('hex');
|
2021-06-06 17:09:53 -07:00
|
|
|
const fileName = path.basename(filePath, path.extname(filePath)).replace(/\W/g, '') + '_' + hash;
|
|
|
|
return path.join(cacheDir, hash[0] + hash[1], fileName);
|
|
|
|
}
|
|
|
|
|
2022-01-26 18:28:42 -08:00
|
|
|
function validateTsConfig(tsconfig: TsConfigLoaderResult): ParsedTsConfigData | undefined {
|
2022-02-25 15:43:58 -08:00
|
|
|
if (!tsconfig.tsConfigPath || !tsconfig.baseUrl)
|
2022-01-26 18:28:42 -08:00
|
|
|
return;
|
|
|
|
// Make 'baseUrl' absolute, because it is relative to the tsconfig.json, not to cwd.
|
|
|
|
const absoluteBaseUrl = path.resolve(path.dirname(tsconfig.tsConfigPath), tsconfig.baseUrl);
|
2022-02-25 15:43:58 -08:00
|
|
|
const paths = tsconfig.paths || { '*': ['*'] };
|
|
|
|
return { absoluteBaseUrl, paths: Object.entries(paths).map(([key, values]) => ({ key, values })) };
|
2022-01-26 18:28:42 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
function loadAndValidateTsconfigForFile(file: string): ParsedTsConfigData | undefined {
|
|
|
|
const cwd = path.dirname(file);
|
|
|
|
if (!cachedTSConfigs.has(cwd)) {
|
|
|
|
const loaded = tsConfigLoader({
|
|
|
|
getEnv: (name: string) => process.env[name],
|
|
|
|
cwd
|
|
|
|
});
|
|
|
|
cachedTSConfigs.set(cwd, validateTsConfig(loaded));
|
|
|
|
}
|
|
|
|
return cachedTSConfigs.get(cwd);
|
|
|
|
}
|
|
|
|
|
2022-02-09 07:14:11 -08:00
|
|
|
const pathSeparator = process.platform === 'win32' ? ';' : ':';
|
|
|
|
const scriptPreprocessor = process.env.PW_TEST_SOURCE_TRANSFORM ?
|
|
|
|
require(process.env.PW_TEST_SOURCE_TRANSFORM) : undefined;
|
2022-02-25 15:43:58 -08:00
|
|
|
const builtins = new Set(Module.builtinModules);
|
|
|
|
|
|
|
|
export function resolveHook(filename: string, specifier: string): string | undefined {
|
|
|
|
if (builtins.has(specifier))
|
|
|
|
return;
|
|
|
|
const isTypeScript = filename.endsWith('.ts') || filename.endsWith('.tsx');
|
|
|
|
if (!isTypeScript)
|
|
|
|
return;
|
|
|
|
const tsconfig = loadAndValidateTsconfigForFile(filename);
|
2022-03-28 14:37:46 -07:00
|
|
|
if (tsconfig) {
|
2022-04-06 22:14:03 +01:00
|
|
|
let longestPrefixLength = -1;
|
|
|
|
let pathMatchedByLongestPrefix: string | undefined;
|
|
|
|
|
2022-03-28 14:37:46 -07:00
|
|
|
for (const { key, values } of tsconfig.paths) {
|
2022-04-06 22:14:03 +01:00
|
|
|
let matchedPartOfSpecifier = specifier;
|
|
|
|
|
|
|
|
const [keyPrefix, keySuffix] = key.split('*');
|
|
|
|
if (key.includes('*')) {
|
|
|
|
// * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
|
|
|
|
// * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
|
|
|
|
// * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
|
|
|
|
// https://github.com/microsoft/TypeScript/blob/f82d0cb3299c04093e3835bc7e29f5b40475f586/src/compiler/moduleNameResolver.ts#L1049
|
|
|
|
if (keyPrefix) {
|
|
|
|
if (!specifier.startsWith(keyPrefix))
|
|
|
|
continue;
|
|
|
|
matchedPartOfSpecifier = matchedPartOfSpecifier.substring(keyPrefix.length, matchedPartOfSpecifier.length);
|
|
|
|
}
|
|
|
|
if (keySuffix) {
|
|
|
|
if (!specifier.endsWith(keySuffix))
|
|
|
|
continue;
|
|
|
|
matchedPartOfSpecifier = matchedPartOfSpecifier.substring(0, matchedPartOfSpecifier.length - keySuffix.length);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (specifier !== key)
|
|
|
|
continue;
|
|
|
|
matchedPartOfSpecifier = specifier;
|
|
|
|
}
|
|
|
|
|
2022-03-28 14:37:46 -07:00
|
|
|
for (const value of values) {
|
2022-04-06 22:14:03 +01:00
|
|
|
let candidate: string = value;
|
|
|
|
|
|
|
|
if (value.includes('*'))
|
|
|
|
candidate = candidate.replace('*', matchedPartOfSpecifier);
|
2022-03-28 14:37:46 -07:00
|
|
|
candidate = path.resolve(tsconfig.absoluteBaseUrl, candidate.replace(/\//g, path.sep));
|
|
|
|
for (const ext of ['', '.js', '.ts', '.mjs', '.cjs', '.jsx', '.tsx']) {
|
2022-04-06 22:14:03 +01:00
|
|
|
if (fs.existsSync(candidate + ext)) {
|
|
|
|
if (keyPrefix.length > longestPrefixLength) {
|
|
|
|
longestPrefixLength = keyPrefix.length;
|
|
|
|
pathMatchedByLongestPrefix = candidate;
|
|
|
|
}
|
|
|
|
}
|
2022-03-28 14:37:46 -07:00
|
|
|
}
|
2022-02-25 15:43:58 -08:00
|
|
|
}
|
|
|
|
}
|
2022-04-06 22:14:03 +01:00
|
|
|
if (pathMatchedByLongestPrefix)
|
|
|
|
return pathMatchedByLongestPrefix;
|
2022-02-25 15:43:58 -08:00
|
|
|
}
|
2022-03-28 14:37:46 -07:00
|
|
|
if (specifier.endsWith('.js')) {
|
|
|
|
const resolved = path.resolve(path.dirname(filename), specifier);
|
|
|
|
if (resolved.endsWith('.js')) {
|
|
|
|
const tsResolved = resolved.substring(0, resolved.length - 3) + '.ts';
|
|
|
|
if (!fs.existsSync(resolved) && fs.existsSync(tsResolved))
|
|
|
|
return tsResolved;
|
|
|
|
}
|
|
|
|
}
|
2022-02-25 15:43:58 -08:00
|
|
|
}
|
2022-02-09 07:14:11 -08:00
|
|
|
|
2022-01-26 18:28:42 -08:00
|
|
|
export function transformHook(code: string, filename: string, isModule = false): string {
|
2021-12-14 19:25:07 -08:00
|
|
|
if (isComponentImport(filename))
|
|
|
|
return componentStub();
|
2022-01-26 18:28:42 -08:00
|
|
|
|
2022-02-09 07:14:11 -08:00
|
|
|
// If we are not TypeScript and there is no applicable preprocessor - bail out.
|
|
|
|
const isTypeScript = filename.endsWith('.ts') || filename.endsWith('.tsx');
|
|
|
|
const hasPreprocessor =
|
|
|
|
process.env.PW_TEST_SOURCE_TRANSFORM &&
|
|
|
|
process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE &&
|
|
|
|
process.env.PW_TEST_SOURCE_TRANSFORM_SCOPE.split(pathSeparator).some(f => filename.startsWith(f));
|
|
|
|
|
|
|
|
if (!isTypeScript && !hasPreprocessor)
|
|
|
|
return code;
|
|
|
|
|
2022-03-10 14:48:33 -08:00
|
|
|
const cachePath = calculateCachePath(code, filename, isModule);
|
2021-11-24 12:42:48 -08:00
|
|
|
const codePath = cachePath + '.js';
|
|
|
|
const sourceMapPath = cachePath + '.map';
|
|
|
|
sourceMaps.set(filename, sourceMapPath);
|
2022-01-20 13:33:40 -08:00
|
|
|
if (!process.env.PW_IGNORE_COMPILE_CACHE && fs.existsSync(codePath))
|
2021-11-24 12:42:48 -08:00
|
|
|
return fs.readFileSync(codePath, 'utf8');
|
|
|
|
// We don't use any browserslist data, but babel checks it anyway.
|
|
|
|
// Silence the annoying warning.
|
|
|
|
process.env.BROWSERSLIST_IGNORE_OLD_DATA = 'true';
|
2022-01-27 14:32:23 -08:00
|
|
|
|
2022-02-14 15:33:14 -07:00
|
|
|
try {
|
2022-04-18 16:50:25 -08:00
|
|
|
const { babelTransform }: { babelTransform: BabelTransformFunction } = require('./babelBundle');
|
2022-04-18 10:31:58 -08:00
|
|
|
const result = babelTransform(filename, isTypeScript, isModule, hasPreprocessor ? scriptPreprocessor : undefined, [require.resolve('./tsxTransform')]);
|
2022-02-14 15:33:14 -07:00
|
|
|
if (result.code) {
|
|
|
|
fs.mkdirSync(path.dirname(cachePath), { recursive: true });
|
|
|
|
if (result.map)
|
|
|
|
fs.writeFileSync(sourceMapPath, JSON.stringify(result.map), 'utf8');
|
|
|
|
fs.writeFileSync(codePath, result.code, 'utf8');
|
|
|
|
}
|
|
|
|
return result.code || '';
|
|
|
|
} catch (e) {
|
|
|
|
// Re-throw error with a playwright-test stack
|
|
|
|
// that could be filtered out.
|
|
|
|
throw new Error(e.message);
|
2021-11-24 12:42:48 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-26 18:28:42 -08:00
|
|
|
export function installTransform(): () => void {
|
2022-02-25 15:43:58 -08:00
|
|
|
let reverted = false;
|
|
|
|
|
|
|
|
const originalResolveFilename = (Module as any)._resolveFilename;
|
|
|
|
function resolveFilename(this: any, specifier: string, parent: Module, ...rest: any[]) {
|
|
|
|
if (!reverted && parent) {
|
|
|
|
const resolved = resolveHook(parent.filename, specifier);
|
|
|
|
if (resolved !== undefined)
|
|
|
|
specifier = resolved;
|
|
|
|
}
|
|
|
|
return originalResolveFilename.call(this, specifier, parent, ...rest);
|
|
|
|
}
|
|
|
|
(Module as any)._resolveFilename = resolveFilename;
|
2022-02-09 07:14:11 -08:00
|
|
|
|
2022-02-25 15:43:58 -08:00
|
|
|
const exts = ['.ts', '.tsx'];
|
2022-02-09 07:14:11 -08:00
|
|
|
// When script preprocessor is engaged, we transpile JS as well.
|
|
|
|
if (scriptPreprocessor)
|
|
|
|
exts.push('.js', '.mjs');
|
2022-02-25 15:43:58 -08:00
|
|
|
const revertPirates = pirates.addHook((code: string, filename: string) => transformHook(code, filename), { exts });
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
reverted = true;
|
|
|
|
(Module as any)._resolveFilename = originalResolveFilename;
|
|
|
|
revertPirates();
|
|
|
|
};
|
2021-06-06 17:09:53 -07:00
|
|
|
}
|
2021-06-23 10:30:54 -07:00
|
|
|
|
|
|
|
export function wrapFunctionWithLocation<A extends any[], R>(func: (location: Location, ...args: A) => R): (...args: A) => R {
|
|
|
|
return (...args) => {
|
|
|
|
const oldPrepareStackTrace = Error.prepareStackTrace;
|
|
|
|
Error.prepareStackTrace = (error, stackFrames) => {
|
|
|
|
const frame: NodeJS.CallSite = sourceMapSupport.wrapCallSite(stackFrames[1]);
|
2021-06-29 15:28:41 -07:00
|
|
|
const fileName = frame.getFileName();
|
|
|
|
// Node error stacks for modules use file:// urls instead of paths.
|
|
|
|
const file = (fileName && fileName.startsWith('file://')) ? url.fileURLToPath(fileName) : fileName;
|
2021-06-23 10:30:54 -07:00
|
|
|
return {
|
2021-06-29 15:28:41 -07:00
|
|
|
file,
|
2021-06-23 10:30:54 -07:00
|
|
|
line: frame.getLineNumber(),
|
|
|
|
column: frame.getColumnNumber(),
|
|
|
|
};
|
|
|
|
};
|
|
|
|
Error.stackTraceLimit = 2;
|
|
|
|
const obj: { stack: Location } = {} as any;
|
|
|
|
Error.captureStackTrace(obj);
|
|
|
|
const location = obj.stack;
|
|
|
|
Error.stackTraceLimit = kStackTraceLimit;
|
|
|
|
Error.prepareStackTrace = oldPrepareStackTrace;
|
|
|
|
return func(location, ...args);
|
|
|
|
};
|
|
|
|
}
|
2021-12-14 19:25:07 -08:00
|
|
|
|
2022-02-16 15:45:35 -08:00
|
|
|
|
|
|
|
let currentlyLoadingTestFile: string | null = null;
|
|
|
|
|
|
|
|
export function setCurrentlyLoadingTestFile(file: string | null) {
|
|
|
|
currentlyLoadingTestFile = file;
|
|
|
|
}
|
|
|
|
|
2021-12-14 19:25:07 -08:00
|
|
|
function isComponentImport(filename: string): boolean {
|
2022-02-16 15:45:35 -08:00
|
|
|
if (filename === currentlyLoadingTestFile)
|
2021-12-14 19:25:07 -08:00
|
|
|
return false;
|
2022-02-16 15:45:35 -08:00
|
|
|
return filename.endsWith('.tsx') || filename.endsWith('.jsx');
|
2021-12-14 19:25:07 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
function componentStub(): string {
|
|
|
|
return `module.exports = new Proxy({}, {
|
|
|
|
get: (obj, prop) => prop
|
|
|
|
});`;
|
|
|
|
}
|