diff --git a/.github/actions/git-diff-on-components/dist/index.js b/.github/actions/git-diff-on-components/dist/index.js index b9ce8af9400e5..1ef76ffbda50c 100644 --- a/.github/actions/git-diff-on-components/dist/index.js +++ b/.github/actions/git-diff-on-components/dist/index.js @@ -1,14 +1,18 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 7351: +/***/ 87351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -21,13 +25,13 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(2037)); +const os = __importStar(__nccwpck_require__(22037)); const utils_1 = __nccwpck_require__(5278); /** * Commands @@ -83,13 +87,13 @@ class Command { } } function escapeData(s) { - return utils_1.toCommandValue(s) + return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { - return utils_1.toCommandValue(s) + return (0, utils_1.toCommandValue)(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') @@ -100,14 +104,18 @@ function escapeProperty(s) { /***/ }), -/***/ 2186: +/***/ 42186: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -120,7 +128,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -134,13 +142,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(7351); +exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +const command_1 = __nccwpck_require__(87351); const file_command_1 = __nccwpck_require__(717); const utils_1 = __nccwpck_require__(5278); -const os = __importStar(__nccwpck_require__(2037)); -const path = __importStar(__nccwpck_require__(1017)); -const oidc_utils_1 = __nccwpck_require__(8041); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const oidc_utils_1 = __nccwpck_require__(98041); /** * The code to exit an action */ @@ -154,7 +162,7 @@ var ExitCode; * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +})(ExitCode || (exports.ExitCode = ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- @@ -165,17 +173,13 @@ var ExitCode; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); + const convertedVal = (0, utils_1.toCommandValue)(val); process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { - const delimiter = '_GitHubActionsFileCommandDelimeter_'; - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); + return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); } + (0, command_1.issueCommand)('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -183,7 +187,7 @@ exports.exportVariable = exportVariable; * @param secret value of the secret */ function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); + (0, command_1.issueCommand)('add-mask', {}, secret); } exports.setSecret = setSecret; /** @@ -193,10 +197,10 @@ exports.setSecret = setSecret; function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { - file_command_1.issueCommand('PATH', inputPath); + (0, file_command_1.issueFileCommand)('PATH', inputPath); } else { - command_1.issueCommand('add-path', {}, inputPath); + (0, command_1.issueCommand)('add-path', {}, inputPath); } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } @@ -233,7 +237,10 @@ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); - return inputs; + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); } exports.getMultilineInput = getMultilineInput; /** @@ -266,8 +273,12 @@ exports.getBooleanInput = getBooleanInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, value); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); } exports.setOutput = setOutput; /** @@ -276,7 +287,7 @@ exports.setOutput = setOutput; * */ function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); + (0, command_1.issue)('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- @@ -307,7 +318,7 @@ exports.isDebug = isDebug; * @param message debug message */ function debug(message) { - command_1.issueCommand('debug', {}, message); + (0, command_1.issueCommand)('debug', {}, message); } exports.debug = debug; /** @@ -316,7 +327,7 @@ exports.debug = debug; * @param properties optional properties to add to the annotation. */ function error(message, properties = {}) { - command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** @@ -325,7 +336,7 @@ exports.error = error; * @param properties optional properties to add to the annotation. */ function warning(message, properties = {}) { - command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.warning = warning; /** @@ -334,7 +345,7 @@ exports.warning = warning; * @param properties optional properties to add to the annotation. */ function notice(message, properties = {}) { - command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); + (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } exports.notice = notice; /** @@ -353,14 +364,14 @@ exports.info = info; * @param name The name of the output group */ function startGroup(name) { - command_1.issue('group', name); + (0, command_1.issue)('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { - command_1.issue('endgroup'); + (0, command_1.issue)('endgroup'); } exports.endGroup = endGroup; /** @@ -396,7 +407,11 @@ exports.group = group; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); } exports.saveState = saveState; /** @@ -418,12 +433,12 @@ exports.getIDToken = getIDToken; /** * Summary exports */ -var summary_1 = __nccwpck_require__(1327); +var summary_1 = __nccwpck_require__(81327); Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); /** * @deprecated use core.summary */ -var summary_2 = __nccwpck_require__(1327); +var summary_2 = __nccwpck_require__(81327); Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); /** * Path exports @@ -432,6 +447,10 @@ var path_utils_1 = __nccwpck_require__(2981); Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +/** + * Platform utilities exports + */ +exports.platform = __importStar(__nccwpck_require__(85243)); //# sourceMappingURL=core.js.map /***/ }), @@ -444,7 +463,11 @@ Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: funct // For internal use, subject to change. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -457,18 +480,19 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issueCommand = void 0; +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(7147)); -const os = __importStar(__nccwpck_require__(2037)); +const crypto = __importStar(__nccwpck_require__(6113)); +const fs = __importStar(__nccwpck_require__(57147)); +const os = __importStar(__nccwpck_require__(22037)); const utils_1 = __nccwpck_require__(5278); -function issueCommand(command, message) { +function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); @@ -476,16 +500,31 @@ function issueCommand(command, message) { if (!fs.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { encoding: 'utf8' }); } -exports.issueCommand = issueCommand; +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + const convertedValue = (0, utils_1.toCommandValue)(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; //# sourceMappingURL=file-command.js.map /***/ }), -/***/ 8041: +/***/ 98041: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -501,9 +540,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(6255); -const auth_1 = __nccwpck_require__(5526); -const core_1 = __nccwpck_require__(2186); +const http_client_1 = __nccwpck_require__(96255); +const auth_1 = __nccwpck_require__(35526); +const core_1 = __nccwpck_require__(42186); class OidcClient { static createHttpClient(allowRetry = true, maxRetry = 10) { const requestOptions = { @@ -535,7 +574,7 @@ class OidcClient { .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); + Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { @@ -553,9 +592,9 @@ class OidcClient { const encodedAudience = encodeURIComponent(audience); id_token_url = `${id_token_url}&audience=${encodedAudience}`; } - core_1.debug(`ID token url is ${id_token_url}`); + (0, core_1.debug)(`ID token url is ${id_token_url}`); const id_token = yield OidcClient.getCall(id_token_url); - core_1.setSecret(id_token); + (0, core_1.setSecret)(id_token); return id_token; } catch (error) { @@ -576,7 +615,11 @@ exports.OidcClient = OidcClient; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -589,13 +632,13 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(1017)); +const path = __importStar(__nccwpck_require__(71017)); /** * toPosixPath converts the given path to the posix form. On Windows, \\ will be * replaced with /. @@ -634,7 +677,108 @@ exports.toPlatformPath = toPlatformPath; /***/ }), -/***/ 1327: +/***/ 85243: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; +const os_1 = __importDefault(__nccwpck_require__(22037)); +const exec = __importStar(__nccwpck_require__(71514)); +const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { + silent: true + }); + const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; +}); +const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d; + const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { + silent: true + }); + const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; + const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; + return { + name, + version + }; +}); +const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { + silent: true + }); + const [name, version] = stdout.trim().split('\n'); + return { + name, + version + }; +}); +exports.platform = os_1.default.platform(); +exports.arch = os_1.default.arch(); +exports.isWindows = exports.platform === 'win32'; +exports.isMacOS = exports.platform === 'darwin'; +exports.isLinux = exports.platform === 'linux'; +function getDetails() { + return __awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (exports.isWindows + ? getWindowsInfo() + : exports.isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform: exports.platform, + arch: exports.arch, + isWindows: exports.isWindows, + isMacOS: exports.isMacOS, + isLinux: exports.isLinux }); + }); +} +exports.getDetails = getDetails; +//# sourceMappingURL=platform.js.map + +/***/ }), + +/***/ 81327: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -650,8 +794,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(2037); -const fs_1 = __nccwpck_require__(7147); +const os_1 = __nccwpck_require__(22037); +const fs_1 = __nccwpck_require__(57147); const { access, appendFile, writeFile } = fs_1.promises; exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; @@ -971,7 +1115,7 @@ exports.toCommandProperties = toCommandProperties; /***/ }), -/***/ 1514: +/***/ 71514: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1006,8 +1150,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getExecOutput = exports.exec = void 0; -const string_decoder_1 = __nccwpck_require__(1576); -const tr = __importStar(__nccwpck_require__(8159)); +const string_decoder_1 = __nccwpck_require__(71576); +const tr = __importStar(__nccwpck_require__(88159)); /** * Exec a command. * Output will be streamed to the live console. @@ -1081,7 +1225,7 @@ exports.getExecOutput = getExecOutput; /***/ }), -/***/ 8159: +/***/ 88159: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1116,13 +1260,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.argStringToArray = exports.ToolRunner = void 0; -const os = __importStar(__nccwpck_require__(2037)); -const events = __importStar(__nccwpck_require__(2361)); -const child = __importStar(__nccwpck_require__(2081)); -const path = __importStar(__nccwpck_require__(1017)); -const io = __importStar(__nccwpck_require__(7436)); -const ioUtil = __importStar(__nccwpck_require__(1962)); -const timers_1 = __nccwpck_require__(9512); +const os = __importStar(__nccwpck_require__(22037)); +const events = __importStar(__nccwpck_require__(82361)); +const child = __importStar(__nccwpck_require__(32081)); +const path = __importStar(__nccwpck_require__(71017)); +const io = __importStar(__nccwpck_require__(47351)); +const ioUtil = __importStar(__nccwpck_require__(81962)); +const timers_1 = __nccwpck_require__(39512); /* eslint-disable @typescript-eslint/unbound-method */ const IS_WINDOWS = process.platform === 'win32'; /* @@ -1706,7 +1850,7 @@ class ExecState extends events.EventEmitter { /***/ }), -/***/ 5526: +/***/ 35526: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -1794,7 +1938,7 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /***/ }), -/***/ 6255: +/***/ 96255: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -1802,7 +1946,11 @@ exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHand /* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -1815,7 +1963,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -1830,10 +1978,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(3685)); -const https = __importStar(__nccwpck_require__(5687)); -const pm = __importStar(__nccwpck_require__(9835)); -const tunnel = __importStar(__nccwpck_require__(4294)); +const http = __importStar(__nccwpck_require__(13685)); +const https = __importStar(__nccwpck_require__(95687)); +const pm = __importStar(__nccwpck_require__(19835)); +const tunnel = __importStar(__nccwpck_require__(74294)); +const undici_1 = __nccwpck_require__(41773); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -1863,16 +2012,16 @@ var HttpCodes; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); +})(Headers || (exports.Headers = Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com @@ -1923,6 +2072,19 @@ class HttpClientResponse { })); }); } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { @@ -2228,6 +2390,15 @@ class HttpClient { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; @@ -2275,7 +2446,7 @@ class HttpClient { if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (this._keepAlive && !useProxy) { + if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. @@ -2307,16 +2478,12 @@ class HttpClient { agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { + // if tunneling agent isn't assigned create a new agent + if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options @@ -2327,6 +2494,30 @@ class HttpClient { } return agent; } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); @@ -2406,7 +2597,7 @@ const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCa /***/ }), -/***/ 9835: +/***/ 19835: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -2427,7 +2618,13 @@ function getProxyUrl(reqUrl) { } })(); if (proxyVar) { - return new URL(proxyVar); + try { + return new DecodedURL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new DecodedURL(`http://${proxyVar}`); + } } else { return undefined; @@ -2438,6 +2635,10 @@ function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; @@ -2463,202 +2664,232 @@ function checkBypass(reqUrl) { .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } exports.checkBypass = checkBypass; -//# sourceMappingURL=proxy.js.map - -/***/ }), - -/***/ 1962: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -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()); - }); -}; -var _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rename = exports.readlink = exports.readdir = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; -const fs = __importStar(__nccwpck_require__(7147)); -const path = __importStar(__nccwpck_require__(1017)); -_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; -exports.IS_WINDOWS = process.platform === 'win32'; -function exists(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield exports.stat(fsPath); - } - catch (err) { - if (err.code === 'ENOENT') { - return false; - } - throw err; - } - return true; - }); +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } -exports.exists = exists; -function isDirectory(fsPath, useStat = false) { - return __awaiter(this, void 0, void 0, function* () { - const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); - return stats.isDirectory(); - }); -} -exports.isDirectory = isDirectory; -/** - * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: - * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). - */ -function isRooted(p) { - p = normalizeSeparators(p); - if (!p) { - throw new Error('isRooted() parameter "p" cannot be empty'); +class DecodedURL extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); } - if (exports.IS_WINDOWS) { - return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello - ); // e.g. C: or C:\hello + get username() { + return this._decodedUsername; } - return p.startsWith('/'); -} -exports.isRooted = isRooted; -/** - * Best effort attempt to determine whether a file exists and is executable. - * @param filePath file path to check - * @param extensions additional file extensions to try - * @return if file exists and is executable, returns the file path. otherwise empty string. - */ -function tryGetExecutablePath(filePath, extensions) { - return __awaiter(this, void 0, void 0, function* () { - let stats = undefined; - try { - // test file exists - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // on Windows, test for valid extension - const upperExt = path.extname(filePath).toUpperCase(); - if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { - return filePath; - } - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - // try each extension - const originalFilePath = filePath; - for (const extension of extensions) { - filePath = originalFilePath + extension; - stats = undefined; - try { - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // preserve the case of the actual file (since an extension was appended) - try { - const directory = path.dirname(filePath); - const upperName = path.basename(filePath).toUpperCase(); - for (const actualName of yield exports.readdir(directory)) { - if (upperName === actualName.toUpperCase()) { - filePath = path.join(directory, actualName); - break; - } - } - } - catch (err) { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); - } - return filePath; - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - } - return ''; - }); -} -exports.tryGetExecutablePath = tryGetExecutablePath; -function normalizeSeparators(p) { - p = p || ''; - if (exports.IS_WINDOWS) { - // convert slashes on Windows - p = p.replace(/\//g, '\\'); - // remove redundant slashes - return p.replace(/\\\\+/g, '\\'); + get password() { + return this._decodedPassword; } - // remove redundant slashes - return p.replace(/\/\/+/g, '/'); -} -// on Mac/Linux, test the execute bit -// R W X R W X R W X -// 256 128 64 32 16 8 4 2 1 -function isUnixExecutable(stats) { - return ((stats.mode & 1) > 0 || - ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || - ((stats.mode & 64) > 0 && stats.uid === process.getuid())); } -// Get the path of cmd.exe in windows -function getCmdPath() { - var _a; - return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; -} -exports.getCmdPath = getCmdPath; -//# sourceMappingURL=io-util.js.map +//# sourceMappingURL=proxy.js.map /***/ }), -/***/ 7436: +/***/ 81962: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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()); + }); +}; +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; +const fs = __importStar(__nccwpck_require__(57147)); +const path = __importStar(__nccwpck_require__(71017)); +_a = fs.promises +// export const {open} = 'fs' +, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +// export const {open} = 'fs' +exports.IS_WINDOWS = process.platform === 'win32'; +// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 +exports.UV_FS_O_EXLOCK = 0x10000000; +exports.READONLY = fs.constants.O_RDONLY; +function exists(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exports.stat(fsPath); + } + catch (err) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } + return true; + }); +} +exports.exists = exists; +function isDirectory(fsPath, useStat = false) { + return __awaiter(this, void 0, void 0, function* () { + const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); + return stats.isDirectory(); + }); +} +exports.isDirectory = isDirectory; +/** + * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: + * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). + */ +function isRooted(p) { + p = normalizeSeparators(p); + if (!p) { + throw new Error('isRooted() parameter "p" cannot be empty'); + } + if (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello + } + return p.startsWith('/'); +} +exports.isRooted = isRooted; +/** + * Best effort attempt to determine whether a file exists and is executable. + * @param filePath file path to check + * @param extensions additional file extensions to try + * @return if file exists and is executable, returns the file path. otherwise empty string. + */ +function tryGetExecutablePath(filePath, extensions) { + return __awaiter(this, void 0, void 0, function* () { + let stats = undefined; + try { + // test file exists + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // on Windows, test for valid extension + const upperExt = path.extname(filePath).toUpperCase(); + if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { + return filePath; + } + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + // try each extension + const originalFilePath = filePath; + for (const extension of extensions) { + filePath = originalFilePath + extension; + stats = undefined; + try { + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // preserve the case of the actual file (since an extension was appended) + try { + const directory = path.dirname(filePath); + const upperName = path.basename(filePath).toUpperCase(); + for (const actualName of yield exports.readdir(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = path.join(directory, actualName); + break; + } + } + } + catch (err) { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); + } + return filePath; + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + } + return ''; + }); +} +exports.tryGetExecutablePath = tryGetExecutablePath; +function normalizeSeparators(p) { + p = p || ''; + if (exports.IS_WINDOWS) { + // convert slashes on Windows + p = p.replace(/\//g, '\\'); + // remove redundant slashes + return p.replace(/\\\\+/g, '\\'); + } + // remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +// on Mac/Linux, test the execute bit +// R W X R W X R W X +// 256 128 64 32 16 8 4 2 1 +function isUnixExecutable(stats) { + return ((stats.mode & 1) > 0 || + ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || + ((stats.mode & 64) > 0 && stats.uid === process.getuid())); +} +// Get the path of cmd.exe in windows +function getCmdPath() { + var _a; + return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; +} +exports.getCmdPath = getCmdPath; +//# sourceMappingURL=io-util.js.map + +/***/ }), + +/***/ 47351: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -2693,13 +2924,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; -const assert_1 = __nccwpck_require__(9491); -const childProcess = __importStar(__nccwpck_require__(2081)); -const path = __importStar(__nccwpck_require__(1017)); -const util_1 = __nccwpck_require__(3837); -const ioUtil = __importStar(__nccwpck_require__(1962)); -const exec = util_1.promisify(childProcess.exec); -const execFile = util_1.promisify(childProcess.execFile); +const assert_1 = __nccwpck_require__(39491); +const path = __importStar(__nccwpck_require__(71017)); +const ioUtil = __importStar(__nccwpck_require__(81962)); /** * Copies a file or folder. * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js @@ -2780,61 +3007,23 @@ exports.mv = mv; function rmRF(inputPath) { return __awaiter(this, void 0, void 0, function* () { if (ioUtil.IS_WINDOWS) { - // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another - // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del. // Check for invalid characters // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file if (/[*"<>|]/.test(inputPath)) { throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); } - try { - const cmdPath = ioUtil.getCmdPath(); - if (yield ioUtil.isDirectory(inputPath, true)) { - yield exec(`${cmdPath} /s /c "rd /s /q "%inputPath%""`, { - env: { inputPath } - }); - } - else { - yield exec(`${cmdPath} /s /c "del /f /a "%inputPath%""`, { - env: { inputPath } - }); - } - } - catch (err) { - // if you try to delete a file that doesn't exist, desired result is achieved - // other errors are valid - if (err.code !== 'ENOENT') - throw err; - } - // Shelling out fails to remove a symlink folder with missing source, this unlink catches that - try { - yield ioUtil.unlink(inputPath); - } - catch (err) { - // if you try to delete a file that doesn't exist, desired result is achieved - // other errors are valid - if (err.code !== 'ENOENT') - throw err; - } } - else { - let isDir = false; - try { - isDir = yield ioUtil.isDirectory(inputPath); - } - catch (err) { - // if you try to delete a file that doesn't exist, desired result is achieved - // other errors are valid - if (err.code !== 'ENOENT') - throw err; - return; - } - if (isDir) { - yield execFile(`rm`, [`-rf`, `${inputPath}`]); - } - else { - yield ioUtil.unlink(inputPath); - } + try { + // note if path does not exist, error is silent + yield ioUtil.rm(inputPath, { + force: true, + maxRetries: 3, + recursive: true, + retryDelay: 300 + }); + } + catch (err) { + throw new Error(`File was unable to be removed ${err}`); } }); } @@ -3006,14 +3195,14 @@ function copyFile(srcFile, destFile, force) { /***/ }), -/***/ 3803: +/***/ 63803: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; -const fs = __nccwpck_require__(7147); +const fs = __nccwpck_require__(57147); exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, @@ -3033,7 +3222,7 @@ exports.createFileSystemAdapter = createFileSystemAdapter; /***/ }), -/***/ 8838: +/***/ 18838: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -3058,16 +3247,16 @@ exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_B /***/ }), -/***/ 5667: +/***/ 75667: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Settings = exports.scandirSync = exports.scandir = void 0; -const async = __nccwpck_require__(4507); -const sync = __nccwpck_require__(9560); -const settings_1 = __nccwpck_require__(8662); +const async = __nccwpck_require__(84507); +const sync = __nccwpck_require__(69560); +const settings_1 = __nccwpck_require__(88662); exports.Settings = settings_1.default; function scandir(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { @@ -3092,17 +3281,17 @@ function getSettings(settingsOrOptions = {}) { /***/ }), -/***/ 4507: +/***/ 84507: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; -const fsStat = __nccwpck_require__(109); -const rpl = __nccwpck_require__(5288); -const constants_1 = __nccwpck_require__(8838); -const utils = __nccwpck_require__(6297); +const fsStat = __nccwpck_require__(70109); +const rpl = __nccwpck_require__(75288); +const constants_1 = __nccwpck_require__(18838); +const utils = __nccwpck_require__(16297); const common = __nccwpck_require__(3847); function read(directory, settings, callback) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { @@ -3225,16 +3414,16 @@ exports.joinPathSegments = joinPathSegments; /***/ }), -/***/ 9560: +/***/ 69560: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdir = exports.readdirWithFileTypes = exports.read = void 0; -const fsStat = __nccwpck_require__(109); -const constants_1 = __nccwpck_require__(8838); -const utils = __nccwpck_require__(6297); +const fsStat = __nccwpck_require__(70109); +const constants_1 = __nccwpck_require__(18838); +const utils = __nccwpck_require__(16297); const common = __nccwpck_require__(3847); function read(directory, settings) { if (!settings.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { @@ -3287,15 +3476,15 @@ exports.readdir = readdir; /***/ }), -/***/ 8662: +/***/ 88662: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const path = __nccwpck_require__(1017); -const fsStat = __nccwpck_require__(109); -const fs = __nccwpck_require__(3803); +const path = __nccwpck_require__(71017); +const fsStat = __nccwpck_require__(70109); +const fs = __nccwpck_require__(63803); class Settings { constructor(_options = {}) { this._options = _options; @@ -3319,7 +3508,7 @@ exports["default"] = Settings; /***/ }), -/***/ 883: +/***/ 60883: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -3346,27 +3535,27 @@ exports.createDirentFromStats = createDirentFromStats; /***/ }), -/***/ 6297: +/***/ 16297: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fs = void 0; -const fs = __nccwpck_require__(883); +const fs = __nccwpck_require__(60883); exports.fs = fs; /***/ }), -/***/ 2987: +/***/ 32987: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFileSystemAdapter = exports.FILE_SYSTEM_ADAPTER = void 0; -const fs = __nccwpck_require__(7147); +const fs = __nccwpck_require__(57147); exports.FILE_SYSTEM_ADAPTER = { lstat: fs.lstat, stat: fs.stat, @@ -3384,16 +3573,16 @@ exports.createFileSystemAdapter = createFileSystemAdapter; /***/ }), -/***/ 109: +/***/ 70109: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.statSync = exports.stat = exports.Settings = void 0; -const async = __nccwpck_require__(4147); -const sync = __nccwpck_require__(4527); -const settings_1 = __nccwpck_require__(2410); +const async = __nccwpck_require__(34147); +const sync = __nccwpck_require__(34527); +const settings_1 = __nccwpck_require__(12410); exports.Settings = settings_1.default; function stat(path, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { @@ -3418,7 +3607,7 @@ function getSettings(settingsOrOptions = {}) { /***/ }), -/***/ 4147: +/***/ 34147: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -3462,7 +3651,7 @@ function callSuccessCallback(callback, result) { /***/ }), -/***/ 4527: +/***/ 34527: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -3493,13 +3682,13 @@ exports.read = read; /***/ }), -/***/ 2410: +/***/ 12410: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const fs = __nccwpck_require__(2987); +const fs = __nccwpck_require__(32987); class Settings { constructor(_options = {}) { this._options = _options; @@ -3517,17 +3706,17 @@ exports["default"] = Settings; /***/ }), -/***/ 6026: +/***/ 26026: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Settings = exports.walkStream = exports.walkSync = exports.walk = void 0; -const async_1 = __nccwpck_require__(7523); -const stream_1 = __nccwpck_require__(6737); -const sync_1 = __nccwpck_require__(3068); -const settings_1 = __nccwpck_require__(141); +const async_1 = __nccwpck_require__(77523); +const stream_1 = __nccwpck_require__(96737); +const sync_1 = __nccwpck_require__(13068); +const settings_1 = __nccwpck_require__(50141); exports.Settings = settings_1.default; function walk(directory, optionsOrSettingsOrCallback, callback) { if (typeof optionsOrSettingsOrCallback === 'function') { @@ -3559,13 +3748,13 @@ function getSettings(settingsOrOptions = {}) { /***/ }), -/***/ 7523: +/***/ 77523: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const async_1 = __nccwpck_require__(5732); +const async_1 = __nccwpck_require__(55732); class AsyncProvider { constructor(_root, _settings) { this._root = _root; @@ -3597,14 +3786,14 @@ function callSuccessCallback(callback, entries) { /***/ }), -/***/ 6737: +/***/ 96737: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const stream_1 = __nccwpck_require__(2781); -const async_1 = __nccwpck_require__(5732); +const stream_1 = __nccwpck_require__(12781); +const async_1 = __nccwpck_require__(55732); class StreamProvider { constructor(_root, _settings) { this._root = _root; @@ -3639,13 +3828,13 @@ exports["default"] = StreamProvider; /***/ }), -/***/ 3068: +/***/ 13068: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const sync_1 = __nccwpck_require__(3595); +const sync_1 = __nccwpck_require__(13595); class SyncProvider { constructor(_root, _settings) { this._root = _root; @@ -3661,17 +3850,17 @@ exports["default"] = SyncProvider; /***/ }), -/***/ 5732: +/***/ 55732: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const events_1 = __nccwpck_require__(2361); -const fsScandir = __nccwpck_require__(5667); -const fastq = __nccwpck_require__(7340); -const common = __nccwpck_require__(7988); -const reader_1 = __nccwpck_require__(8311); +const events_1 = __nccwpck_require__(82361); +const fsScandir = __nccwpck_require__(75667); +const fastq = __nccwpck_require__(1213); +const common = __nccwpck_require__(97988); +const reader_1 = __nccwpck_require__(88311); class AsyncReader extends reader_1.default { constructor(_root, _settings) { super(_root, _settings); @@ -3766,7 +3955,7 @@ exports["default"] = AsyncReader; /***/ }), -/***/ 7988: +/***/ 97988: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -3805,13 +3994,13 @@ exports.joinPathSegments = joinPathSegments; /***/ }), -/***/ 8311: +/***/ 88311: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const common = __nccwpck_require__(7988); +const common = __nccwpck_require__(97988); class Reader { constructor(_root, _settings) { this._root = _root; @@ -3824,15 +4013,15 @@ exports["default"] = Reader; /***/ }), -/***/ 3595: +/***/ 13595: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const fsScandir = __nccwpck_require__(5667); -const common = __nccwpck_require__(7988); -const reader_1 = __nccwpck_require__(8311); +const fsScandir = __nccwpck_require__(75667); +const common = __nccwpck_require__(97988); +const reader_1 = __nccwpck_require__(88311); class SyncReader extends reader_1.default { constructor() { super(...arguments); @@ -3891,14 +4080,14 @@ exports["default"] = SyncReader; /***/ }), -/***/ 141: +/***/ 50141: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const path = __nccwpck_require__(1017); -const fsScandir = __nccwpck_require__(5667); +const path = __nccwpck_require__(71017); +const fsScandir = __nccwpck_require__(75667); class Settings { constructor(_options = {}) { this._options = _options; @@ -3925,7 +4114,7 @@ exports["default"] = Settings; /***/ }), -/***/ 7032: +/***/ 67032: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -4146,18 +4335,18 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.AST_TOKEN_TYPES = exports.AST_NODE_TYPES = void 0; -var ast_spec_1 = __nccwpck_require__(7032); +var ast_spec_1 = __nccwpck_require__(67032); Object.defineProperty(exports, "AST_NODE_TYPES", ({ enumerable: true, get: function () { return ast_spec_1.AST_NODE_TYPES; } })); -var ast_spec_2 = __nccwpck_require__(7032); +var ast_spec_2 = __nccwpck_require__(67032); Object.defineProperty(exports, "AST_TOKEN_TYPES", ({ enumerable: true, get: function () { return ast_spec_2.AST_TOKEN_TYPES; } })); -__exportStar(__nccwpck_require__(5481), exports); -__exportStar(__nccwpck_require__(8443), exports); -__exportStar(__nccwpck_require__(6761), exports); +__exportStar(__nccwpck_require__(75481), exports); +__exportStar(__nccwpck_require__(58443), exports); +__exportStar(__nccwpck_require__(56761), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 5481: +/***/ 75481: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -4170,7 +4359,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 8443: +/***/ 58443: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -4180,7 +4369,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 6761: +/***/ 56761: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -4206,22 +4395,22 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.TSESTree = void 0; -exports.TSESTree = __importStar(__nccwpck_require__(7032)); +exports.TSESTree = __importStar(__nccwpck_require__(67032)); //# sourceMappingURL=ts-estree.js.map /***/ }), -/***/ 8318: +/***/ 78318: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.astConverter = void 0; -const convert_1 = __nccwpck_require__(7078); -const convert_comments_1 = __nccwpck_require__(8571); -const node_utils_1 = __nccwpck_require__(7882); -const simple_traverse_1 = __nccwpck_require__(5783); +const convert_1 = __nccwpck_require__(77078); +const convert_comments_1 = __nccwpck_require__(58571); +const node_utils_1 = __nccwpck_require__(32706); +const simple_traverse_1 = __nccwpck_require__(95783); function astConverter(ast, extra, shouldPreserveNodeMaps) { /** * The TypeScript compiler produced fundamental parse errors when parsing the @@ -4279,7 +4468,7 @@ exports.astConverter = astConverter; /***/ }), -/***/ 8571: +/***/ 58571: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -4305,10 +4494,10 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.convertComments = void 0; -const ts = __importStar(__nccwpck_require__(7414)); -const util_1 = __nccwpck_require__(949); -const node_utils_1 = __nccwpck_require__(7882); -const ts_estree_1 = __nccwpck_require__(7607); +const ts = __importStar(__nccwpck_require__(37414)); +const util_1 = __nccwpck_require__(60949); +const node_utils_1 = __nccwpck_require__(32706); +const ts_estree_1 = __nccwpck_require__(77607); /** * Convert all comments for the given AST. * @param ast the AST object @@ -4345,7 +4534,7 @@ exports.convertComments = convertComments; /***/ }), -/***/ 7078: +/***/ 77078: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -4373,10 +4562,10 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Converter = exports.convertError = void 0; // There's lots of funny stuff due to the typing of ts.Node /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access */ -const ts = __importStar(__nccwpck_require__(7414)); -const node_utils_1 = __nccwpck_require__(7882); -const ts_estree_1 = __nccwpck_require__(7607); -const version_check_1 = __nccwpck_require__(464); +const ts = __importStar(__nccwpck_require__(37414)); +const node_utils_1 = __nccwpck_require__(32706); +const ts_estree_1 = __nccwpck_require__(77607); +const version_check_1 = __nccwpck_require__(63322); const SyntaxKind = ts.SyntaxKind; /** * Extends and formats a given error object @@ -6632,7 +6821,7 @@ exports.Converter = Converter; /***/ }), -/***/ 1857: +/***/ 71857: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6661,10 +6850,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createDefaultProgram = void 0; -const debug_1 = __importDefault(__nccwpck_require__(8237)); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const ts = __importStar(__nccwpck_require__(7414)); -const shared_1 = __nccwpck_require__(2201); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const ts = __importStar(__nccwpck_require__(37414)); +const shared_1 = __nccwpck_require__(62201); const log = (0, debug_1.default)('typescript-eslint:typescript-estree:createDefaultProgram'); /** * @param code The code of the file being linted @@ -6701,7 +6890,7 @@ exports.createDefaultProgram = createDefaultProgram; /***/ }), -/***/ 6864: +/***/ 26864: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6730,9 +6919,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createIsolatedProgram = void 0; -const debug_1 = __importDefault(__nccwpck_require__(8237)); -const ts = __importStar(__nccwpck_require__(7414)); -const shared_1 = __nccwpck_require__(2201); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const ts = __importStar(__nccwpck_require__(37414)); +const shared_1 = __nccwpck_require__(62201); const log = (0, debug_1.default)('typescript-eslint:typescript-estree:createIsolatedProgram'); /** * @param code The code of the file being linted @@ -6786,7 +6975,7 @@ exports.createIsolatedProgram = createIsolatedProgram; /***/ }), -/***/ 8971: +/***/ 88971: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6796,11 +6985,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createProjectProgram = void 0; -const debug_1 = __importDefault(__nccwpck_require__(8237)); -const path_1 = __importDefault(__nccwpck_require__(1017)); -const createWatchProgram_1 = __nccwpck_require__(3947); -const node_utils_1 = __nccwpck_require__(7882); -const shared_1 = __nccwpck_require__(2201); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const createWatchProgram_1 = __nccwpck_require__(73947); +const node_utils_1 = __nccwpck_require__(32706); +const shared_1 = __nccwpck_require__(62201); const log = (0, debug_1.default)('typescript-eslint:typescript-estree:createProjectProgram'); const DEFAULT_EXTRA_FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx']; /** @@ -6854,7 +7043,7 @@ exports.createProjectProgram = createProjectProgram; /***/ }), -/***/ 7888: +/***/ 17888: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6883,9 +7072,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createSourceFile = void 0; -const debug_1 = __importDefault(__nccwpck_require__(8237)); -const ts = __importStar(__nccwpck_require__(7414)); -const shared_1 = __nccwpck_require__(2201); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const ts = __importStar(__nccwpck_require__(37414)); +const shared_1 = __nccwpck_require__(62201); const log = (0, debug_1.default)('typescript-eslint:typescript-estree:createSourceFile'); function createSourceFile(code, extra) { log('Getting AST without type information in %s mode for: %s', extra.jsx ? 'TSX' : 'TS', extra.filePath); @@ -6897,7 +7086,7 @@ exports.createSourceFile = createSourceFile; /***/ }), -/***/ 3947: +/***/ 73947: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -6926,11 +7115,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getProgramsForProjects = exports.createWatchProgram = exports.clearWatchCaches = void 0; -const debug_1 = __importDefault(__nccwpck_require__(8237)); -const fs_1 = __importDefault(__nccwpck_require__(7147)); -const semver_1 = __importDefault(__nccwpck_require__(1383)); -const ts = __importStar(__nccwpck_require__(7414)); -const shared_1 = __nccwpck_require__(2201); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const fs_1 = __importDefault(__nccwpck_require__(57147)); +const semver_1 = __importDefault(__nccwpck_require__(11383)); +const ts = __importStar(__nccwpck_require__(37414)); +const shared_1 = __nccwpck_require__(62201); const log = (0, debug_1.default)('typescript-eslint:typescript-estree:createWatchProgram'); /** * Maps tsconfig paths to their corresponding file contents and resulting watches @@ -7314,7 +7503,7 @@ function maybeInvalidateProgram(existingWatch, filePath, tsconfigPath) { /***/ }), -/***/ 2201: +/***/ 62201: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7343,8 +7532,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getModuleResolver = exports.getAstFromProgram = exports.getScriptKind = exports.getCanonicalFileName = exports.ensureAbsolutePath = exports.createDefaultCompilerOptionsFromExtra = exports.canonicalDirname = exports.CORE_COMPILER_OPTIONS = void 0; -const path_1 = __importDefault(__nccwpck_require__(1017)); -const ts = __importStar(__nccwpck_require__(7414)); +const path_1 = __importDefault(__nccwpck_require__(71017)); +const ts = __importStar(__nccwpck_require__(37414)); /** * Compiler options required to avoid critical functionality issues */ @@ -7448,7 +7637,7 @@ exports.getModuleResolver = getModuleResolver; /***/ }), -/***/ 4183: +/***/ 54183: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7477,11 +7666,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createProgramFromConfigFile = exports.useProvidedPrograms = void 0; -const debug_1 = __importDefault(__nccwpck_require__(8237)); -const fs = __importStar(__nccwpck_require__(7147)); -const path = __importStar(__nccwpck_require__(1017)); -const ts = __importStar(__nccwpck_require__(7414)); -const shared_1 = __nccwpck_require__(2201); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const fs = __importStar(__nccwpck_require__(57147)); +const path = __importStar(__nccwpck_require__(71017)); +const ts = __importStar(__nccwpck_require__(37414)); +const shared_1 = __nccwpck_require__(62201); const log = (0, debug_1.default)('typescript-eslint:typescript-estree:useProvidedProgram'); function useProvidedPrograms(programInstances, extra) { log('Retrieving ast for %s from provided program instance(s)', extra.filePath); @@ -7544,7 +7733,7 @@ function formatDiagnostics(diagnostics) { /***/ }), -/***/ 2942: +/***/ 82942: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7561,29 +7750,29 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.version = exports.visitorKeys = exports.createProgram = exports.clearCaches = exports.simpleTraverse = exports.clearProgramCache = exports.parseWithNodeMaps = exports.parseAndGenerateServices = exports.parse = void 0; -var parser_1 = __nccwpck_require__(1738); +var parser_1 = __nccwpck_require__(71738); Object.defineProperty(exports, "parse", ({ enumerable: true, get: function () { return parser_1.parse; } })); Object.defineProperty(exports, "parseAndGenerateServices", ({ enumerable: true, get: function () { return parser_1.parseAndGenerateServices; } })); Object.defineProperty(exports, "parseWithNodeMaps", ({ enumerable: true, get: function () { return parser_1.parseWithNodeMaps; } })); Object.defineProperty(exports, "clearProgramCache", ({ enumerable: true, get: function () { return parser_1.clearProgramCache; } })); -var simple_traverse_1 = __nccwpck_require__(5783); +var simple_traverse_1 = __nccwpck_require__(95783); Object.defineProperty(exports, "simpleTraverse", ({ enumerable: true, get: function () { return simple_traverse_1.simpleTraverse; } })); -__exportStar(__nccwpck_require__(7607), exports); -var createWatchProgram_1 = __nccwpck_require__(3947); +__exportStar(__nccwpck_require__(77607), exports); +var createWatchProgram_1 = __nccwpck_require__(73947); Object.defineProperty(exports, "clearCaches", ({ enumerable: true, get: function () { return createWatchProgram_1.clearWatchCaches; } })); -var useProvidedPrograms_1 = __nccwpck_require__(4183); +var useProvidedPrograms_1 = __nccwpck_require__(54183); Object.defineProperty(exports, "createProgram", ({ enumerable: true, get: function () { return useProvidedPrograms_1.createProgramFromConfigFile; } })); // re-export for backwards-compat -var visitor_keys_1 = __nccwpck_require__(5530); +var visitor_keys_1 = __nccwpck_require__(25530); Object.defineProperty(exports, "visitorKeys", ({ enumerable: true, get: function () { return visitor_keys_1.visitorKeys; } })); // note - cannot migrate this to an import statement because it will make TSC copy the package.json to the dist folder // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access -exports.version = __nccwpck_require__(3929).version; +exports.version = __nccwpck_require__(73929).version; //# sourceMappingURL=index.js.map /***/ }), -/***/ 2241: +/***/ 82241: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -7849,7 +8038,7 @@ exports.xhtmlEntities = { /***/ }), -/***/ 7882: +/***/ 32706: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -7875,9 +8064,9 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.firstDefined = exports.nodeHasTokens = exports.createError = exports.TSError = exports.convertTokens = exports.convertToken = exports.getTokenType = exports.isChildUnwrappableOptionalChain = exports.isChainExpression = exports.isOptional = exports.isComputedProperty = exports.unescapeStringLiteralText = exports.hasJSXAncestor = exports.findFirstMatchingAncestor = exports.findNextToken = exports.getTSNodeAccessibility = exports.getDeclarationKind = exports.isJSXToken = exports.isToken = exports.getRange = exports.canContainDirective = exports.getLocFor = exports.getLineAndCharacterFor = exports.getBinaryExpressionType = exports.isJSDocComment = exports.isComment = exports.isComma = exports.getLastModifier = exports.hasModifier = exports.isESTreeClassMember = exports.getTextForTokenKind = exports.isLogicalOperator = exports.isAssignmentOperator = void 0; -const ts = __importStar(__nccwpck_require__(7414)); -const ts_estree_1 = __nccwpck_require__(7607); -const xhtml_entities_1 = __nccwpck_require__(2241); +const ts = __importStar(__nccwpck_require__(37414)); +const ts_estree_1 = __nccwpck_require__(77607); +const xhtml_entities_1 = __nccwpck_require__(82241); const SyntaxKind = ts.SyntaxKind; const LOGICAL_OPERATORS = [ SyntaxKind.BarBarToken, @@ -8415,7 +8604,7 @@ exports.firstDefined = firstDefined; /***/ }), -/***/ 1738: +/***/ 71738: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -8444,21 +8633,21 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.clearParseAndGenerateServicesCalls = exports.clearProgramCache = exports.parseWithNodeMaps = exports.parseAndGenerateServices = exports.parse = void 0; -const debug_1 = __importDefault(__nccwpck_require__(8237)); -const globby_1 = __nccwpck_require__(3398); -const is_glob_1 = __importDefault(__nccwpck_require__(4466)); -const semver_1 = __importDefault(__nccwpck_require__(1383)); -const path_1 = __nccwpck_require__(1017); -const ts = __importStar(__nccwpck_require__(7414)); -const ast_converter_1 = __nccwpck_require__(8318); -const convert_1 = __nccwpck_require__(7078); -const createDefaultProgram_1 = __nccwpck_require__(1857); -const createIsolatedProgram_1 = __nccwpck_require__(6864); -const createProjectProgram_1 = __nccwpck_require__(8971); -const createSourceFile_1 = __nccwpck_require__(7888); -const semantic_or_syntactic_errors_1 = __nccwpck_require__(6909); -const shared_1 = __nccwpck_require__(2201); -const useProvidedPrograms_1 = __nccwpck_require__(4183); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const globby_1 = __nccwpck_require__(43398); +const is_glob_1 = __importDefault(__nccwpck_require__(34466)); +const semver_1 = __importDefault(__nccwpck_require__(11383)); +const path_1 = __nccwpck_require__(71017); +const ts = __importStar(__nccwpck_require__(37414)); +const ast_converter_1 = __nccwpck_require__(78318); +const convert_1 = __nccwpck_require__(77078); +const createDefaultProgram_1 = __nccwpck_require__(71857); +const createIsolatedProgram_1 = __nccwpck_require__(26864); +const createProjectProgram_1 = __nccwpck_require__(88971); +const createSourceFile_1 = __nccwpck_require__(17888); +const semantic_or_syntactic_errors_1 = __nccwpck_require__(16909); +const shared_1 = __nccwpck_require__(62201); +const useProvidedPrograms_1 = __nccwpck_require__(54183); const log = (0, debug_1.default)('typescript-eslint:typescript-estree:parser'); /** * This needs to be kept in sync with the top-level README.md in the @@ -8955,7 +9144,7 @@ exports.parseAndGenerateServices = parseAndGenerateServices; /***/ }), -/***/ 6909: +/***/ 16909: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -8981,7 +9170,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getFirstSemanticOrSyntacticError = void 0; -const ts = __importStar(__nccwpck_require__(7414)); +const ts = __importStar(__nccwpck_require__(37414)); /** * By default, diagnostics from the TypeScript compiler contain all errors - regardless of whether * they are related to generic ECMAScript standards, or TypeScript-specific constructs. @@ -9074,14 +9263,14 @@ function convertDiagnosticToSemanticOrSyntacticError(diagnostic) { /***/ }), -/***/ 5783: +/***/ 95783: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.simpleTraverse = void 0; -const visitor_keys_1 = __nccwpck_require__(5530); +const visitor_keys_1 = __nccwpck_require__(25530); // eslint-disable-next-line @typescript-eslint/no-explicit-any function isValidNode(x) { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access @@ -9146,7 +9335,7 @@ const types_1 = __nccwpck_require__(3742); /***/ }), -/***/ 7607: +/***/ 77607: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -9168,13 +9357,13 @@ var types_1 = __nccwpck_require__(3742); Object.defineProperty(exports, "AST_NODE_TYPES", ({ enumerable: true, get: function () { return types_1.AST_NODE_TYPES; } })); Object.defineProperty(exports, "AST_TOKEN_TYPES", ({ enumerable: true, get: function () { return types_1.AST_TOKEN_TYPES; } })); Object.defineProperty(exports, "TSESTree", ({ enumerable: true, get: function () { return types_1.TSESTree; } })); -__exportStar(__nccwpck_require__(6092), exports); +__exportStar(__nccwpck_require__(76092), exports); __exportStar(__nccwpck_require__(5985), exports); //# sourceMappingURL=index.js.map /***/ }), -/***/ 6092: +/***/ 76092: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -9184,7 +9373,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 464: +/***/ 63322: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -9210,8 +9399,8 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.typescriptVersionIsAtLeast = void 0; -const semver = __importStar(__nccwpck_require__(1383)); -const ts = __importStar(__nccwpck_require__(7414)); +const semver = __importStar(__nccwpck_require__(11383)); +const ts = __importStar(__nccwpck_require__(37414)); function semverCheck(version) { return semver.satisfies(ts.version, `>= ${version}.0 || >= ${version}.1-rc || >= ${version}.0-beta`, { includePrerelease: true, @@ -9233,36 +9422,36 @@ for (const version of versions) { /***/ }), -/***/ 7633: +/***/ 77633: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getKeys = void 0; -const eslint_visitor_keys_1 = __nccwpck_require__(7185); +const eslint_visitor_keys_1 = __nccwpck_require__(37185); const getKeys = eslint_visitor_keys_1.getKeys; exports.getKeys = getKeys; //# sourceMappingURL=get-keys.js.map /***/ }), -/***/ 5530: +/***/ 25530: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.visitorKeys = exports.getKeys = void 0; -var get_keys_1 = __nccwpck_require__(7633); +var get_keys_1 = __nccwpck_require__(77633); Object.defineProperty(exports, "getKeys", ({ enumerable: true, get: function () { return get_keys_1.getKeys; } })); -var visitor_keys_1 = __nccwpck_require__(216); +var visitor_keys_1 = __nccwpck_require__(80216); Object.defineProperty(exports, "visitorKeys", ({ enumerable: true, get: function () { return visitor_keys_1.visitorKeys; } })); //# sourceMappingURL=index.js.map /***/ }), -/***/ 216: +/***/ 80216: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -9288,7 +9477,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.visitorKeys = void 0; -const eslintVisitorKeys = __importStar(__nccwpck_require__(7185)); +const eslintVisitorKeys = __importStar(__nccwpck_require__(37185)); const additionalKeys = { // ES2020 ImportExpression: ['source'], @@ -9421,12 +9610,12 @@ exports.visitorKeys = visitorKeys; /***/ }), -/***/ 5360: +/***/ 55360: /***/ ((module, exports, __nccwpck_require__) => { /* module decorator */ module = __nccwpck_require__.nmd(module); -var Module = (__nccwpck_require__(8188).Module); -var nodePath = __nccwpck_require__(1017); +var Module = (__nccwpck_require__(98188).Module); +var nodePath = __nccwpck_require__(71017); var appModulePaths = []; var old_nodeModulePaths = Module._nodeModulePaths; @@ -9537,7 +9726,7 @@ exports.enableForDir = enableForDir; /***/ }), -/***/ 9600: +/***/ 99600: /***/ ((module) => { "use strict"; @@ -9550,7 +9739,7 @@ module.exports = (...arguments_) => { /***/ }), -/***/ 6848: +/***/ 76848: /***/ ((module) => { "use strict"; @@ -9852,10 +10041,10 @@ function range(a, b, str) { /***/ }), -/***/ 3717: +/***/ 33717: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var concatMap = __nccwpck_require__(6891); +var concatMap = __nccwpck_require__(86891); var balanced = __nccwpck_require__(9417); module.exports = expandTop; @@ -9919,10 +10108,13 @@ function parseCommaParts(str) { return parts; } -function expandTop(str) { +function expandTop(str, options) { if (!str) return []; + options = options || {}; + var max = options.max == null ? Infinity : options.max; + // I don't know why Bash 4.3 does this, but it does. // Anything starting with {} will have the first two bytes preserved // but *only* at the top level, so {},a}b will not expand to anything, @@ -9933,7 +10125,7 @@ function expandTop(str) { str = '\\{\\}' + str.substr(2); } - return expand(escapeBraces(str), true).map(unescapeBraces); + return expand(escapeBraces(str), max, true).map(unescapeBraces); } function identity(e) { @@ -9954,122 +10146,127 @@ function gte(i, y) { return i >= y; } -function expand(str, isTop) { +function expand(str, max, isTop) { var expansions = []; - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); + // The `{a},b}` rewrite below restarts expansion on a rewritten string with + // the same `max` and `isTop = true`. Loop instead of recursing so a long run + // of non-expanding `{}` groups can't exhaust the call stack. + for (;;) { + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,(?!,).*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + isTop = true + continue + } + return [str]; } - return [str]; - } - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], max, false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, max, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } } } - } - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, max, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.max(Math.abs(numeric(n[2])), 1) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; - - var N; - - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - - N = []; - - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; + for (var i = x; test(i, y) && N.length < max; i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } } } + N.push(c); } - N.push(c); + } else { + N = concatMap(n, function(el) { return expand(el, max, false) }); } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length && expansions.length < max; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } } - } - return expansions; + return expansions; + } } - /***/ }), -/***/ 610: +/***/ 50610: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const stringify = __nccwpck_require__(8750); -const compile = __nccwpck_require__(9434); -const expand = __nccwpck_require__(5873); -const parse = __nccwpck_require__(6477); +const stringify = __nccwpck_require__(38750); +const compile = __nccwpck_require__(79434); +const expand = __nccwpck_require__(35873); +const parse = __nccwpck_require__(96477); /** * Expand the given pattern or create a regex-compatible string. @@ -10089,8 +10286,8 @@ const braces = (input, options = {}) => { let output = []; if (Array.isArray(input)) { - for (let pattern of input) { - let result = braces.create(pattern, options); + for (const pattern of input) { + const result = braces.create(pattern, options); if (Array.isArray(result)) { output.push(...result); } else { @@ -10224,7 +10421,7 @@ braces.create = (input, options = {}) => { return [input]; } - return options.expand !== true + return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); }; @@ -10238,40 +10435,42 @@ module.exports = braces; /***/ }), -/***/ 9434: +/***/ 79434: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const fill = __nccwpck_require__(6330); -const utils = __nccwpck_require__(5207); +const utils = __nccwpck_require__(45207); const compile = (ast, options = {}) => { - let walk = (node, parent = {}) => { - let invalidBlock = utils.isInvalidBrace(parent); - let invalidNode = node.invalid === true && options.escapeInvalid === true; - let invalid = invalidBlock === true || invalidNode === true; - let prefix = options.escapeInvalid === true ? '\\' : ''; + const walk = (node, parent = {}) => { + const invalidBlock = utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; + const invalid = invalidBlock === true || invalidNode === true; + const prefix = options.escapeInvalid === true ? '\\' : ''; let output = ''; if (node.isOpen === true) { return prefix + node.value; } + if (node.isClose === true) { + console.log('node.isClose', prefix, node.value); return prefix + node.value; } if (node.type === 'open') { - return invalid ? (prefix + node.value) : '('; + return invalid ? prefix + node.value : '('; } if (node.type === 'close') { - return invalid ? (prefix + node.value) : ')'; + return invalid ? prefix + node.value : ')'; } if (node.type === 'comma') { - return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|'); + return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; } if (node.value) { @@ -10279,8 +10478,8 @@ const compile = (ast, options = {}) => { } if (node.nodes && node.ranges > 0) { - let args = utils.reduce(node.nodes); - let range = fill(...args, { ...options, wrap: false, toRegex: true }); + const args = utils.reduce(node.nodes); + const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true }); if (range.length !== 0) { return args.length > 1 && range.length > 1 ? `(${range})` : range; @@ -10288,10 +10487,11 @@ const compile = (ast, options = {}) => { } if (node.nodes) { - for (let child of node.nodes) { + for (const child of node.nodes) { output += walk(child, node); } } + return output; }; @@ -10303,14 +10503,14 @@ module.exports = compile; /***/ }), -/***/ 8774: +/***/ 18774: /***/ ((module) => { "use strict"; module.exports = { - MAX_LENGTH: 1024 * 64, + MAX_LENGTH: 10000, // Digits CHAR_0: '0', /* 0 */ @@ -10368,18 +10568,18 @@ module.exports = { /***/ }), -/***/ 5873: +/***/ 35873: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const fill = __nccwpck_require__(6330); -const stringify = __nccwpck_require__(8750); -const utils = __nccwpck_require__(5207); +const stringify = __nccwpck_require__(38750); +const utils = __nccwpck_require__(45207); const append = (queue = '', stash = '', enclose = false) => { - let result = []; + const result = []; queue = [].concat(queue); stash = [].concat(stash); @@ -10389,15 +10589,15 @@ const append = (queue = '', stash = '', enclose = false) => { return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; } - for (let item of queue) { + for (const item of queue) { if (Array.isArray(item)) { - for (let value of item) { + for (const value of item) { result.push(append(value, stash, enclose)); } } else { for (let ele of stash) { if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; - result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele)); + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); } } } @@ -10405,9 +10605,9 @@ const append = (queue = '', stash = '', enclose = false) => { }; const expand = (ast, options = {}) => { - let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit; - let walk = (node, parent = {}) => { + const walk = (node, parent = {}) => { node.queue = []; let p = parent; @@ -10429,7 +10629,7 @@ const expand = (ast, options = {}) => { } if (node.nodes && node.ranges > 0) { - let args = utils.reduce(node.nodes); + const args = utils.reduce(node.nodes); if (utils.exceedsLimit(...args, options.step, rangeLimit)) { throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); @@ -10445,7 +10645,7 @@ const expand = (ast, options = {}) => { return; } - let enclose = utils.encloseBrace(node); + const enclose = utils.encloseBrace(node); let queue = node.queue; let block = node; @@ -10455,7 +10655,7 @@ const expand = (ast, options = {}) => { } for (let i = 0; i < node.nodes.length; i++) { - let child = node.nodes[i]; + const child = node.nodes[i]; if (child.type === 'comma' && node.type === 'brace') { if (i === 1) queue.push(''); @@ -10489,13 +10689,13 @@ module.exports = expand; /***/ }), -/***/ 6477: +/***/ 96477: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const stringify = __nccwpck_require__(8750); +const stringify = __nccwpck_require__(38750); /** * Constants @@ -10517,7 +10717,7 @@ const { CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE -} = __nccwpck_require__(8774); +} = __nccwpck_require__(18774); /** * parse @@ -10528,22 +10728,21 @@ const parse = (input, options = {}) => { throw new TypeError('Expected a string'); } - let opts = options || {}; - let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + const opts = options || {}; + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; if (input.length > max) { throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); } - let ast = { type: 'root', input, nodes: [] }; - let stack = [ast]; + const ast = { type: 'root', input, nodes: [] }; + const stack = [ast]; let block = ast; let prev = ast; let brackets = 0; - let length = input.length; + const length = input.length; let index = 0; let depth = 0; let value; - let memo = {}; /** * Helpers @@ -10606,7 +10805,6 @@ const parse = (input, options = {}) => { if (value === CHAR_LEFT_SQUARE_BRACKET) { brackets++; - let closed = true; let next; while (index < length && (next = advance())) { @@ -10662,7 +10860,7 @@ const parse = (input, options = {}) => { */ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { - let open = value; + const open = value; let next; if (options.keepQuotes !== true) { @@ -10694,8 +10892,8 @@ const parse = (input, options = {}) => { if (value === CHAR_LEFT_CURLY_BRACE) { depth++; - let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; - let brace = { + const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + const brace = { type: 'brace', open: true, close: false, @@ -10722,7 +10920,7 @@ const parse = (input, options = {}) => { continue; } - let type = 'close'; + const type = 'close'; block = stack.pop(); block.close = true; @@ -10740,7 +10938,7 @@ const parse = (input, options = {}) => { if (value === CHAR_COMMA && depth > 0) { if (block.ranges > 0) { block.ranges = 0; - let open = block.nodes.shift(); + const open = block.nodes.shift(); block.nodes = [open, { type: 'text', value: stringify(block) }]; } @@ -10754,7 +10952,7 @@ const parse = (input, options = {}) => { */ if (value === CHAR_DOT && depth > 0 && block.commas === 0) { - let siblings = block.nodes; + const siblings = block.nodes; if (depth === 0 || siblings.length === 0) { push({ type: 'text', value }); @@ -10781,7 +10979,7 @@ const parse = (input, options = {}) => { if (prev.type === 'range') { siblings.pop(); - let before = siblings[siblings.length - 1]; + const before = siblings[siblings.length - 1]; before.value += prev.value + value; prev = before; block.ranges--; @@ -10814,8 +11012,8 @@ const parse = (input, options = {}) => { }); // get the location of the block on parent.nodes (block's siblings) - let parent = stack[stack.length - 1]; - let index = parent.nodes.indexOf(block); + const parent = stack[stack.length - 1]; + const index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes parent.nodes.splice(index, 1, ...block.nodes); } @@ -10830,18 +11028,18 @@ module.exports = parse; /***/ }), -/***/ 8750: +/***/ 38750: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const utils = __nccwpck_require__(5207); +const utils = __nccwpck_require__(45207); module.exports = (ast, options = {}) => { - let stringify = (node, parent = {}) => { - let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); - let invalidNode = node.invalid === true && options.escapeInvalid === true; + const stringify = (node, parent = {}) => { + const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + const invalidNode = node.invalid === true && options.escapeInvalid === true; let output = ''; if (node.value) { @@ -10856,7 +11054,7 @@ module.exports = (ast, options = {}) => { } if (node.nodes) { - for (let child of node.nodes) { + for (const child of node.nodes) { output += stringify(child); } } @@ -10870,7 +11068,7 @@ module.exports = (ast, options = {}) => { /***/ }), -/***/ 5207: +/***/ 45207: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -10907,7 +11105,7 @@ exports.exceedsLimit = (min, max, step = 1, limit) => { */ exports.escapeNode = (block, n = 0, type) => { - let node = block.nodes[n]; + const node = block.nodes[n]; if (!node) return; if ((type && node.type === type) || node.type === 'open' || node.type === 'close') { @@ -10976,13 +11174,23 @@ exports.reduce = nodes => nodes.reduce((acc, node) => { exports.flatten = (...args) => { const result = []; + const flat = arr => { for (let i = 0; i < arr.length; i++) { - let ele = arr[i]; - Array.isArray(ele) ? flat(ele, result) : ele !== void 0 && result.push(ele); + const ele = arr[i]; + + if (Array.isArray(ele)) { + flat(ele); + continue; + } + + if (ele !== undefined) { + result.push(ele); + } } return result; }; + flat(args); return result; }; @@ -10990,7 +11198,7 @@ exports.flatten = (...args) => { /***/ }), -/***/ 6891: +/***/ 86891: /***/ ((module) => { module.exports = function (xs, fn) { @@ -11010,7 +11218,7 @@ var isArray = Array.isArray || function (xs) { /***/ }), -/***/ 8222: +/***/ 28222: /***/ ((module, exports, __nccwpck_require__) => { /* eslint-env browser */ @@ -11140,14 +11348,17 @@ function useColors() { return false; } + let m; + // Is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + // eslint-disable-next-line no-return-assign return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // Is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } @@ -11231,7 +11442,7 @@ function save(namespaces) { function load() { let r; try { - r = exports.storage.getItem('debug'); + r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ; } catch (error) { // Swallow // XXX (@Qix-) should we be logging these? @@ -11267,7 +11478,7 @@ function localstorage() { } } -module.exports = __nccwpck_require__(6243)(exports); +module.exports = __nccwpck_require__(46243)(exports); const {formatters} = module.exports; @@ -11286,7 +11497,7 @@ formatters.j = function (v) { /***/ }), -/***/ 6243: +/***/ 46243: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { @@ -11302,7 +11513,7 @@ function setup(env) { createDebug.disable = disable; createDebug.enable = enable; createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(900); + createDebug.humanize = __nccwpck_require__(80900); createDebug.destroy = destroy; Object.keys(env).forEach(key => { @@ -11457,24 +11668,62 @@ function setup(env) { createDebug.names = []; createDebug.skips = []; - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; + const split = (typeof namespaces === 'string' ? namespaces : '') + .trim() + .replace(/\s+/g, ',') + .split(',') + .filter(Boolean); - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; + for (const ns of split) { + if (ns[0] === '-') { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); } + } + } - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + /** + * Checks if the given string matches a namespace template, honoring + * asterisks as wildcards. + * + * @param {String} search + * @param {String} template + * @return {Boolean} + */ + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { + // Match character or proceed with wildcard + if (template[templateIndex] === '*') { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; // Skip the '*' + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition + // Backtrack to the last '*' and try to match more characters + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); + return false; // No match } } + + // Handle trailing '*' in template + while (templateIndex < template.length && template[templateIndex] === '*') { + templateIndex++; + } + + return templateIndex === template.length; } /** @@ -11485,8 +11734,8 @@ function setup(env) { */ function disable() { const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ...createDebug.names, + ...createDebug.skips.map(namespace => '-' + namespace) ].join(','); createDebug.enable(''); return namespaces; @@ -11500,21 +11749,14 @@ function setup(env) { * @api public */ function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - let i; - let len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { return false; } } - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { return true; } } @@ -11522,19 +11764,6 @@ function setup(env) { return false; } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } - /** * Coerce `val`. * @@ -11567,7 +11796,7 @@ module.exports = setup; /***/ }), -/***/ 8237: +/***/ 38237: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** @@ -11576,23 +11805,23 @@ module.exports = setup; */ if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(8222); + module.exports = __nccwpck_require__(28222); } else { - module.exports = __nccwpck_require__(5332); + module.exports = __nccwpck_require__(35332); } /***/ }), -/***/ 5332: +/***/ 35332: /***/ ((module, exports, __nccwpck_require__) => { /** * Module dependencies. */ -const tty = __nccwpck_require__(6224); -const util = __nccwpck_require__(3837); +const tty = __nccwpck_require__(76224); +const util = __nccwpck_require__(73837); /** * This is the Node.js implementation of `debug()`. @@ -11618,7 +11847,7 @@ exports.colors = [6, 2, 3, 4, 5, 1]; try { // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(1415); + const supportsColor = __nccwpck_require__(91415); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ @@ -11776,11 +12005,11 @@ function getDate() { } /** - * Invokes `util.format()` with the specified arguments and writes to stderr. + * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. */ function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); + return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); } /** @@ -11826,7 +12055,7 @@ function init(debug) { } } -module.exports = __nccwpck_require__(6243)(exports); +module.exports = __nccwpck_require__(46243)(exports); const {formatters} = module.exports; @@ -11854,18 +12083,18 @@ formatters.O = function (v) { /***/ }), -/***/ 8013: +/***/ 48013: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const precinct = __nccwpck_require__(8360); -const path = __nccwpck_require__(1017); -const fs = __nccwpck_require__(7147); -const cabinet = __nccwpck_require__(1695); -const debug = __nccwpck_require__(8237)('tree'); -const Config = __nccwpck_require__(3133); +const precinct = __nccwpck_require__(98360); +const path = __nccwpck_require__(71017); +const fs = __nccwpck_require__(57147); +const cabinet = __nccwpck_require__(41695); +const debug = __nccwpck_require__(38237)('tree'); +const Config = __nccwpck_require__(53133); /** * Recursively find all dependencies (avoiding circular) traversing the entire dependency tree @@ -12063,14 +12292,14 @@ function dedupeNonExistent(nonExistent) { /***/ }), -/***/ 3133: +/***/ 53133: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(1017); -const debug = __nccwpck_require__(8237)('tree'); +const path = __nccwpck_require__(71017); +const debug = __nccwpck_require__(38237)('tree'); class Config { constructor(options) { @@ -12094,7 +12323,7 @@ class Config { if ('string' === typeof this.tsConfig) { debug('preparsing the ts config into an object for performance'); - const ts = __nccwpck_require__(7414); + const ts = __nccwpck_require__(37414); const tsParsedConfig = ts.readJsonConfigFile(this.tsConfig, ts.sys.readFile); const obj = ts.parseJsonSourceFileConfigFileContent(tsParsedConfig, ts.sys, path.dirname(this.tsConfig)); this.tsConfig = obj.raw; @@ -12118,16 +12347,16 @@ module.exports = Config; /***/ }), -/***/ 3451: +/***/ 33451: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Walker = __nccwpck_require__(6695); -const types = __nccwpck_require__(6848); +const Walker = __nccwpck_require__(46695); +const types = __nccwpck_require__(76848); const escodegen = __nccwpck_require__(7991); -const getModuleType = __nccwpck_require__(8173); +const getModuleType = __nccwpck_require__(18173); /** * @param {String} src - the string content or AST of an AMD module @@ -12247,14 +12476,14 @@ function getEvaluatedValue(node) { /***/ }), -/***/ 4291: +/***/ 14291: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Walker = __nccwpck_require__(6695); -const types = __nccwpck_require__(6848); +const Walker = __nccwpck_require__(46695); +const types = __nccwpck_require__(76848); /** * @param {String|Object} content - A file's string content or its AST @@ -12299,13 +12528,13 @@ function extractDependencyFromMainRequire(node) { /***/ }), -/***/ 8786: +/***/ 48786: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Walker = __nccwpck_require__(6695); +const Walker = __nccwpck_require__(46695); /** * Extracts the dependencies of the supplied es6 module @@ -12363,15 +12592,15 @@ module.exports = function(src, options) { /***/ }), -/***/ 637: +/***/ 70637: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Walker = __nccwpck_require__(6695); -const gonzales = __nccwpck_require__(9391); -const debug = __nccwpck_require__(8237)('detective-less'); +const Walker = __nccwpck_require__(46695); +const gonzales = __nccwpck_require__(69391); +const debug = __nccwpck_require__(38237)('detective-less'); /** * Extract the @import statements from a given less file's content @@ -12435,15 +12664,15 @@ function extractDependencies(importStatementNode) { /***/ }), -/***/ 2782: +/***/ 62782: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const d = __nccwpck_require__(8237); -const postcss_1 = __nccwpck_require__(7001); -const postCssValuesParser = __nccwpck_require__(3184); -const isUrl = __nccwpck_require__(239); +const d = __nccwpck_require__(38237); +const postcss_1 = __nccwpck_require__(77001); +const postCssValuesParser = __nccwpck_require__(83184); +const isUrl = __nccwpck_require__(70239); const debug = d('detective-postcss'); function detective(src, options = { url: false }) { let references = []; @@ -12529,15 +12758,15 @@ module.exports = detective; /***/ }), -/***/ 2696: +/***/ 12696: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { debuglog } = __nccwpck_require__(3837); -const Walker = __nccwpck_require__(6695); -const sass = __nccwpck_require__(9391); +const { debuglog } = __nccwpck_require__(73837); +const Walker = __nccwpck_require__(46695); +const sass = __nccwpck_require__(69391); const debug = debuglog('detective-sass'); @@ -12598,15 +12827,15 @@ function extractDependencies(importStatementNode) { /***/ }), -/***/ 3841: +/***/ 53841: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const { debuglog } = __nccwpck_require__(3837); -const Walker = __nccwpck_require__(6695); -const sass = __nccwpck_require__(9391); +const { debuglog } = __nccwpck_require__(73837); +const Walker = __nccwpck_require__(46695); +const sass = __nccwpck_require__(69391); const debug = debuglog('detective-scss'); @@ -12667,7 +12896,7 @@ function extractDependencies(importStatementNode) { /***/ }), -/***/ 6569: +/***/ 56569: /***/ ((module) => { "use strict"; @@ -12701,15 +12930,15 @@ module.exports = function(fileContent) { /***/ }), -/***/ 415: +/***/ 30415: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const Parser = __nccwpck_require__(2942); -const Walker = __nccwpck_require__(6695); -const types = __nccwpck_require__(1272); +const Parser = __nccwpck_require__(82942); +const Walker = __nccwpck_require__(46695); +const types = __nccwpck_require__(51272); /** * Extracts the dependencies of the supplied TypeScript module @@ -12814,7 +13043,7 @@ function extractDependencyFromMainRequire(node) { /***/ }), -/***/ 1272: +/***/ 51272: /***/ ((module) => { // Deprecated @@ -13051,13 +13280,13 @@ module.exports.isDynamicImport = function(node) { /***/ }), -/***/ 2738: +/***/ 12738: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(1017); -const pathType = __nccwpck_require__(3433); +const path = __nccwpck_require__(71017); +const pathType = __nccwpck_require__(63433); const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; @@ -13145,23 +13374,35 @@ module.exports.sync = (input, options) => { -const DescriptionFileUtils = __nccwpck_require__(5387); -const getInnerRequest = __nccwpck_require__(9954); +const DescriptionFileUtils = __nccwpck_require__(15387); +const getInnerRequest = __nccwpck_require__(39954); /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonPrimitive} JsonPrimitive */ /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +// Sentinel stored in `_fieldDataCache` when a description file does not +// contain a usable alias field object. Lets us distinguish "not cached yet" +// from "no valid field" without calling back into `getField`. +const NO_FIELD_OBJECT = Symbol("NoFieldObject"); + module.exports = class AliasFieldPlugin { /** * @param {string | ResolveStepHook} source source - * @param {string | Array} field field + * @param {string | string[]} field field * @param {string | ResolveStepHook} target target */ constructor(source, field, target) { this.source = source; this.field = field; this.target = target; + // `this.field` is fixed for the plugin's lifetime, so caching + // per description-file content is safe. The cached value is either + // the resolved alias-map object or the `NO_FIELD_OBJECT` sentinel + // meaning "description file has no usable alias field". + /** @type {WeakMap} */ + this._fieldDataCache = new WeakMap(); } /** @@ -13176,34 +13417,47 @@ module.exports = class AliasFieldPlugin { if (!request.descriptionFileData) return callback(); const innerRequest = getInnerRequest(resolver, request); if (!innerRequest) return callback(); - const fieldData = DescriptionFileUtils.getField( - request.descriptionFileData, - this.field - ); - if (fieldData === null || typeof fieldData !== "object") { - if (resolveContext.log) + const { descriptionFileData } = request; + let fieldData = this._fieldDataCache.get(descriptionFileData); + if (fieldData === undefined) { + const raw = DescriptionFileUtils.getField( + descriptionFileData, + this.field, + ); + fieldData = + raw === null || typeof raw !== "object" + ? NO_FIELD_OBJECT + : /** @type {{ [k: string]: JsonPrimitive }} */ (raw); + this._fieldDataCache.set(descriptionFileData, fieldData); + } + if (fieldData === NO_FIELD_OBJECT) { + if (resolveContext.log) { resolveContext.log( - "Field '" + - this.field + - "' doesn't contain a valid alias configuration" + `Field '${this.field}' doesn't contain a valid alias configuration`, ); + } return callback(); } + /** @type {JsonPrimitive | undefined} */ const data = Object.prototype.hasOwnProperty.call( fieldData, - innerRequest + innerRequest, ) - ? fieldData[innerRequest] + ? /** @type {{ [Key in string]: JsonPrimitive }} */ (fieldData)[ + innerRequest + ] : innerRequest.startsWith("./") - ? fieldData[innerRequest.slice(2)] - : undefined; + ? /** @type {{ [Key in string]: JsonPrimitive }} */ (fieldData)[ + innerRequest.slice(2) + ] + : undefined; if (data === innerRequest) return callback(); if (data === undefined) return callback(); if (data === false) { /** @type {ResolveRequest} */ const ignoreObj = { ...request, - path: false + path: false, }; if (typeof resolveContext.yield === "function") { resolveContext.yield(ignoreObj); @@ -13211,22 +13465,19 @@ module.exports = class AliasFieldPlugin { } return callback(null, ignoreObj); } + /** @type {ResolveRequest} */ const obj = { ...request, - path: request.descriptionFileRoot, - request: data, - fullySpecified: false + path: /** @type {string} */ (request.descriptionFileRoot), + request: /** @type {string} */ (data), + fullySpecified: false, }; resolver.doResolve( target, obj, - "aliased from description file " + - request.descriptionFilePath + - " with mapping '" + - innerRequest + - "' to '" + - data + - "'", + `aliased from description file ${ + request.descriptionFilePath + } with mapping '${innerRequest}' to '${/** @type {string} */ data}'`, resolveContext, (err, result) => { if (err) return callback(err); @@ -13234,7 +13485,7 @@ module.exports = class AliasFieldPlugin { // Don't allow other aliasing or raw request if (result === undefined) return callback(null, null); callback(null, result); - } + }, ); }); } @@ -13243,7 +13494,7 @@ module.exports = class AliasFieldPlugin { /***/ }), -/***/ 7222: +/***/ 77222: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -13254,18 +13505,32 @@ module.exports = class AliasFieldPlugin { -const forEachBail = __nccwpck_require__(4833); -const { PathType, getType } = __nccwpck_require__(4030); - /** @typedef {import("./Resolver")} Resolver */ -/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {{alias: string|Array|false, name: string, onlyModule?: boolean}} AliasOption */ +/** @typedef {string | string[] | false} Alias */ +/** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */ + +const { aliasResolveHandler, compileAliasOptions } = __nccwpck_require__(22943); +/** + * When `alias` is given as an array, the targets are tried in priority + * order and the first matching one wins. Tried-and-failed higher-priority + * targets are recorded on `resolveContext.missingDependencies` (via the + * downstream `FileExistsPlugin`) so that a consumer's watcher can + * invalidate the resolve once one of them appears. The winning target is + * recorded on `resolveContext.fileDependencies`; its removal triggers + * re-resolution, at which point the fallback target is returned. + * + * Callers that cache successful resolves (e.g. webpack's `unsafeCache`) + * are responsible for invalidating those entries when the tracked + * dependencies change -- otherwise a stale path may survive across + * rebuilds even though this plugin itself would return the correct + * fallback on a fresh resolve. + */ module.exports = class AliasPlugin { /** * @param {string | ResolveStepHook} source source - * @param {AliasOption | Array} options options + * @param {AliasOption | AliasOption[]} options options * @param {string | ResolveStepHook} target target */ constructor(source, options, target) { @@ -13280,106 +13545,365 @@ module.exports = class AliasPlugin { */ apply(resolver) { const target = resolver.ensureHook(this.target); - const getAbsolutePathWithSlashEnding = maybeAbsolutePath => { - const type = getType(maybeAbsolutePath); - if (type === PathType.AbsolutePosix || type === PathType.AbsoluteWin) { - return resolver.join(maybeAbsolutePath, "_").slice(0, -1); - } - return null; - }; - const isSubPath = (path, maybeSubPath) => { - const absolutePath = getAbsolutePathWithSlashEnding(maybeSubPath); - if (!absolutePath) return false; - return path.startsWith(absolutePath); - }; + const compiled = compileAliasOptions(resolver, this.options); + resolver .getHook(this.source) .tapAsync("AliasPlugin", (request, resolveContext, callback) => { - const innerRequest = request.request || request.path; - if (!innerRequest) return callback(); - forEachBail( - this.options, - (item, callback) => { - let shouldStop = false; - if ( - innerRequest === item.name || - (!item.onlyModule && - (request.request - ? innerRequest.startsWith(`${item.name}/`) - : isSubPath(innerRequest, item.name))) - ) { - const remainingRequest = innerRequest.substr(item.name.length); - const resolveWithAlias = (alias, callback) => { - if (alias === false) { - /** @type {ResolveRequest} */ - const ignoreObj = { - ...request, - path: false - }; - if (typeof resolveContext.yield === "function") { - resolveContext.yield(ignoreObj); - return callback(null, null); - } - return callback(null, ignoreObj); - } - if ( - innerRequest !== alias && - !innerRequest.startsWith(alias + "/") - ) { - shouldStop = true; - const newRequestStr = alias + remainingRequest; - const obj = { - ...request, - request: newRequestStr, - fullySpecified: false - }; - return resolver.doResolve( - target, - obj, - "aliased with mapping '" + - item.name + - "': '" + - alias + - "' to '" + - newRequestStr + - "'", - resolveContext, - (err, result) => { - if (err) return callback(err); - if (result) return callback(null, result); - return callback(); - } - ); - } - return callback(); - }; - const stoppingCallback = (err, result) => { - if (err) return callback(err); - - if (result) return callback(null, result); - // Don't allow other aliasing or raw request - if (shouldStop) return callback(null, null); - return callback(); - }; - if (Array.isArray(item.alias)) { - return forEachBail( - item.alias, - resolveWithAlias, - stoppingCallback - ); - } else { - return resolveWithAlias(item.alias, stoppingCallback); - } - } - return callback(); - }, - callback + aliasResolveHandler( + resolver, + compiled, + target, + request, + resolveContext, + callback, ); }); } }; +/***/ }), + +/***/ 22943: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const forEachBail = __nccwpck_require__(34833); +const { PathType, getType } = __nccwpck_require__(64030); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveCallback} ResolveCallback */ +/** @typedef {string | string[] | false} Alias */ +/** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */ + +/** + * @typedef {object} CompiledAliasOption + * @property {string} name original alias name + * @property {string} nameWithSlash name + "/" — precomputed to avoid per-resolve concat + * @property {Alias} alias alias target(s) + * @property {boolean} onlyModule normalized onlyModule flag + * @property {string | null} absolutePath absolute form of `name` (with slash ending), null when not absolute + * @property {string | null} wildcardPrefix substring before the single "*" in `name`, null when no wildcard + * @property {string | null} wildcardSuffix substring after the single "*" in `name`, null when no wildcard + * @property {number} firstCharCode first character code of `name` — used as a cheap screen on the hot path. `-1` indicates "matches any first char" (empty wildcard prefix). + * @property {boolean} arrayAlias true when `alias` is an array — precomputed so the hot path skips `Array.isArray` + */ + +/** + * Bucketed view of compiled options used by `aliasResolveHandler` to avoid + * walking the full option list on every resolve. The `all` array preserves + * the legacy linear order (declaration order) for the fallback path. The + * `byFirstChar` map buckets options by the first char code of their `name` + * — each bucket preserves declaration order among its members. The + * `hasAnyFirstChar` flag is true when at least one option matches any + * first char (`firstCharCode === -1`), in which case resolve-time scans + * fall back to `all` to keep declaration-order semantics across buckets. + * The `useBuckets` flag is true only when bucketing would actually help — + * i.e. there are at least 2 distinct first chars AND no empty-prefix + * wildcard. When false, the resolve hot path skips the `Map.get` and + * iterates `all` directly with the per-option first-char-code screen + * (matching the pre-bucketing behavior). This avoids paying for `Map.get` + * on degenerate single-bucket lists like a long chain of aliases that + * all share one first char — the bucket lookup adds overhead without + * narrowing the candidate set, which showed up as a transient-memory + * regression on `pathological-deep-stack`. + * @typedef {object} CompiledAliasOptions + * @property {CompiledAliasOption[]} all declaration-ordered list + * @property {Map} byFirstChar bucketed by first char code + * @property {boolean} hasAnyFirstChar true when an empty-prefix wildcard is present + * @property {boolean} useBuckets true when the bucket fast-path should be used at resolve time + */ + +const EMPTY_LIST = /** @type {CompiledAliasOption[]} */ ([]); +const EMPTY_COMPILED_OPTIONS = /** @type {CompiledAliasOptions} */ ({ + all: EMPTY_LIST, + byFirstChar: new Map(), + hasAnyFirstChar: false, + useBuckets: false, +}); + +/** + * Precompute per-option strings used on every resolve so the hot path in + * `aliasResolveHandler` does no string concatenation / split work per entry. + * Called once per plugin apply — the returned structure is stable for the + * lifetime of the resolver. + * + * Beyond the per-option precompute step, this also partitions the list into + * a `byFirstChar` map so that, when no "empty-prefix" wildcards are + * present, the resolve-time scan only walks options whose `name` starts + * with the same char as the current request. For large alias lists (300+ + * entries) this turns an O(N) screen into O(K) where K is the bucket size + * for the request's first char. + * @param {Resolver} resolver resolver + * @param {AliasOption[]} options options + * @returns {CompiledAliasOptions} compiled options + */ +function compileAliasOptions(resolver, options) { + if (options.length === 0) return EMPTY_COMPILED_OPTIONS; + const all = /** @type {CompiledAliasOption[]} */ ( + Array.from({ length: options.length }) + ); + /** @type {Map} */ + const byFirstChar = new Map(); + let hasAnyFirstChar = false; + for (let i = 0; i < options.length; i++) { + const item = options[i]; + const { name } = item; + let absolutePath = null; + const type = getType(name); + if (type === PathType.AbsolutePosix || type === PathType.AbsoluteWin) { + absolutePath = resolver.join(name, "_").slice(0, -1); + } + const firstStar = name.indexOf("*"); + let wildcardPrefix = null; + let wildcardSuffix = null; + if (firstStar !== -1 && !name.includes("*", firstStar + 1)) { + wildcardPrefix = name.slice(0, firstStar); + wildcardSuffix = name.slice(firstStar + 1); + } + // firstCharCode: used by `aliasResolveHandler` to quickly skip aliases + // whose name can't possibly match the current innerRequest. For a plain + // alias (no wildcard) the first char of the name is also the first char + // of `nameWithSlash` and of `absolutePath` (since the latter is derived + // from name via `resolver.join(name, "_")`, which only appends). For a + // wildcard with a non-empty prefix, the first char of that prefix is + // also the first char of name. Only the `name === "*"` case (empty + // wildcard prefix) can match arbitrary first chars — encode that as -1. + let firstCharCode; + if (wildcardPrefix !== null && wildcardPrefix.length === 0) { + firstCharCode = -1; + } else { + firstCharCode = name.length > 0 ? name.charCodeAt(0) : -1; + } + const compiled = { + name, + nameWithSlash: `${name}/`, + alias: item.alias, + onlyModule: Boolean(item.onlyModule), + absolutePath, + wildcardPrefix, + wildcardSuffix, + firstCharCode, + arrayAlias: Array.isArray(item.alias), + }; + all[i] = compiled; + if (firstCharCode === -1) { + hasAnyFirstChar = true; + } else { + let bucket = byFirstChar.get(firstCharCode); + if (bucket === undefined) { + bucket = []; + byFirstChar.set(firstCharCode, bucket); + } + bucket.push(compiled); + } + } + // Only enable the bucket fast-path when it would actually help. With + // a single bucket (all aliases share one first char, e.g. a chain of + // `chain-0 -> chain-1 -> …` rewrites), the resolve-time `Map.get` + // does no discrimination — every request lands in that one bucket + // or in nothing — and the lookup is overhead compared to walking + // `all` with the per-option first-char-code screen. Requiring 2+ + // distinct first chars matches the cases where bucketing has + // measurable benefit (huge-alias-* / large-alias-list / stack-churn). + const useBuckets = !hasAnyFirstChar && byFirstChar.size >= 2; + return { all, byFirstChar, hasAnyFirstChar, useBuckets }; +} + +/** @typedef {(err?: null | Error, result?: null | ResolveRequest) => void} InnerCallback */ +/** + * @param {Resolver} resolver resolver + * @param {CompiledAliasOptions} options compiled options + * @param {ResolveStepHook} target target + * @param {ResolveRequest} request request + * @param {ResolveContext} resolveContext resolve context + * @param {InnerCallback} callback callback + * @returns {void} + */ +function aliasResolveHandler( + resolver, + options, + target, + request, + resolveContext, + callback, +) { + if (options.all.length === 0) return callback(); + const innerRequest = request.request || request.path; + if (!innerRequest) return callback(); + + // Precompute values used in the inner scan loop so we don't recompute + // them per option. This is meaningful when `options` has hundreds of + // entries (e.g. monorepos with generated alias lists) — see the + // `huge-alias-list` / `huge-alias-miss` benchmarks. + const innerFirstCharCode = innerRequest.charCodeAt(0); + const hasRequestString = Boolean(request.request); + + // Dispatch through the first-char-code bucket when it actually + // narrows the candidate set (`useBuckets` requires 2+ distinct + // first chars and no empty-prefix wildcard). When the field has + // only one first-char bucket — e.g. a long chain of `chain-N` + // aliases that all start with the same char — every request lands + // in that one bucket or nothing, so `Map.get` is overhead vs. just + // walking `all` with the per-option char-code screen. Walking + // `all` also matches the pre-bucketing behavior and keeps the + // `pathological-deep-stack` allocation profile flat. + let scan; + if (options.useBuckets) { + const bucket = options.byFirstChar.get(innerFirstCharCode); + if (bucket === undefined) return callback(); + scan = bucket; + } else { + scan = options.all; + } + + forEachBail( + scan, + (item, callback) => { + // Char-code screen left in for the fallback (`options.all`) path + // where the bucket dispatch above wasn't usable. In the bucket + // path this is always true and folds into a no-op. + const { firstCharCode } = item; + if (firstCharCode !== -1 && firstCharCode !== innerFirstCharCode) { + return callback(); + } + + /** @type {boolean} */ + let shouldStop = false; + + // For absolute-name aliases, accept the normalized + // `absolutePath` form as well as the raw `nameWithSlash`. + // `nameWithSlash` unconditionally appends `/`, so a raw + // windows request with native backslashes + // (e.g. `C:\\abs\\foo\\baz` against `name: "C:\\abs\\foo"`) + // otherwise fails `startsWith("C:\\abs\\foo/")` and is + // silently skipped. Mirroring the `absolutePath` check in + // both branches closes the gap without changing any + // existing matches. + const { absolutePath } = item; + const matchRequest = + innerRequest === item.name || + (!item.onlyModule && + ((hasRequestString && innerRequest.startsWith(item.nameWithSlash)) || + (absolutePath !== null && innerRequest.startsWith(absolutePath)))); + + const matchWildcard = !item.onlyModule && item.wildcardPrefix !== null; + + if (matchRequest || matchWildcard) { + /** + * @param {Alias} alias alias + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @returns {void} + */ + const resolveWithAlias = (alias, callback) => { + if (alias === false) { + /** @type {ResolveRequest} */ + const ignoreObj = { + ...request, + path: false, + }; + if (typeof resolveContext.yield === "function") { + resolveContext.yield(ignoreObj); + return callback(null, null); + } + return callback(null, ignoreObj); + } + + let newRequestStr; + + if ( + matchWildcard && + innerRequest.startsWith( + /** @type {string} */ (item.wildcardPrefix), + ) && + innerRequest.endsWith(/** @type {string} */ (item.wildcardSuffix)) + ) { + const match = innerRequest.slice( + /** @type {string} */ (item.wildcardPrefix).length, + innerRequest.length - + /** @type {string} */ (item.wildcardSuffix).length, + ); + newRequestStr = alias.toString().replace("*", match); + } + + if ( + matchRequest && + innerRequest !== alias && + !innerRequest.startsWith(`${alias}/`) + ) { + /** @type {string} */ + const remainingRequest = innerRequest.slice(item.name.length); + newRequestStr = alias + remainingRequest; + } + + if (newRequestStr !== undefined) { + shouldStop = true; + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: newRequestStr, + fullySpecified: false, + }; + return resolver.doResolve( + target, + obj, + `aliased with mapping '${item.name}': '${alias}' to '${newRequestStr}'`, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + return callback(); + }, + ); + } + return callback(); + }; + + /** + * @param {(null | Error)=} err error + * @param {(null | ResolveRequest)=} result result + * @returns {void} + */ + const stoppingCallback = (err, result) => { + if (err) return callback(err); + + if (result) return callback(null, result); + // Don't allow other aliasing or raw request + if (shouldStop) return callback(null, null); + return callback(); + }; + + if (item.arrayAlias) { + return forEachBail( + /** @type {string[]} */ (item.alias), + resolveWithAlias, + stoppingCallback, + ); + } + return resolveWithAlias(item.alias, stoppingCallback); + } + + return callback(); + }, + callback, + ); +} + +module.exports.aliasResolveHandler = aliasResolveHandler; +module.exports.compileAliasOptions = compileAliasOptions; + + /***/ }), /***/ 5864: @@ -13394,6 +13918,7 @@ module.exports = class AliasPlugin { /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ module.exports = class AppendPlugin { @@ -13417,18 +13942,19 @@ module.exports = class AppendPlugin { resolver .getHook(this.source) .tapAsync("AppendPlugin", (request, resolveContext, callback) => { + /** @type {ResolveRequest} */ const obj = { ...request, path: request.path + this.appending, relativePath: - request.relativePath && request.relativePath + this.appending + request.relativePath && request.relativePath + this.appending, }; resolver.doResolve( target, obj, this.appending, resolveContext, - callback + callback, ); }); } @@ -13437,7 +13963,7 @@ module.exports = class AppendPlugin { /***/ }), -/***/ 8127: +/***/ 68127: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -13448,23 +13974,42 @@ module.exports = class AppendPlugin { -const nextTick = (__nccwpck_require__(7282).nextTick); +// eslint-disable-next-line n/prefer-global/process +const { nextTick } = __nccwpck_require__(77282); /** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").PathLike} PathLike */ +/** @typedef {import("./Resolver").PathOrFileDescriptor} PathOrFileDescriptor */ /** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +/** @typedef {FileSystem & SyncFileSystem} BaseFileSystem */ -const dirname = path => { +/** + * @template T + * @typedef {import("./Resolver").FileSystemCallback} FileSystemCallback + */ + +/** + * @param {string} path path + * @returns {string} dirname + */ +const dirname = (path) => { let idx = path.length - 1; while (idx >= 0) { - const c = path.charCodeAt(idx); + const char = path.charCodeAt(idx); // slash or backslash - if (c === 47 || c === 92) break; + if (char === 47 || char === 92) break; idx--; } if (idx < 0) return ""; return path.slice(0, idx); }; +/** + * @template T + * @param {FileSystemCallback[]} callbacks callbacks + * @param {Error | null} err error + * @param {T} result result + */ const runCallbacks = (callbacks, err, result) => { if (callbacks.length === 1) { callbacks[0](err, result); @@ -13475,19 +14020,132 @@ const runCallbacks = (callbacks, err, result) => { for (const callback of callbacks) { try { callback(err, result); - } catch (e) { - if (!error) error = e; + } catch (err) { + if (!error) error = err; } } callbacks.length = 0; if (error) throw error; }; +// eslint-disable-next-line jsdoc/reject-function-type +/** @typedef {Function} EXPECTED_FUNCTION */ +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {any} EXPECTED_ANY */ + +/** + * The first pending cache hit is held in these slots (a scheduled tick is + * pending iff `firstCallback` is set); later hits from the same synchronous + * burst spill into `dispatchQueue` as flat [callback, err, result] triples + * and are drained by the same tick. This keeps the common single-hit case + * as cheap as a plain `nextTick` while bursts share one tick. + * @type {FileSystemCallback | undefined} + */ +let firstCallback; +/** @type {Error | null} */ +let firstErr = null; +/** @type {EXPECTED_ANY} */ +let firstResult; +/** @type {EXPECTED_ANY[]} */ +let dispatchQueue = []; +let dispatchQueueLength = 0; +/** @type {EXPECTED_ANY[]} */ +let spareQueue = []; +// upper bound on the spill-array capacity kept alive between bursts +const MAX_RETAINED_QUEUE_LENGTH = 1024; + +const runDispatch = () => { + const callback = /** @type {FileSystemCallback} */ ( + firstCallback + ); + const err = firstErr; + const result = firstResult; + // clear before calling: hits made from inside a callback start a new tick + firstCallback = undefined; + firstErr = null; + firstResult = undefined; + if (dispatchQueueLength === 0) { + // single hit: no queue bookkeeping, a throw affects nobody else + callback(err, result); + return; + } + const queue = dispatchQueue; + const length = dispatchQueueLength; + // ping-pong the two arrays so draining never allocates + dispatchQueue = spareQueue; + dispatchQueueLength = 0; + let i = -3; + try { + callback(err, result); + for (i = 0; i < length; i += 3) { + queue[i](queue[i + 1], queue[i + 2]); + } + } finally { + // a throwing callback must not starve the rest: re-schedule the + // remainder ahead of anything scheduled during this drain (matching + // the old per-tick FIFO order) and rethrow + i += 3; + if (i < length) { + if (firstCallback === undefined) { + // no reentrant hit took the slot, so `dispatchQueue` is empty + firstCallback = queue[i]; + firstErr = queue[i + 1]; + firstResult = queue[i + 2]; + nextTick(runDispatch); + for (let j = i + 3; j < length; j++) { + dispatchQueue[dispatchQueueLength++] = queue[j]; + } + } else { + // a reentrant hit claimed the slot (and scheduled the tick); + // displace it behind the remainder to keep FIFO order + const rest = queue.slice(i, length); + rest.push(firstCallback, firstErr, firstResult); + for (let j = 0; j < dispatchQueueLength; j++) { + rest.push(dispatchQueue[j]); + } + [firstCallback, firstErr, firstResult] = rest; + dispatchQueue = rest.slice(3); + dispatchQueueLength = dispatchQueue.length; + } + } + // release references but keep the backing store, so the next burst + // does not have to re-grow the array from scratch + for (let j = 0; j < length; j++) queue[j] = undefined; + // bound the permanently retained capacity after a rare giant burst + if (queue.length > MAX_RETAINED_QUEUE_LENGTH) { + queue.length = MAX_RETAINED_QUEUE_LENGTH; + } + spareQueue = queue; + } +}; + +/** + * Cache hits stay asynchronous, but all hits from the same synchronous + * execution share a single `nextTick` instead of scheduling one each. + * @param {FileSystemCallback} callback callback + * @param {Error | null} err error + * @param {EXPECTED_ANY} result result + */ +const scheduleDispatch = (callback, err, result) => { + if (firstCallback === undefined) { + firstCallback = callback; + firstErr = err; + firstResult = result; + nextTick(runDispatch); + } else { + const queue = dispatchQueue; + queue[dispatchQueueLength] = callback; + queue[dispatchQueueLength + 1] = err; + queue[dispatchQueueLength + 2] = result; + dispatchQueueLength += 3; + } +}; + class OperationMergerBackend { /** - * @param {any} provider async method - * @param {any} syncProvider sync method - * @param {any} providerContext call context for the provider methods + * @param {EXPECTED_FUNCTION | undefined} provider async method in filesystem + * @param {EXPECTED_FUNCTION | undefined} syncProvider sync method in filesystem + * @param {BaseFileSystem} providerContext call context for the provider methods */ constructor(provider, syncProvider, providerContext) { this._provider = provider; @@ -13496,43 +14154,78 @@ class OperationMergerBackend { this._activeAsyncOperations = new Map(); this.provide = this._provider - ? (path, options, callback) => { + ? // Comment to align jsdoc + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {object | FileSystemCallback | undefined} options options + * @param {FileSystemCallback=} callback callback + * @returns {EXPECTED_ANY} result + */ + (path, options, callback) => { if (typeof options === "function") { - callback = options; + callback = + /** @type {FileSystemCallback} */ + (options); options = undefined; } + if ( + typeof path !== "string" && + !Buffer.isBuffer(path) && + !(path instanceof URL) && + typeof path !== "number" + ) { + /** @type {EXPECTED_FUNCTION} */ + (callback)( + new TypeError("path must be a string, Buffer, URL or number"), + ); + return; + } if (options) { - return this._provider.call( + return /** @type {EXPECTED_FUNCTION} */ (this._provider).call( this._providerContext, path, options, - callback + callback, ); } - if (typeof path !== "string") { - callback(new TypeError("path must be a string")); - return; - } let callbacks = this._activeAsyncOperations.get(path); if (callbacks) { callbacks.push(callback); return; } this._activeAsyncOperations.set(path, (callbacks = [callback])); - provider(path, (err, result) => { - this._activeAsyncOperations.delete(path); - runCallbacks(callbacks, err, result); - }); - } + /** @type {EXPECTED_FUNCTION} */ + (provider)( + path, + /** + * @param {Error} err error + * @param {EXPECTED_ANY} result result + */ + (err, result) => { + this._activeAsyncOperations.delete(path); + runCallbacks(callbacks, err, result); + }, + ); + } : null; this.provideSync = this._syncProvider - ? (path, options) => { - return this._syncProvider.call(this._providerContext, path, options); - } + ? // Comment to align jsdoc + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {object=} options options + * @returns {EXPECTED_ANY} result + */ + (path, options) => + /** @type {EXPECTED_FUNCTION} */ (this._syncProvider).call( + this._providerContext, + path, + options, + ) : null; } purge() {} + purgeParent() {} } @@ -13560,26 +14253,38 @@ const STORAGE_MODE_IDLE = 0; const STORAGE_MODE_SYNC = 1; const STORAGE_MODE_ASYNC = 2; +/** + * @callback Provide + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @param {FileSystemCallback} callback callback + * @returns {void} + */ + class CacheBackend { /** * @param {number} duration max cache duration of items - * @param {any} provider async method - * @param {any} syncProvider sync method - * @param {any} providerContext call context for the provider methods + * @param {EXPECTED_FUNCTION | undefined} provider async method + * @param {EXPECTED_FUNCTION | undefined} syncProvider sync method + * @param {BaseFileSystem} providerContext call context for the provider methods */ constructor(duration, provider, syncProvider, providerContext) { this._duration = duration; this._provider = provider; this._syncProvider = syncProvider; this._providerContext = providerContext; - /** @type {Map} */ + /** @type {Map[]>} */ this._activeAsyncOperations = new Map(); - /** @type {Map }>} */ + /** @type {Map }>} */ this._data = new Map(); /** @type {Set[]} */ this._levels = []; for (let i = 0; i < 10; i++) this._levels.push(new Set()); - for (let i = 5000; i < duration; i += 500) this._levels.push(new Set()); + if (duration !== Infinity) { + for (let i = 5000; i < duration; i += 500) { + this._levels.push(new Set()); + } + } this._currentLevel = 0; this._tickInterval = Math.floor(duration / this._levels.length); /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ @@ -13590,25 +14295,41 @@ class CacheBackend { /** @type {number | undefined} */ this._nextDecay = undefined; + // eslint-disable-next-line no-warning-comments + // @ts-ignore this.provide = provider ? this.provide.bind(this) : null; + // eslint-disable-next-line no-warning-comments + // @ts-ignore this.provideSync = syncProvider ? this.provideSync.bind(this) : null; } + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @param {FileSystemCallback} callback callback + * @returns {void} + */ provide(path, options, callback) { if (typeof options === "function") { callback = options; options = undefined; } - if (typeof path !== "string") { - callback(new TypeError("path must be a string")); + if ( + typeof path !== "string" && + !Buffer.isBuffer(path) && + !(path instanceof URL) && + typeof path !== "number" + ) { + callback(new TypeError("path must be a string, Buffer, URL or number")); return; } + const strPath = typeof path !== "string" ? path.toString() : path; if (options) { - return this._provider.call( + return /** @type {EXPECTED_FUNCTION} */ (this._provider).call( this._providerContext, path, options, - callback + callback, ); } @@ -13618,38 +14339,68 @@ class CacheBackend { } // Check in cache - let cacheEntry = this._data.get(path); + const cacheEntry = this._data.get(strPath); if (cacheEntry !== undefined) { - if (cacheEntry.err) return nextTick(callback, cacheEntry.err); - return nextTick(callback, null, cacheEntry.result); + if (cacheEntry.err) { + return scheduleDispatch(callback, cacheEntry.err, undefined); + } + return scheduleDispatch(callback, null, cacheEntry.result); } // Check if there is already the same operation running - let callbacks = this._activeAsyncOperations.get(path); + let callbacks = this._activeAsyncOperations.get(strPath); if (callbacks !== undefined) { callbacks.push(callback); return; } - this._activeAsyncOperations.set(path, (callbacks = [callback])); + this._activeAsyncOperations.set(strPath, (callbacks = [callback])); // Run the operation - this._provider.call(this._providerContext, path, (err, result) => { - this._activeAsyncOperations.delete(path); - this._storeResult(path, err, result); + /** @type {EXPECTED_FUNCTION} */ + (this._provider).call( + this._providerContext, + path, + /** + * @param {Error | null} err error + * @param {EXPECTED_ANY=} result result + */ + (err, result) => { + this._activeAsyncOperations.delete(strPath); + this._storeResult(strPath, err, result); - // Enter async mode if not yet done - this._enterAsyncMode(); + // Enter async mode if not yet done + this._enterAsyncMode(); - runCallbacks(callbacks, err, result); - }); + runCallbacks( + /** @type {FileSystemCallback[]} */ (callbacks), + err, + result, + ); + }, + ); } + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @returns {EXPECTED_ANY} result + */ provideSync(path, options) { - if (typeof path !== "string") { + if ( + typeof path !== "string" && + !Buffer.isBuffer(path) && + !(path instanceof URL) && + typeof path !== "number" + ) { throw new TypeError("path must be a string"); } + const strPath = typeof path !== "string" ? path.toString() : path; if (options) { - return this._syncProvider.call(this._providerContext, path, options); + return /** @type {EXPECTED_FUNCTION} */ (this._syncProvider).call( + this._providerContext, + path, + options, + ); } // In sync mode we may have to decay some cache items @@ -13658,7 +14409,7 @@ class CacheBackend { } // Check in cache - let cacheEntry = this._data.get(path); + const cacheEntry = this._data.get(strPath); if (cacheEntry !== undefined) { if (cacheEntry.err) throw cacheEntry.err; return cacheEntry.result; @@ -13666,28 +14417,39 @@ class CacheBackend { // Get all active async operations // This sync operation will also complete them - const callbacks = this._activeAsyncOperations.get(path); - this._activeAsyncOperations.delete(path); + const callbacks = this._activeAsyncOperations.get(strPath); + this._activeAsyncOperations.delete(strPath); // Run the operation // When in idle mode, we will enter sync mode let result; try { - result = this._syncProvider.call(this._providerContext, path); + result = /** @type {EXPECTED_FUNCTION} */ (this._syncProvider).call( + this._providerContext, + path, + ); } catch (err) { - this._storeResult(path, err, undefined); + this._storeResult(strPath, /** @type {Error} */ (err), undefined); this._enterSyncModeWhenIdle(); - if (callbacks) runCallbacks(callbacks, err, undefined); + if (callbacks) { + runCallbacks(callbacks, /** @type {Error} */ (err), undefined); + } throw err; } - this._storeResult(path, undefined, result); + this._storeResult(strPath, null, result); this._enterSyncModeWhenIdle(); - if (callbacks) runCallbacks(callbacks, undefined, result); + if (callbacks) { + runCallbacks(callbacks, null, result); + } return result; } - purge(what) { - if (!what) { + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + * @param {{ exact?: boolean }=} options options; `exact: true` removes only entries whose key matches `what` exactly instead of any entry whose key starts with `what` + */ + purge(what, options) { + if (what === undefined || what === null) { if (this._mode !== STORAGE_MODE_IDLE) { this._data.clear(); for (const level of this._levels) { @@ -13695,9 +14457,58 @@ class CacheBackend { } this._enterIdleMode(); } - } else if (typeof what === "string") { - for (let [key, data] of this._data) { - if (key.startsWith(what)) { + return; + } + const exact = + options !== undefined && options !== null && options.exact === true; + if (exact) { + if ( + typeof what === "string" || + Buffer.isBuffer(what) || + what instanceof URL || + typeof what === "number" + ) { + const strWhat = typeof what !== "string" ? what.toString() : what; + const data = this._data.get(strWhat); + if (data !== undefined) { + this._data.delete(strWhat); + data.level.delete(strWhat); + } + } else { + for (const item of what) { + const strItem = typeof item !== "string" ? item.toString() : item; + const data = this._data.get(strItem); + if (data !== undefined) { + this._data.delete(strItem); + data.level.delete(strItem); + } + } + } + if (this._data.size === 0) { + this._enterIdleMode(); + } + return; + } + if ( + typeof what === "string" || + Buffer.isBuffer(what) || + what instanceof URL || + typeof what === "number" + ) { + const strWhat = typeof what !== "string" ? what.toString() : what; + if (strWhat === "") { + // empty string is a prefix of every key — short-circuit the O(n) scan + if (this._mode !== STORAGE_MODE_IDLE) { + this._data.clear(); + for (const level of this._levels) { + level.clear(); + } + this._enterIdleMode(); + } + return; + } + for (const [key, data] of this._data) { + if (key.startsWith(strWhat)) { this._data.delete(key); data.level.delete(key); } @@ -13706,9 +14517,10 @@ class CacheBackend { this._enterIdleMode(); } } else { - for (let [key, data] of this._data) { + for (const [key, data] of this._data) { for (const item of what) { - if (key.startsWith(item)) { + const strItem = typeof item !== "string" ? item.toString() : item; + if (key.startsWith(strItem)) { this._data.delete(key); data.level.delete(key); break; @@ -13721,20 +14533,35 @@ class CacheBackend { } } + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + */ purgeParent(what) { - if (!what) { + if (what === undefined || what === null) { this.purge(); - } else if (typeof what === "string") { - this.purge(dirname(what)); + } else if ( + typeof what === "string" || + Buffer.isBuffer(what) || + what instanceof URL || + typeof what === "number" + ) { + const strWhat = typeof what !== "string" ? what.toString() : what; + this.purge(dirname(strWhat)); } else { const set = new Set(); for (const item of what) { - set.add(dirname(item)); + const strItem = typeof item !== "string" ? item.toString() : item; + set.add(dirname(strItem)); } this.purge(set); } } + /** + * @param {string} path path + * @param {Error | null} err error + * @param {EXPECTED_ANY} result result + */ _storeResult(path, err, result) { if (this._data.has(path)) return; const level = this._levels[this._currentLevel]; @@ -13746,15 +14573,15 @@ class CacheBackend { const nextLevel = (this._currentLevel + 1) % this._levels.length; const decay = this._levels[nextLevel]; this._currentLevel = nextLevel; - for (let item of decay) { + for (const item of decay) { this._data.delete(item); } decay.clear(); if (this._data.size === 0) { this._enterIdleMode(); } else { - // @ts-ignore _nextDecay is always a number in sync mode - this._nextDecay += this._tickInterval; + /** @type {number} */ + (this._nextDecay) += this._tickInterval; } } @@ -13778,15 +14605,25 @@ class CacheBackend { break; case STORAGE_MODE_SYNC: this._runDecays(); - // @ts-ignore _runDecays may change the mode - if (this._mode === STORAGE_MODE_IDLE) return; + // _runDecays may change the mode + if ( + /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ + (this._mode) === STORAGE_MODE_IDLE + ) { + return; + } timeout = Math.max( 0, - /** @type {number} */ (this._nextDecay) - Date.now() + /** @type {number} */ (this._nextDecay) - Date.now(), ); break; } this._mode = STORAGE_MODE_ASYNC; + // When duration is Infinity, cache entries never expire, so there + // is no need to schedule a decay timer. + if (this._duration === Infinity) { + return; + } const ref = setTimeout(() => { this._mode = STORAGE_MODE_SYNC; this._runDecays(); @@ -13809,6 +14646,16 @@ class CacheBackend { } } +/** + * @template {EXPECTED_FUNCTION} Provider + * @template {EXPECTED_FUNCTION} AsyncProvider + * @template FileSystem + * @param {number} duration duration in ms files are cached + * @param {Provider | undefined} provider provider + * @param {AsyncProvider | undefined} syncProvider sync provider + * @param {BaseFileSystem} providerContext provider context + * @returns {OperationMergerBackend | CacheBackend} backend + */ const createBackend = (duration, provider, syncProvider, providerContext) => { if (duration > 0) { return new CacheBackend(duration, provider, syncProvider, providerContext); @@ -13817,6 +14664,10 @@ const createBackend = (duration, provider, syncProvider, providerContext) => { }; module.exports = class CachedInputFileSystem { + /** + * @param {BaseFileSystem} fileSystem file system + * @param {number} duration duration in ms files are cached + */ constructor(fileSystem, duration) { this.fileSystem = fileSystem; @@ -13824,7 +14675,7 @@ module.exports = class CachedInputFileSystem { duration, this.fileSystem.lstat, this.fileSystem.lstatSync, - this.fileSystem + this.fileSystem, ); const lstat = this._lstatBackend.provide; this.lstat = /** @type {FileSystem["lstat"]} */ (lstat); @@ -13835,7 +14686,7 @@ module.exports = class CachedInputFileSystem { duration, this.fileSystem.stat, this.fileSystem.statSync, - this.fileSystem + this.fileSystem, ); const stat = this._statBackend.provide; this.stat = /** @type {FileSystem["stat"]} */ (stat); @@ -13846,84 +14697,127 @@ module.exports = class CachedInputFileSystem { duration, this.fileSystem.readdir, this.fileSystem.readdirSync, - this.fileSystem + this.fileSystem, ); const readdir = this._readdirBackend.provide; this.readdir = /** @type {FileSystem["readdir"]} */ (readdir); const readdirSync = this._readdirBackend.provideSync; - this.readdirSync = /** @type {SyncFileSystem["readdirSync"]} */ (readdirSync); + this.readdirSync = /** @type {SyncFileSystem["readdirSync"]} */ ( + readdirSync + ); this._readFileBackend = createBackend( duration, this.fileSystem.readFile, this.fileSystem.readFileSync, - this.fileSystem + this.fileSystem, ); const readFile = this._readFileBackend.provide; this.readFile = /** @type {FileSystem["readFile"]} */ (readFile); const readFileSync = this._readFileBackend.provideSync; - this.readFileSync = /** @type {SyncFileSystem["readFileSync"]} */ (readFileSync); + this.readFileSync = /** @type {SyncFileSystem["readFileSync"]} */ ( + readFileSync + ); this._readJsonBackend = createBackend( duration, + // prettier-ignore this.fileSystem.readJson || (this.readFile && - ((path, callback) => { - // @ts-ignore - this.readFile(path, (err, buffer) => { - if (err) return callback(err); - if (!buffer || buffer.length === 0) - return callback(new Error("No file content")); - let data; - try { - data = JSON.parse(buffer.toString("utf-8")); - } catch (e) { - return callback(e); - } - callback(null, data); - }); - })), + ( + /** + * @param {string} path path + * @param {FileSystemCallback} callback callback + */ + (path, callback) => { + this.readFile(path, (err, buffer) => { + if (err) return callback(err); + if (!buffer || buffer.length === 0) + {return callback(new Error("No file content"));} + let data; + try { + data = JSON.parse(buffer.toString("utf8")); + } catch (err_) { + return callback(/** @type {Error} */ (err_)); + } + callback(null, data); + }); + }) + ), + // prettier-ignore this.fileSystem.readJsonSync || (this.readFileSync && - (path => { - const buffer = this.readFileSync(path); - const data = JSON.parse(buffer.toString("utf-8")); - return data; - })), - this.fileSystem + ( + /** + * @param {string} path path + * @returns {EXPECTED_ANY} result + */ + (path) => { + const buffer = this.readFileSync(path); + const data = JSON.parse(buffer.toString("utf8")); + return data; + } + )), + this.fileSystem, ); const readJson = this._readJsonBackend.provide; this.readJson = /** @type {FileSystem["readJson"]} */ (readJson); const readJsonSync = this._readJsonBackend.provideSync; - this.readJsonSync = /** @type {SyncFileSystem["readJsonSync"]} */ (readJsonSync); + this.readJsonSync = /** @type {SyncFileSystem["readJsonSync"]} */ ( + readJsonSync + ); this._readlinkBackend = createBackend( duration, this.fileSystem.readlink, this.fileSystem.readlinkSync, - this.fileSystem + this.fileSystem, ); const readlink = this._readlinkBackend.provide; this.readlink = /** @type {FileSystem["readlink"]} */ (readlink); const readlinkSync = this._readlinkBackend.provideSync; - this.readlinkSync = /** @type {SyncFileSystem["readlinkSync"]} */ (readlinkSync); + this.readlinkSync = /** @type {SyncFileSystem["readlinkSync"]} */ ( + readlinkSync + ); + + this._realpathBackend = createBackend( + duration, + this.fileSystem.realpath, + this.fileSystem.realpathSync, + this.fileSystem, + ); + const realpath = this._realpathBackend.provide; + this.realpath = /** @type {FileSystem["realpath"]} */ (realpath); + const realpathSync = this._realpathBackend.provideSync; + this.realpathSync = /** @type {SyncFileSystem["realpathSync"]} */ ( + realpathSync + ); } - purge(what) { - this._statBackend.purge(what); - this._lstatBackend.purge(what); - this._readdirBackend.purgeParent(what); - this._readFileBackend.purge(what); - this._readlinkBackend.purge(what); - this._readJsonBackend.purge(what); + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + * @param {{ exact?: boolean }=} options options; `exact: true` removes only cache entries whose key matches `what` exactly instead of any entry whose key starts with `what` + */ + purge(what, options) { + this._statBackend.purge(what, options); + this._lstatBackend.purge(what, options); + if (options !== undefined && options !== null && options.exact === true) { + this._readdirBackend.purge(what, options); + } else { + this._readdirBackend.purgeParent(what); + } + this._readFileBackend.purge(what, options); + this._readlinkBackend.purge(what, options); + this._readJsonBackend.purge(what, options); + this._realpathBackend.purge(what, options); } }; /***/ }), -/***/ 4086: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 36041: +/***/ ((module) => { "use strict"; /* @@ -13933,11 +14827,15 @@ module.exports = class CachedInputFileSystem { -const basename = (__nccwpck_require__(4880).basename); - /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ module.exports = class CloneBasenamePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ constructor(source, target) { this.source = source; this.target = target; @@ -13952,21 +14850,23 @@ module.exports = class CloneBasenamePlugin { resolver .getHook(this.source) .tapAsync("CloneBasenamePlugin", (request, resolveContext, callback) => { - const filename = basename(request.path); - const filePath = resolver.join(request.path, filename); + const requestPath = /** @type {string} */ (request.path); + const filename = resolver.basename(requestPath); + const filePath = resolver.join(requestPath, filename); + /** @type {ResolveRequest} */ const obj = { ...request, path: filePath, relativePath: request.relativePath && - resolver.join(request.relativePath, filename) + resolver.join(request.relativePath, filename), }; resolver.doResolve( target, obj, - "using path: " + filePath, + `using path: ${filePath}`, resolveContext, - callback + callback, ); }); } @@ -13975,7 +14875,7 @@ module.exports = class CloneBasenamePlugin { /***/ }), -/***/ 5315: +/***/ 55607: /***/ ((module) => { "use strict"; @@ -14013,7 +14913,7 @@ module.exports = class ConditionalPlugin { apply(resolver) { const target = resolver.ensureHook(this.target); const { test, message, allowAlternatives } = this; - const keys = Object.keys(test); + const keys = /** @type {(keyof ResolveRequest)[]} */ (Object.keys(test)); resolver .getHook(this.source) .tapAsync("ConditionalPlugin", (request, resolveContext, callback) => { @@ -14033,7 +14933,7 @@ module.exports = class ConditionalPlugin { // Don't allow other alternatives if (result === undefined) return callback(null, null); callback(null, result); - } + }, ); }); } @@ -14042,7 +14942,7 @@ module.exports = class ConditionalPlugin { /***/ }), -/***/ 7644: +/***/ 87644: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -14053,11 +14953,14 @@ module.exports = class ConditionalPlugin { -const DescriptionFileUtils = __nccwpck_require__(5387); +const DescriptionFileUtils = __nccwpck_require__(15387); /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +const BACKSLASH_G = /\\/g; + module.exports = class DescriptionFilePlugin { /** * @param {string | ResolveStepHook} source source @@ -14083,7 +14986,7 @@ module.exports = class DescriptionFilePlugin { .tapAsync( "DescriptionFilePlugin", (request, resolveContext, callback) => { - const path = request.path; + const { path } = request; if (!path) return callback(); const directory = this.pathIsFile ? DescriptionFileUtils.cdUp(path) @@ -14097,36 +15000,40 @@ module.exports = class DescriptionFilePlugin { ? { path: request.descriptionFilePath, content: request.descriptionFileData, - directory: /** @type {string} */ (request.descriptionFileRoot) - } + directory: + /** @type {string} */ + (request.descriptionFileRoot), + } : undefined, resolveContext, (err, result) => { if (err) return callback(err); if (!result) { - if (resolveContext.log) + if (resolveContext.log) { resolveContext.log( - `No description file found in ${directory} or above` + `No description file found in ${directory} or above`, ); + } return callback(); } - const relativePath = - "." + path.substr(result.directory.length).replace(/\\/g, "/"); + const rawRelative = path.slice(result.directory.length); + const relativePath = `.${ + rawRelative.includes("\\") + ? rawRelative.replace(BACKSLASH_G, "/") + : rawRelative + }`; + /** @type {ResolveRequest} */ const obj = { ...request, descriptionFilePath: result.path, descriptionFileData: result.content, descriptionFileRoot: result.directory, - relativePath: relativePath + relativePath, }; resolver.doResolve( target, obj, - "using description file: " + - result.path + - " (relative path: " + - relativePath + - ")", + `using description file: ${result.path} (relative path: ${relativePath})`, resolveContext, (err, result) => { if (err) return callback(err); @@ -14134,11 +15041,11 @@ module.exports = class DescriptionFilePlugin { // Don't allow other processing if (result === undefined) return callback(null, null); callback(null, result); - } + }, ); - } + }, ); - } + }, ); } }; @@ -14146,8 +15053,8 @@ module.exports = class DescriptionFilePlugin { /***/ }), -/***/ 5387: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 15387: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* @@ -14157,29 +15064,74 @@ module.exports = class DescriptionFilePlugin { -const forEachBail = __nccwpck_require__(4833); +const forEachBail = __nccwpck_require__(34833); +const { decodeText } = __nccwpck_require__(55524); /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").JsonValue} JsonValue */ /** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** - * @typedef {Object} DescriptionFileInfo - * @property {any=} content - * @property {string} path - * @property {string} directory + * @typedef {object} DescriptionFileInfo + * @property {JsonObject=} content content + * @property {string} path path + * @property {string} directory directory */ /** * @callback ErrorFirstCallback - * @param {Error|null=} error + * @param {Error | null=} error * @param {DescriptionFileInfo=} result */ +/** + * @typedef {object} Result + * @property {string} path path to description file + * @property {string} directory directory of description file + * @property {JsonObject} content content of description file + */ + +const CHAR_SLASH = 47; +const CHAR_BACKSLASH = 92; + +/** + * Walk up one directory. Called once per package-root candidate and once per + * `described-resolve` (to find the enclosing description file), so it's on + * the resolver's hot path. + * + * Previous implementation called `lastIndexOf("/")` and `lastIndexOf("\\")` + * separately and then picked the larger. For any non-trivial directory + * string on POSIX, `lastIndexOf("\\")` scans the full string just to return + * -1. A single reverse char-code scan does the same work in one pass. + * + * Any single-character directory is treated as a root — `directory.length + * <= 1` collapses the `"/"`, `"\\"` and `""` branches into one compare. + * Without the `"\\"` case, `cdUp("\\")` (reached from a UNC root or a DOS + * device path like `\\?\…`) would return itself via `slice(0, i || 1)` + * and trap `loadDescriptionFile` in an infinite loop. Once single-char + * roots are filtered up front, the reverse scan always produces a + * strictly shorter string. + * @param {string} directory directory + * @returns {string | null} parent directory or null + */ +function cdUp(directory) { + if (directory.length <= 1) return null; + for (let i = directory.length - 1; i >= 0; i--) { + const code = directory.charCodeAt(i); + if (code === CHAR_SLASH || code === CHAR_BACKSLASH) { + return directory.slice(0, i || 1); + } + } + return null; +} + /** * @param {Resolver} resolver resolver * @param {string} directory directory * @param {string[]} filenames filenames - * @param {DescriptionFileInfo|undefined} oldInfo oldInfo + * @param {DescriptionFileInfo | undefined} oldInfo oldInfo * @param {ResolveContext} resolveContext resolveContext * @param {ErrorFirstCallback} callback callback */ @@ -14189,142 +15141,159 @@ function loadDescriptionFile( filenames, oldInfo, resolveContext, - callback + callback, ) { - (function findDescriptionFile() { - if (oldInfo && oldInfo.directory === directory) { - // We already have info for this directory and can reuse it - return callback(null, oldInfo); - } - forEachBail( - filenames, - (filename, callback) => { - const descriptionFilePath = resolver.join(directory, filename); - if (resolver.fileSystem.readJson) { - resolver.fileSystem.readJson(descriptionFilePath, (err, content) => { - if (err) { - if (typeof err.code !== "undefined") { - if (resolveContext.missingDependencies) { - resolveContext.missingDependencies.add(descriptionFilePath); - } - return callback(); - } - if (resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(descriptionFilePath); - } - return onJson(err); - } - if (resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(descriptionFilePath); - } - onJson(null, content); - }); + // Hoist the per-filename iterator and the per-level done callback out + // of `findDescriptionFile`. They both close over `directory`, which we + // reassign as we walk up the tree, so the same closures keep working + // across every level — the previous implementation re-allocated both + // arrows on every recursion step, which adds up on deep walks (multiple + // `DescriptionFilePlugin` taps per resolve, each climbing several + // directories looking for `package.json`). + /** + * @param {string} filename filename + * @param {(err?: null | Error, result?: null | Result) => void} iterCallback callback + * @returns {void} + */ + const iterFilename = (filename, iterCallback) => { + const descriptionFilePath = resolver.join(directory, filename); + + /** + * @param {(null | Error)=} err error + * @param {JsonObject=} resolvedContent content + * @returns {void} + */ + function onJson(err, resolvedContent) { + if (err) { + if (resolveContext.log) { + resolveContext.log( + `${descriptionFilePath} (directory description file): ${err}`, + ); } else { - resolver.fileSystem.readFile(descriptionFilePath, (err, content) => { - if (err) { - if (resolveContext.missingDependencies) { - resolveContext.missingDependencies.add(descriptionFilePath); - } - return callback(); - } - if (resolveContext.fileDependencies) { - resolveContext.fileDependencies.add(descriptionFilePath); - } - let json; + err.message = `${descriptionFilePath} (directory description file): ${err}`; + } + return iterCallback(err); + } + iterCallback(null, { + content: /** @type {JsonObject} */ (resolvedContent), + directory, + path: descriptionFilePath, + }); + } - if (content) { - try { - json = JSON.parse(content.toString()); - } catch (e) { - return onJson(e); - } - } else { - return onJson(new Error("No content in file")); + if (resolver.fileSystem.readJson) { + resolver.fileSystem.readJson(descriptionFilePath, (err, content) => { + if (err) { + if ( + typeof (/** @type {NodeJS.ErrnoException} */ (err).code) !== + "undefined" + ) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); } - - onJson(null, json); - }); + return iterCallback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + return onJson(err); } - - function onJson(err, content) { - if (err) { - if (resolveContext.log) - resolveContext.log( - descriptionFilePath + " (directory description file): " + err - ); - else - err.message = - descriptionFilePath + " (directory description file): " + err; - return callback(err); + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + onJson(null, content); + }); + } else { + resolver.fileSystem.readFile(descriptionFilePath, (err, content) => { + if (err) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); } - callback(null, { - content, - directory, - path: descriptionFilePath - }); + return iterCallback(); } - }, - (err, result) => { - if (err) return callback(err); - if (result) { - return callback(null, result); - } else { - const dir = cdUp(directory); - if (!dir) { - return callback(); - } else { - directory = dir; - return findDescriptionFile(); + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + + /** @type {JsonObject | undefined} */ + let json; + + if (content) { + try { + json = JSON.parse(decodeText(content)); + } catch (/** @type {unknown} */ err_) { + return onJson(/** @type {Error} */ (err_)); } + } else { + return onJson(new Error("No content in file")); } - } - ); - })(); + + onJson(null, json); + }); + } + }; + // Forward-declared so the helpers below can reference each other + // without falling foul of `no-use-before-define`. + /** @type {() => void} */ + let findDescriptionFile; + /** + * @param {(null | Error)=} err error + * @param {(null | Result)=} result result + * @returns {void} + */ + const onLevelDone = (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + const dir = cdUp(directory); + if (!dir) { + return callback(); + } + directory = dir; + return findDescriptionFile(); + }; + findDescriptionFile = () => { + if (oldInfo && oldInfo.directory === directory) { + // We already have info for this directory and can reuse it + return callback(null, oldInfo); + } + forEachBail(filenames, iterFilename, onLevelDone); + }; + findDescriptionFile(); } /** - * @param {any} content content - * @param {string|string[]} field field - * @returns {object|string|number|boolean|undefined} field data + * @param {JsonObject} content content + * @param {string | string[]} field field + * @returns {JsonValue | undefined} field data */ function getField(content, field) { if (!content) return undefined; if (Array.isArray(field)) { + /** @type {JsonValue} */ let current = content; for (let j = 0; j < field.length; j++) { if (current === null || typeof current !== "object") { current = null; break; } - current = current[field[j]]; + current = /** @type {JsonValue} */ ( + /** @type {JsonObject} */ + (current)[field[j]] + ); } return current; - } else { - return content[field]; } + return content[field]; } -/** - * @param {string} directory directory - * @returns {string|null} parent directory or null - */ -function cdUp(directory) { - if (directory === "/") return null; - const i = directory.lastIndexOf("/"), - j = directory.lastIndexOf("\\"); - const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; - if (p < 0) return null; - return directory.substr(0, p || 1); -} - -exports.loadDescriptionFile = loadDescriptionFile; -exports.getField = getField; -exports.cdUp = cdUp; +module.exports.cdUp = cdUp; +module.exports.getField = getField; +module.exports.loadDescriptionFile = loadDescriptionFile; /***/ }), -/***/ 674: +/***/ 80674: /***/ ((module) => { "use strict"; @@ -14363,31 +15332,36 @@ module.exports = class DirectoryExistsPlugin { const directory = request.path; if (!directory) return callback(); fs.stat(directory, (err, stat) => { - if (err || !stat) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(directory); - if (resolveContext.log) - resolveContext.log(directory + " doesn't exist"); - return callback(); - } - if (!stat.isDirectory()) { - if (resolveContext.missingDependencies) + // Combine the two miss branches: a stat failure and a + // "not a directory" result share the same handling — record + // the path on `missingDependencies`, log the right reason, + // then bail. The error-message ternary picks the wording + // that matched the failing condition. + if (err || !stat || !stat.isDirectory()) { + if (resolveContext.missingDependencies) { resolveContext.missingDependencies.add(directory); - if (resolveContext.log) - resolveContext.log(directory + " is not a directory"); + } + if (resolveContext.log) { + resolveContext.log( + err || !stat + ? `${directory} doesn't exist` + : `${directory} is not a directory`, + ); + } return callback(); } - if (resolveContext.fileDependencies) + if (resolveContext.fileDependencies) { resolveContext.fileDependencies.add(directory); + } resolver.doResolve( target, request, `existing directory ${directory}`, resolveContext, - callback + callback, ); }); - } + }, ); } }; @@ -14395,7 +15369,7 @@ module.exports = class DirectoryExistsPlugin { /***/ }), -/***/ 1866: +/***/ 81866: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -14406,14 +15380,18 @@ module.exports = class DirectoryExistsPlugin { -const path = __nccwpck_require__(1017); -const DescriptionFileUtils = __nccwpck_require__(5387); -const forEachBail = __nccwpck_require__(4833); -const { processExportsField } = __nccwpck_require__(3679); -const { parseIdentifier } = __nccwpck_require__(2505); -const { checkImportsExportsFieldTarget } = __nccwpck_require__(4030); +const DescriptionFileUtils = __nccwpck_require__(15387); +const forEachBail = __nccwpck_require__(34833); +const { processExportsField } = __nccwpck_require__(63679); +const { parseIdentifier } = __nccwpck_require__(42505); +const { + deprecatedInvalidSegmentRegEx, + invalidSegmentRegEx, +} = __nccwpck_require__(64030); /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ /** @typedef {import("./util/entrypoints").ExportsField} ExportsField */ /** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ @@ -14424,14 +15402,19 @@ module.exports = class ExportsFieldPlugin { * @param {Set} conditionNames condition names * @param {string | string[]} fieldNamePath name path * @param {string | ResolveStepHook} target target + * @param {boolean=} restrictions whether `restrictions` are configured (enables exports-target fallback when a target is filtered out) */ - constructor(source, conditionNames, fieldNamePath, target) { + constructor(source, conditionNames, fieldNamePath, target, restrictions) { this.source = source; this.target = target; this.conditionNames = conditionNames; this.fieldName = fieldNamePath; - /** @type {WeakMap} */ - this.fieldProcessorCache = new WeakMap(); + this.restrictions = Boolean(restrictions); + // `null` is cached for description files that have no exports field, + // so subsequent resolves against the same package.json skip the + // `DescriptionFileUtils.getField` walk entirely. + /** @type {WeakMap} */ + this._fieldProcessorCache = new WeakMap(); } /** @@ -14444,106 +15427,202 @@ module.exports = class ExportsFieldPlugin { .getHook(this.source) .tapAsync("ExportsFieldPlugin", (request, resolveContext, callback) => { // When there is no description file, abort - if (!request.descriptionFilePath) return callback(); + if (!request.descriptionFileData) return callback(); if ( // When the description file is inherited from parent, abort // (There is no description file inside of this package) request.relativePath !== "." || request.request === undefined - ) + ) { return callback(); + } + const { descriptionFileData } = request; const remainingRequest = request.query || request.fragment ? (request.request === "." ? "./" : request.request) + - request.query + - request.fragment + request.query + + request.fragment : request.request; - /** @type {ExportsField|null} */ - const exportsField = DescriptionFileUtils.getField( - request.descriptionFileData, - this.fieldName - ); - if (!exportsField) return callback(); - - if (request.directory) { - return callback( - new Error( - `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)` - ) - ); - } + /** @type {string[]} */ let paths; + /** @type {string | null} */ + let usedField; try { - // We attach the cache to the description file instead of the exportsField value - // because we use a WeakMap and the exportsField could be a string too. - // Description file is always an object when exports field can be accessed. - let fieldProcessor = this.fieldProcessorCache.get( - request.descriptionFileData - ); - if (fieldProcessor === undefined) { - fieldProcessor = processExportsField(exportsField); - this.fieldProcessorCache.set( - request.descriptionFileData, - fieldProcessor + // Look up the cached processor first. On a cache hit we + // avoid re-walking the description file for the exports + // field — and `null` is cached for description files that + // have no exports field at all, so those skip the read + // entirely. `processExportsField` can throw on a malformed + // `exports` map (e.g. a key without a leading `.`), so + // building the processor must stay inside this try/catch. + let fieldProcessor = + this._fieldProcessorCache.get(descriptionFileData); + if ( + fieldProcessor === undefined && + !this._fieldProcessorCache.has(descriptionFileData) + ) { + const exportsField = + /** @type {ExportsField | null | undefined} */ + ( + DescriptionFileUtils.getField( + descriptionFileData, + this.fieldName, + ) + ); + fieldProcessor = exportsField + ? processExportsField(exportsField) + : null; + this._fieldProcessorCache.set(descriptionFileData, fieldProcessor); + } + if (!fieldProcessor) return callback(); + + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)`, + ), ); } - paths = fieldProcessor(remainingRequest, this.conditionNames); - } catch (err) { + + [paths, usedField] = fieldProcessor( + remainingRequest, + this.conditionNames, + ); + } catch (/** @type {unknown} */ err) { if (resolveContext.log) { resolveContext.log( - `Exports field in ${request.descriptionFilePath} can't be processed: ${err}` + `Exports field in ${request.descriptionFilePath} can't be processed: ${err}`, ); } - return callback(err); + return callback(/** @type {Error} */ (err)); } if (paths.length === 0) { + const conditions = [...this.conditionNames]; + const conditionsStr = + conditions.length === 1 + ? `the condition "${conditions[0]}"` + : `the conditions ${JSON.stringify(conditions)}`; return callback( new Error( - `Package path ${remainingRequest} is not exported from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})` - ) + `"${remainingRequest}" is not exported under ${conditionsStr} from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})`, + ), ); } + // When `restrictions` are configured, share a marker down the + // chain so RestrictionsPlugin can tell us it filtered out an + // otherwise-valid target — then we fall back instead of erroring. + const restrictionsMarker = this.restrictions + ? { blocked: false } + : undefined; + forEachBail( paths, - (p, callback) => { - const parsedIdentifier = parseIdentifier(p); + /** + * @param {string} path path + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @param {number} i index + * @returns {void} + */ + (path, callback, i) => { + const parsedIdentifier = parseIdentifier(path); if (!parsedIdentifier) return callback(); const [relativePath, query, fragment] = parsedIdentifier; - const error = checkImportsExportsFieldTarget(relativePath); + if (!relativePath.startsWith("./")) { + if (paths.length === i) { + return callback( + new Error( + `Invalid "exports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`, + ), + ); + } - if (error) { - return callback(error); + return callback(); + } + + const withoutDotSlash = relativePath.slice(2); + if ( + invalidSegmentRegEx.test(withoutDotSlash) && + deprecatedInvalidSegmentRegEx.test(withoutDotSlash) + ) { + if (paths.length === i) { + return callback( + new Error( + `Invalid "exports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`, + ), + ); + } + + return callback(); } + /** @type {ResolveRequest} */ const obj = { ...request, request: undefined, - path: path.join( + path: resolver.join( /** @type {string} */ (request.descriptionFileRoot), - relativePath + relativePath, ), relativePath, query, - fragment + fragment, }; + // Attach the marker only when restrictions are configured, so + // resolves without restrictions keep their request shape and + // never leak the property onto the result. + if (restrictionsMarker) { + obj.__restrictionsMarker = restrictionsMarker; + } resolver.doResolve( target, obj, - "using exports field: " + p, + `using exports field: ${path}`, resolveContext, - callback + (err, result) => { + if (err) return callback(err); + // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400 + if (result === undefined) return callback(null, null); + callback(null, result); + }, ); }, - (err, result) => callback(err, result || null) + /** + * @param {(null | Error)=} err error + * @param {(null | ResolveRequest)=} result result + * @returns {void} + */ + (err, result) => { + if (err) return callback(err); + // When an exports field match was found but the target file doesn't exist, + // return an error to prevent fallback to parent node_modules directories. + // Per the Node.js ESM spec, a matched exports entry that fails to resolve + // is a hard error, not a signal to continue searching up the directory tree. + // See: https://github.com/webpack/enhanced-resolve/issues/399 + if (!result) { + // Exception: the target existed but `restrictions` filtered it + // out — return no result so the next `modules` entry is tried. + if (restrictionsMarker && restrictionsMarker.blocked) { + return callback(null, null); + } + return callback( + new Error( + `Package path ${remainingRequest} is exported from package ${request.descriptionFileRoot}, but no valid target file was found (see exports field in ${request.descriptionFilePath})`, + ), + ); + } + // Drop the internal marker before it reaches the result. + if (restrictionsMarker) delete result.__restrictionsMarker; + callback(null, result); + }, ); }); } @@ -14552,7 +15631,7 @@ module.exports = class ExportsFieldPlugin { /***/ }), -/***/ 2894: +/***/ 82894: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -14563,12 +15642,12 @@ module.exports = class ExportsFieldPlugin { -const forEachBail = __nccwpck_require__(4833); +const forEachBail = __nccwpck_require__(34833); /** @typedef {import("./Resolver")} Resolver */ /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {{ alias: string|string[], extension: string }} ExtensionAliasOption */ +/** @typedef {{ alias: string | string[], extension: string }} ExtensionAliasOption */ module.exports = class ExtensionAliasPlugin { /** @@ -14592,29 +15671,90 @@ module.exports = class ExtensionAliasPlugin { resolver .getHook(this.source) .tapAsync("ExtensionAliasPlugin", (request, resolveContext, callback) => { - const requestPath = request.request; - if (!requestPath || !requestPath.endsWith(extension)) return callback(); - const resolve = (alias, callback) => { - resolver.doResolve( + // Two modes of operation: + // - "request" mode: original request specifier still carries the + // extension (e.g. user wrote `./foo.js`). We swap the extension + // on `request.request` and re-resolve. + // - "path" mode: the specifier has already been joined into an + // absolute `request.path` (e.g. produced by the imports field). + // We swap the extension on `request.path` and `request.relativePath`. + const useRequest = request.request !== undefined; + const source = useRequest + ? /** @type {string} */ (request.request) + : request.path; + if (!source || !source.endsWith(extension)) return callback(); + const isAliasString = typeof alias === "string"; + // Hoist the base (everything before the old extension) out of the + // per-alias `resolve` callback. For an array `alias`, the callback + // runs once per candidate extension; the base does not change + // between iterations, so there's no reason to recompute it. + const sourceBase = source.slice(0, -extension.length); + const relativePathBase = + !useRequest && + request.relativePath && + request.relativePath.endsWith(extension) + ? request.relativePath.slice(0, -extension.length) + : null; + /** + * @param {string} alias extension alias + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @param {number=} index index + * @returns {void} + */ + const resolve = (alias, callback, index) => { + const newValue = `${sourceBase}${alias}`; + const nextRequest = useRequest + ? { + ...request, + request: newValue, + fullySpecified: true, + } + : { + ...request, + path: newValue, + relativePath: + relativePathBase !== null + ? `${relativePathBase}${alias}` + : request.relativePath, + fullySpecified: true, + }; + + return resolver.doResolve( target, - { - ...request, - request: `${requestPath.slice(0, -extension.length)}${alias}`, - fullySpecified: true - }, + nextRequest, `aliased from extension alias with mapping '${extension}' to '${alias}'`, resolveContext, - callback + (err, result) => { + // Throw error if we are on the last alias (for multiple aliases) and it failed, always throw if we are not an array or we have only one alias + if (!isAliasString && index) { + if (index !== this.options.alias.length) { + if (resolveContext.log) { + resolveContext.log( + `Failed to alias from extension alias with mapping '${extension}' to '${alias}' for '${newValue}': ${err}`, + ); + } + + return callback(null, result); + } + + return callback(err, result); + } + callback(err, result); + }, ); }; - + /** + * @param {(null | Error)=} err error + * @param {(null | ResolveRequest)=} result result + * @returns {void} + */ const stoppingCallback = (err, result) => { if (err) return callback(err); if (result) return callback(null, result); // Don't allow other aliasing or raw request return callback(null, null); }; - if (typeof alias === "string") { + if (isAliasString) { resolve(alias, stoppingCallback); } else if (alias.length > 1) { forEachBail(alias, resolve, stoppingCallback); @@ -14665,26 +15805,33 @@ module.exports = class FileExistsPlugin { const file = request.path; if (!file) return callback(); fs.stat(file, (err, stat) => { - if (err || !stat) { - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(file); - if (resolveContext.log) resolveContext.log(file + " doesn't exist"); - return callback(); - } - if (!stat.isFile()) { - if (resolveContext.missingDependencies) + // Combine the two miss branches: a stat failure and a + // "not a file" result share the same handling — record the + // path on `missingDependencies`, log the right reason, then + // bail. The error-message ternary picks the wording that + // matched the failing condition. + if (err || !stat || !stat.isFile()) { + if (resolveContext.missingDependencies) { resolveContext.missingDependencies.add(file); - if (resolveContext.log) resolveContext.log(file + " is not a file"); + } + if (resolveContext.log) { + resolveContext.log( + err || !stat + ? `${file} doesn't exist` + : `${file} is not a file`, + ); + } return callback(); } - if (resolveContext.fileDependencies) + if (resolveContext.fileDependencies) { resolveContext.fileDependencies.add(file); + } resolver.doResolve( target, request, - "existing file: " + file, + `existing file: ${file}`, resolveContext, - callback + callback, ); }); }); @@ -14705,14 +15852,15 @@ module.exports = class FileExistsPlugin { -const path = __nccwpck_require__(1017); -const DescriptionFileUtils = __nccwpck_require__(5387); -const forEachBail = __nccwpck_require__(4833); -const { processImportsField } = __nccwpck_require__(3679); -const { parseIdentifier } = __nccwpck_require__(2505); -const { checkImportsExportsFieldTarget } = __nccwpck_require__(4030); +const DescriptionFileUtils = __nccwpck_require__(15387); +const forEachBail = __nccwpck_require__(34833); +const { processImportsField } = __nccwpck_require__(63679); +const { parseIdentifier } = __nccwpck_require__(42505); +const { invalidSegmentRegEx } = __nccwpck_require__(64030); /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ /** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ /** @typedef {import("./util/entrypoints").ImportsField} ImportsField */ @@ -14732,15 +15880,18 @@ module.exports = class ImportsFieldPlugin { conditionNames, fieldNamePath, targetFile, - targetPackage + targetPackage, ) { this.source = source; this.targetFile = targetFile; this.targetPackage = targetPackage; this.conditionNames = conditionNames; this.fieldName = fieldNamePath; - /** @type {WeakMap} */ - this.fieldProcessorCache = new WeakMap(); + // `null` is cached for description files that have no imports field, + // so subsequent resolves against the same package.json skip the + // `DescriptionFileUtils.getField` walk entirely. + /** @type {WeakMap} */ + this._fieldProcessorCache = new WeakMap(); } /** @@ -14755,123 +15906,174 @@ module.exports = class ImportsFieldPlugin { .getHook(this.source) .tapAsync("ImportsFieldPlugin", (request, resolveContext, callback) => { // When there is no description file, abort - if (!request.descriptionFilePath || request.request === undefined) { + if (!request.descriptionFileData || request.request === undefined) { return callback(); } + const { descriptionFileData } = request; + // Skip the concat when there's nothing to append — the common + // case has empty query/fragment, so this avoids an allocation + // per resolve. Mirrors the pattern in ExportsFieldPlugin. const remainingRequest = - request.request + request.query + request.fragment; - /** @type {ImportsField|null} */ - const importsField = DescriptionFileUtils.getField( - request.descriptionFileData, - this.fieldName - ); - if (!importsField) return callback(); - - if (request.directory) { - return callback( - new Error( - `Resolving to directories is not possible with the imports field (request was ${remainingRequest}/)` - ) - ); - } + request.query || request.fragment + ? request.request + request.query + request.fragment + : request.request; + /** @type {string[]} */ let paths; + /** @type {string | null} */ + let usedField; try { - // We attach the cache to the description file instead of the importsField value - // because we use a WeakMap and the importsField could be a string too. - // Description file is always an object when exports field can be accessed. - let fieldProcessor = this.fieldProcessorCache.get( - request.descriptionFileData - ); - if (fieldProcessor === undefined) { - fieldProcessor = processImportsField(importsField); - this.fieldProcessorCache.set( - request.descriptionFileData, - fieldProcessor + // Look up the cached processor first. On a cache hit we + // avoid re-walking the description file for the imports + // field — and `null` is cached for description files that + // have no imports field at all, so those skip the read + // entirely. `processImportsField` can throw on a + // malformed `imports` map, so building the processor must + // stay inside this try/catch. + let fieldProcessor = + this._fieldProcessorCache.get(descriptionFileData); + if ( + fieldProcessor === undefined && + !this._fieldProcessorCache.has(descriptionFileData) + ) { + const importsField = + /** @type {ImportsField | null | undefined} */ + ( + DescriptionFileUtils.getField( + descriptionFileData, + this.fieldName, + ) + ); + fieldProcessor = importsField + ? processImportsField(importsField) + : null; + this._fieldProcessorCache.set(descriptionFileData, fieldProcessor); + } + if (!fieldProcessor) return callback(); + + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the imports field (request was ${remainingRequest}/)`, + ), ); } - paths = fieldProcessor(remainingRequest, this.conditionNames); - } catch (err) { + + [paths, usedField] = fieldProcessor( + remainingRequest, + this.conditionNames, + ); + } catch (/** @type {unknown} */ err) { if (resolveContext.log) { resolveContext.log( - `Imports field in ${request.descriptionFilePath} can't be processed: ${err}` + `Imports field in ${request.descriptionFilePath} can't be processed: ${err}`, ); } - return callback(err); + return callback(/** @type {Error} */ (err)); } if (paths.length === 0) { return callback( new Error( - `Package import ${remainingRequest} is not imported from package ${request.descriptionFileRoot} (see imports field in ${request.descriptionFilePath})` - ) + `Package import ${remainingRequest} is not imported from package ${request.descriptionFileRoot} (see imports field in ${request.descriptionFilePath})`, + ), ); } forEachBail( paths, - (p, callback) => { - const parsedIdentifier = parseIdentifier(p); + /** + * @param {string} path path + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @param {number} i index + * @returns {void} + */ + (path, callback, i) => { + const parsedIdentifier = parseIdentifier(path); if (!parsedIdentifier) return callback(); const [path_, query, fragment] = parsedIdentifier; - const error = checkImportsExportsFieldTarget(path_); - - if (error) { - return callback(error); - } - switch (path_.charCodeAt(0)) { // should be relative case dotCode: { + const withoutDotSlash = path_.slice(2); + if (invalidSegmentRegEx.test(withoutDotSlash)) { + if (paths.length === i) { + return callback( + new Error( + `Invalid "imports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`, + ), + ); + } + + return callback(); + } + + /** @type {ResolveRequest} */ const obj = { ...request, request: undefined, - path: path.join( + path: resolver.join( /** @type {string} */ (request.descriptionFileRoot), - path_ + path_, ), relativePath: path_, query, - fragment + fragment, }; resolver.doResolve( targetFile, obj, - "using imports field: " + p, + `using imports field: ${path}`, resolveContext, - callback + (err, result) => { + if (err) return callback(err); + // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400 + if (result === undefined) return callback(null, null); + callback(null, result); + }, ); break; } // package resolving default: { + /** @type {ResolveRequest} */ const obj = { ...request, request: path_, relativePath: path_, fullySpecified: true, query, - fragment + fragment, }; resolver.doResolve( targetPackage, obj, - "using imports field: " + p, + `using imports field: ${path}`, resolveContext, - callback + (err, result) => { + if (err) return callback(err); + // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400 + if (result === undefined) return callback(null, null); + callback(null, result); + }, ); } } }, - (err, result) => callback(err, result || null) + /** + * @param {null | Error=} err error + * @param {null | ResolveRequest=} result result + * @returns {void} + */ + (err, result) => callback(err, result || null), ); }); } @@ -14880,7 +16082,7 @@ module.exports = class ImportsFieldPlugin { /***/ }), -/***/ 8095: +/***/ 58095: /***/ ((module) => { "use strict"; @@ -14892,6 +16094,7 @@ module.exports = class ImportsFieldPlugin { /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ const namespaceStartCharCode = "@".charCodeAt(0); @@ -14924,27 +16127,37 @@ module.exports = class JoinRequestPartPlugin { i = req.indexOf("/", i + 1); } - let moduleName, remainingRequest, fullySpecified; + /** @type {string} */ + let moduleName; + /** @type {string} */ + let remainingRequest; + /** @type {boolean} */ + let fullySpecified; if (i < 0) { moduleName = req; remainingRequest = "."; fullySpecified = false; } else { moduleName = req.slice(0, i); - remainingRequest = "." + req.slice(i); - fullySpecified = request.fullySpecified; + remainingRequest = `.${req.slice(i)}`; + fullySpecified = /** @type {boolean} */ (request.fullySpecified); } + /** @type {ResolveRequest} */ const obj = { ...request, - path: resolver.join(request.path, moduleName), + path: resolver.join( + /** @type {string} */ + (request.path), + moduleName, + ), relativePath: request.relativePath && resolver.join(request.relativePath, moduleName), request: remainingRequest, - fullySpecified + fullySpecified, }; resolver.doResolve(target, obj, null, resolveContext, callback); - } + }, ); } }; @@ -14952,7 +16165,7 @@ module.exports = class JoinRequestPartPlugin { /***/ }), -/***/ 2010: +/***/ 22010: /***/ ((module) => { "use strict"; @@ -14964,6 +16177,7 @@ module.exports = class JoinRequestPartPlugin { /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ module.exports = class JoinRequestPlugin { @@ -14985,13 +16199,16 @@ module.exports = class JoinRequestPlugin { resolver .getHook(this.source) .tapAsync("JoinRequestPlugin", (request, resolveContext, callback) => { + const requestPath = /** @type {string} */ (request.path); + const requestRequest = /** @type {string} */ (request.request); + /** @type {ResolveRequest} */ const obj = { ...request, - path: resolver.join(request.path, request.request), + path: resolver.join(requestPath, requestRequest), relativePath: request.relativePath && - resolver.join(request.relativePath, request.request), - request: undefined + resolver.join(request.relativePath, requestRequest), + request: undefined, }; resolver.doResolve(target, obj, null, resolveContext, callback); }); @@ -15001,7 +16218,7 @@ module.exports = class JoinRequestPlugin { /***/ }), -/***/ 1656: +/***/ 81656: /***/ ((module) => { "use strict"; @@ -15013,8 +16230,12 @@ module.exports = class JoinRequestPlugin { /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ module.exports = class LogInfoPlugin { + /** + * @param {string | ResolveStepHook} source source + */ constructor(source) { this.source = source; } @@ -15024,33 +16245,37 @@ module.exports = class LogInfoPlugin { * @returns {void} */ apply(resolver) { - const source = this.source; + const { source } = this; resolver .getHook(this.source) .tapAsync("LogInfoPlugin", (request, resolveContext, callback) => { if (!resolveContext.log) return callback(); - const log = resolveContext.log; - const prefix = "[" + source + "] "; - if (request.path) - log(prefix + "Resolving in directory: " + request.path); - if (request.request) - log(prefix + "Resolving request: " + request.request); - if (request.module) log(prefix + "Request is an module request."); - if (request.directory) log(prefix + "Request is a directory request."); - if (request.query) - log(prefix + "Resolving request query: " + request.query); - if (request.fragment) - log(prefix + "Resolving request fragment: " + request.fragment); - if (request.descriptionFilePath) + const { log } = resolveContext; + const prefix = `[${source}] `; + if (request.path) { + log(`${prefix}Resolving in directory: ${request.path}`); + } + if (request.request) { + log(`${prefix}Resolving request: ${request.request}`); + } + if (request.module) log(`${prefix}Request is an module request.`); + if (request.directory) log(`${prefix}Request is a directory request.`); + if (request.query) { + log(`${prefix}Resolving request query: ${request.query}`); + } + if (request.fragment) { + log(`${prefix}Resolving request fragment: ${request.fragment}`); + } + if (request.descriptionFilePath) { log( - prefix + "Has description data from " + request.descriptionFilePath + `${prefix}Has description data from ${request.descriptionFilePath}`, ); - if (request.relativePath) + } + if (request.relativePath) { log( - prefix + - "Relative path from description file is: " + - request.relativePath + `${prefix}Relative path from description file is: ${request.relativePath}`, ); + } callback(); }); } @@ -15059,7 +16284,7 @@ module.exports = class LogInfoPlugin { /***/ }), -/***/ 3438: +/***/ 83438: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -15070,15 +16295,22 @@ module.exports = class LogInfoPlugin { -const path = __nccwpck_require__(1017); -const DescriptionFileUtils = __nccwpck_require__(5387); +const DescriptionFileUtils = __nccwpck_require__(15387); /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {{name: string|Array, forceRelative: boolean}} MainFieldOptions */ + +/** @typedef {{ name: string | string[], forceRelative: boolean }} MainFieldOptions */ const alreadyTriedMainField = Symbol("alreadyTriedMainField"); +// Sentinel cached for description files where the main field resolves to a +// value we cannot use (missing, non-string, ".", "./"). Cheaper to store and +// check than to re-walk the description file on every resolve. +const NO_MAIN = Symbol("NoMain"); + module.exports = class MainFieldPlugin { /** * @param {string | ResolveStepHook} source source @@ -15089,6 +16321,12 @@ module.exports = class MainFieldPlugin { this.source = source; this.options = options; this.target = target; + // Cache the resolved `mainModule` per description-file content. The + // options (`name`, `forceRelative`) are fixed for this plugin + // instance, so caching against content alone is safe. Stores either + // the ready-to-use request string or the `NO_MAIN` sentinel. + /** @type {WeakMap} */ + this._mainModuleCache = new WeakMap(); } /** @@ -15102,44 +16340,47 @@ module.exports = class MainFieldPlugin { .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => { if ( request.path !== request.descriptionFileRoot || - request[alreadyTriedMainField] === request.descriptionFilePath || + /** @type {ResolveRequest & { [alreadyTriedMainField]?: string }} */ + (request)[alreadyTriedMainField] === request.descriptionFilePath || !request.descriptionFilePath - ) + ) { return callback(); - const filename = path.basename(request.descriptionFilePath); - let mainModule = DescriptionFileUtils.getField( - request.descriptionFileData, - this.options.name + } + const descFileData = /** @type {JsonObject} */ ( + request.descriptionFileData ); - - if ( - !mainModule || - typeof mainModule !== "string" || - mainModule === "." || - mainModule === "./" - ) { + let mainModule = this._mainModuleCache.get(descFileData); + if (mainModule === undefined) { + let raw = + /** @type {string | null | undefined} */ + (DescriptionFileUtils.getField(descFileData, this.options.name)); + if (!raw || typeof raw !== "string" || raw === "." || raw === "./") { + this._mainModuleCache.set(descFileData, NO_MAIN); + return callback(); + } + if (this.options.forceRelative && !/^\.\.?\//.test(raw)) { + raw = `./${raw}`; + } + mainModule = raw; + this._mainModuleCache.set(descFileData, mainModule); + } else if (mainModule === NO_MAIN) { return callback(); } - if (this.options.forceRelative && !/^\.\.?\//.test(mainModule)) - mainModule = "./" + mainModule; + const filename = resolver.basename(request.descriptionFilePath); + /** @type {ResolveRequest & { [alreadyTriedMainField]?: string }} */ const obj = { ...request, request: mainModule, module: false, directory: mainModule.endsWith("/"), - [alreadyTriedMainField]: request.descriptionFilePath + [alreadyTriedMainField]: request.descriptionFilePath, }; return resolver.doResolve( target, obj, - "use " + - mainModule + - " from " + - this.options.name + - " in " + - filename, + `use ${mainModule} from ${this.options.name} in ${filename}`, resolveContext, - callback + callback, ); }); } @@ -15148,7 +16389,7 @@ module.exports = class MainFieldPlugin { /***/ }), -/***/ 8409: +/***/ 78409: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -15159,8 +16400,7 @@ module.exports = class MainFieldPlugin { -const forEachBail = __nccwpck_require__(4833); -const getPaths = __nccwpck_require__(4880); +const { modulesResolveHandler } = __nccwpck_require__(70561); /** @typedef {import("./Resolver")} Resolver */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ @@ -15168,12 +16408,12 @@ const getPaths = __nccwpck_require__(4880); module.exports = class ModulesInHierarchicalDirectoriesPlugin { /** * @param {string | ResolveStepHook} source source - * @param {string | Array} directories directories + * @param {string | string[]} directories directories * @param {string | ResolveStepHook} target target */ constructor(source, directories, target) { this.source = source; - this.directories = /** @type {Array} */ ([]).concat(directories); + this.directories = /** @type {string[]} */ [...directories]; this.target = target; } @@ -15188,47 +16428,15 @@ module.exports = class ModulesInHierarchicalDirectoriesPlugin { .tapAsync( "ModulesInHierarchicalDirectoriesPlugin", (request, resolveContext, callback) => { - const fs = resolver.fileSystem; - const addrs = getPaths(request.path) - .paths.map(p => { - return this.directories.map(d => resolver.join(p, d)); - }) - .reduce((array, p) => { - array.push.apply(array, p); - return array; - }, []); - forEachBail( - addrs, - (addr, callback) => { - fs.stat(addr, (err, stat) => { - if (!err && stat && stat.isDirectory()) { - const obj = { - ...request, - path: addr, - request: "./" + request.request, - module: false - }; - const message = "looking for modules in " + addr; - return resolver.doResolve( - target, - obj, - message, - resolveContext, - callback - ); - } - if (resolveContext.log) - resolveContext.log( - addr + " doesn't exist or is not a directory" - ); - if (resolveContext.missingDependencies) - resolveContext.missingDependencies.add(addr); - return callback(); - }); - }, - callback + modulesResolveHandler( + resolver, + this.directories, + target, + request, + resolveContext, + callback, ); - } + }, ); } }; @@ -15236,7 +16444,7 @@ module.exports = class ModulesInHierarchicalDirectoriesPlugin { /***/ }), -/***/ 9650: +/***/ 59650: /***/ ((module) => { "use strict"; @@ -15248,6 +16456,7 @@ module.exports = class ModulesInHierarchicalDirectoriesPlugin { /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ module.exports = class ModulesInRootPlugin { @@ -15271,18 +16480,19 @@ module.exports = class ModulesInRootPlugin { resolver .getHook(this.source) .tapAsync("ModulesInRootPlugin", (request, resolveContext, callback) => { + /** @type {ResolveRequest} */ const obj = { ...request, path: this.path, - request: "./" + request.request, - module: false + request: `./${request.request}`, + module: false, }; resolver.doResolve( target, obj, - "looking for modules in " + this.path, + `looking for modules in ${this.path}`, resolveContext, - callback + callback, ); }); } @@ -15291,7 +16501,147 @@ module.exports = class ModulesInRootPlugin { /***/ }), -/***/ 8530: +/***/ 70561: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const forEachBail = __nccwpck_require__(34833); +const { getPathsCached } = __nccwpck_require__(84880); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {(err?: null | Error, result?: null | ResolveRequest) => void} InnerCallback */ + +/** + * Per-(directories-array) cache of the flat `addrs` list produced for a given + * `request.path`. For a fixed directories configuration the fan-out of + * `ancestor × directory` is deterministic per request.path, and many resolves + * share the same starting directory (sibling files in one project, loops over + * a batch of imports, etc.) — caching avoids the `getPaths` regex split plus + * `len(paths) × len(directories)` join calls per resolve. + * + * The outer map is keyed on the directories array reference (plugin-owned, + * stable for the lifetime of the resolver), and the inner map on the + * starting `request.path`. Kept private to this module (rather than hung off + * `resolver.pathCache`) so the pathCache's hidden-class shape is unchanged — + * that avoids perturbing the interpreter-mode IC state for the + * `resolver.pathCache.{join,dirname,basename}.fn(...)` accesses that run on + * every resolve, which the CodSpeed instruction-count harness is sensitive to. + * @type {WeakMap>} + */ +const _addrsCacheByDirs = new WeakMap(); + +/** + * @param {Resolver} resolver resolver + * @param {string[]} directories directories + * @param {ResolveStepHook} target target + * @param {ResolveRequest} request request + * @param {ResolveContext} resolveContext resolve context + * @param {InnerCallback} callback callback + * @returns {void} + */ +function modulesResolveHandler( + resolver, + directories, + target, + request, + resolveContext, + callback, +) { + const fs = resolver.fileSystem; + const requestPath = /** @type {string} */ (request.path); + // Compute-or-reuse the flat `addrs` list. Inlined (rather than a helper + // function) so the cache-hit path — which is the vast majority of + // invocations — stays a single WeakMap + Map lookup with no function-call + // overhead. See `_addrsCacheByDirs` above for caching rationale. + let addrs; + let perPath = _addrsCacheByDirs.get(directories); + if (perPath === undefined) { + perPath = new Map(); + _addrsCacheByDirs.set(directories, perPath); + } else { + addrs = perPath.get(requestPath); + } + if (addrs === undefined) { + const { paths } = getPathsCached(fs, requestPath); + const pathsLen = paths.length; + const dirsLen = directories.length; + // Pre-size the flat array rather than going through `map().reduce()` + // with intermediate arrays + spreads. + // eslint-disable-next-line unicorn/no-new-array + addrs = new Array(pathsLen * dirsLen); + let idx = 0; + const joinFn = resolver.pathCache.join.fn; + for (let pi = 0; pi < pathsLen; pi++) { + const pathItem = paths[pi]; + for (let di = 0; di < dirsLen; di++) { + addrs[idx++] = joinFn(pathItem, directories[di]); + } + } + perPath.set(requestPath, addrs); + } + // Hoist the dot-prefixed request out of the per-addr iterator. `addrs` + // can have up to `paths.length × directories.length` entries (e.g. 36 + // for an 8-deep source dir × 4-module config), and concatenating the + // same `./${request.request}` string on every iteration is wasted + // work — it's constant for the whole fan-out. + const relRequest = `./${request.request}`; + forEachBail( + addrs, + /** + * @param {string} addr addr + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @returns {void} + */ + (addr, callback) => { + fs.stat(addr, (err, stat) => { + if (!err && stat && stat.isDirectory()) { + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: addr, + request: relRequest, + module: false, + }; + const message = `looking for modules in ${addr}`; + return resolver.doResolve( + target, + obj, + message, + resolveContext, + callback, + ); + } + if (resolveContext.log) { + resolveContext.log(`${addr} doesn't exist or is not a directory`); + } + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(addr); + } + return callback(); + }); + }, + callback, + ); +} + +module.exports = { + modulesResolveHandler, +}; + + +/***/ }), + +/***/ 86695: /***/ ((module) => { "use strict"; @@ -15332,7 +16682,7 @@ module.exports = class NextPlugin { /***/ }), -/***/ 3103: +/***/ 83103: /***/ ((module) => { "use strict"; @@ -15365,25 +16715,35 @@ module.exports = class ParsePlugin { */ apply(resolver) { const target = resolver.ensureHook(this.target); + const { requestOptions } = this; resolver .getHook(this.source) .tapAsync("ParsePlugin", (request, resolveContext, callback) => { const parsed = resolver.parse(/** @type {string} */ (request.request)); - const obj = { ...request, ...parsed, ...this.requestOptions }; - if (request.query && !parsed.query) { - obj.query = request.query; - } - if (request.fragment && !parsed.fragment) { - obj.fragment = request.fragment; - } + /** @type {ResolveRequest} */ + // Single spread + direct field assignment instead of + // `{ ...request, ...parsed, ...requestOptions }` — avoids + // two extra property enumerations on every resolve. + // Keep in sync with Resolver.parse() output shape. + const obj = { ...request }; + obj.request = parsed.request; + obj.query = parsed.query || request.query || ""; + obj.fragment = parsed.fragment || request.fragment || ""; + obj.module = parsed.module; + obj.directory = parsed.directory; + obj.file = parsed.file; + obj.internal = parsed.internal; + Object.assign(obj, requestOptions); if (parsed && resolveContext.log) { if (parsed.module) resolveContext.log("Parsed request is a module"); - if (parsed.directory) + if (parsed.directory) { resolveContext.log("Parsed request is a directory"); + } } // There is an edge-case where a request with # can be a path or a fragment -> try both if (obj.request && !obj.query && obj.fragment) { const directory = obj.fragment.endsWith("/"); + /** @type {ResolveRequest} */ const alternative = { ...obj, directory, @@ -15391,7 +16751,7 @@ module.exports = class ParsePlugin { obj.request + (obj.directory ? "/" : "") + (directory ? obj.fragment.slice(0, -1) : obj.fragment), - fragment: "" + fragment: "", }; resolver.doResolve( target, @@ -15402,7 +16762,7 @@ module.exports = class ParsePlugin { if (err) return callback(err); if (result) return callback(null, result); resolver.doResolve(target, obj, null, resolveContext, callback); - } + }, ); return; } @@ -15427,9 +16787,10 @@ module.exports = class ParsePlugin { /** @typedef {import("./Resolver")} Resolver */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** - * @typedef {Object} PnpApiImpl - * @property {function(string, string, object): string} resolveToUnqualified + * @typedef {object} PnpApiImpl + * @property {(packageName: string, issuer: string, options: { considerBuiltins: boolean }) => string | null} resolveToUnqualified resolve to unqualified */ module.exports = class PnpPlugin { @@ -15437,11 +16798,13 @@ module.exports = class PnpPlugin { * @param {string | ResolveStepHook} source source * @param {PnpApiImpl} pnpApi pnpApi * @param {string | ResolveStepHook} target target + * @param {string | ResolveStepHook} alternateTarget alternateTarget */ - constructor(source, pnpApi, target) { + constructor(source, pnpApi, target, alternateTarget) { this.source = source; this.pnpApi = pnpApi; this.target = target; + this.alternateTarget = alternateTarget; } /** @@ -15449,7 +16812,9 @@ module.exports = class PnpPlugin { * @returns {void} */ apply(resolver) { + /** @type {ResolveStepHook} */ const target = resolver.ensureHook(this.target); + const alternateTarget = resolver.ensureHook(this.alternateTarget); resolver .getHook(this.source) .tapAsync("PnpPlugin", (request, resolveContext, callback) => { @@ -15462,35 +16827,61 @@ module.exports = class PnpPlugin { const packageMatch = /^(@[^/]+\/)?[^/]+/.exec(req); if (!packageMatch) return callback(); - const packageName = packageMatch[0]; + const [packageName] = packageMatch; const innerRequest = `.${req.slice(packageName.length)}`; + /** @type {string | undefined | null} */ let resolution; + /** @type {string | undefined | null} */ let apiResolution; try { resolution = this.pnpApi.resolveToUnqualified(packageName, issuer, { - considerBuiltins: false + considerBuiltins: false, }); + + if (resolution === null) { + // This is either not a PnP managed issuer or it's a Node builtin + // Try to continue resolving with our alternatives + resolver.doResolve( + alternateTarget, + request, + "issuer is not managed by a pnpapi", + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // Skip alternatives + return callback(null, null); + }, + ); + return; + } + if (resolveContext.fileDependencies) { apiResolution = this.pnpApi.resolveToUnqualified("pnpapi", issuer, { - considerBuiltins: false + considerBuiltins: false, }); } - } catch (error) { + } catch (/** @type {unknown} */ error) { if ( - error.code === "MODULE_NOT_FOUND" && - error.pnpCode === "UNDECLARED_DEPENDENCY" + /** @type {Error & { code: string }} */ + (error).code === "MODULE_NOT_FOUND" && + /** @type {Error & { pnpCode: string }} */ + (error).pnpCode === "UNDECLARED_DEPENDENCY" ) { // This is not a PnP managed dependency. // Try to continue resolving with our alternatives if (resolveContext.log) { - resolveContext.log(`request is not managed by the pnpapi`); - for (const line of error.message.split("\n").filter(Boolean)) + resolveContext.log("request is not managed by the pnpapi"); + for (const line of /** @type {Error} */ (error).message + .split("\n") + .filter(Boolean)) { resolveContext.log(` ${line}`); + } } return callback(); } - return callback(error); + return callback(/** @type {Error} */ (error)); } if (resolution === packageName) return callback(); @@ -15498,13 +16889,13 @@ module.exports = class PnpPlugin { if (apiResolution && resolveContext.fileDependencies) { resolveContext.fileDependencies.add(apiResolution); } - + /** @type {ResolveRequest} */ const obj = { ...request, path: resolution, request: innerRequest, ignoreSymlinks: true, - fullySpecified: request.fullySpecified && innerRequest !== "." + fullySpecified: request.fullySpecified && innerRequest !== ".", }; resolver.doResolve( target, @@ -15516,7 +16907,7 @@ module.exports = class PnpPlugin { if (result) return callback(null, result); // Skip alternatives return callback(null, null); - } + }, ); }); } @@ -15525,7 +16916,7 @@ module.exports = class PnpPlugin { /***/ }), -/***/ 2009: +/***/ 42009: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -15536,136 +16927,590 @@ module.exports = class PnpPlugin { -const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = __nccwpck_require__(8636); +const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = __nccwpck_require__(68636); const createInnerContext = __nccwpck_require__(6072); -const { parseIdentifier } = __nccwpck_require__(2505); +const { parseIdentifier } = __nccwpck_require__(42505); const { - normalize, - cachedJoin: join, + PathType, + createCachedBasename, + createCachedDirname, + createCachedJoin, getType, - PathType -} = __nccwpck_require__(4030); + normalize, + toPath, +} = __nccwpck_require__(64030); + +/* eslint-disable jsdoc/check-alignment */ +// TODO in the next major release use only `Promise.withResolvers()` +const _withResolvers = + // eslint-disable-next-line n/no-unsupported-features/es-syntax + Promise.withResolvers + ? /** + * @param {Resolver} self resolver + * @param {Context} context context information object + * @param {string | URL} path context path or a `file:` URL instance + * @param {string | URL} request request string or a `file:` URL instance + * @param {ResolveContext} resolveContext resolve context + * @returns {Promise} result + */ + (self, context, path, request, resolveContext) => { + // eslint-disable-next-line n/no-unsupported-features/es-syntax + const { promise, resolve, reject } = Promise.withResolvers(); + self.resolve(context, path, request, resolveContext, (err, res) => { + if (err) reject(err); + else resolve(/** @type {string | false} */ (res)); + }); + return promise; + } + : /** + * @param {Resolver} self resolver + * @param {Context} context context information object + * @param {string | URL} path context path or a `file:` URL instance + * @param {string | URL} request request string or a `file:` URL instance + * @param {ResolveContext} resolveContext resolve context + * @returns {Promise} result + */ + (self, context, path, request, resolveContext) => + new Promise((resolve, reject) => { + self.resolve(context, path, request, resolveContext, (err, res) => { + if (err) reject(err); + else resolve(/** @type {string | false} */ (res)); + }); + }); +/* eslint-enable jsdoc/check-alignment */ -/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ +/** @typedef {import("./AliasUtils").AliasOption} AliasOption */ +/** @typedef {import("./util/path").CachedJoin} CachedJoin */ +/** @typedef {import("./util/path").CachedDirname} CachedDirname */ +/** @typedef {import("./util/path").CachedBasename} CachedBasename */ /** - * @typedef {Object} FileSystemStats - * @property {function(): boolean} isDirectory - * @property {function(): boolean} isFile + * @typedef {object} JoinCacheEntry + * @property {CachedJoin["fn"]} fn cached join function + * @property {CachedJoin["cache"]} cache the underlying cache map */ /** - * @typedef {Object} FileSystemDirent - * @property {Buffer | string} name - * @property {function(): boolean} isDirectory - * @property {function(): boolean} isFile + * @typedef {object} DirnameCacheEntry + * @property {CachedDirname["fn"]} fn cached dirname function + * @property {CachedDirname["cache"]} cache the underlying cache map */ /** - * @typedef {Object} PossibleFileSystemError - * @property {string=} code - * @property {number=} errno - * @property {string=} path - * @property {string=} syscall + * @typedef {object} BasenameCacheEntry + * @property {CachedBasename["fn"]} fn cached dirname function + * @property {CachedBasename["cache"]} cache the underlying cache map + */ + +/** + * @typedef {object} PathCacheFunctions + * @property {JoinCacheEntry} join cached join + * @property {DirnameCacheEntry} dirname cached dirname + * @property {BasenameCacheEntry} basename cached basename + */ + +/** @type {WeakMap} */ +const _pathCacheByFs = new WeakMap(); + +const HASH_ESCAPE_RE = /#/g; + +/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ + +/** + * @typedef {object} KnownContext + * @property {string[]=} environments environments + */ + +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {KnownContext & Record} Context */ + +/** @typedef {Error & { details?: string }} ErrorWithDetail */ + +/** @typedef {(err: ErrorWithDetail | null, res?: string | false, req?: ResolveRequest) => void} ResolveCallback */ + +/** + * @typedef {object} PossibleFileSystemError + * @property {string=} code code + * @property {number=} errno number + * @property {string=} path path + * @property {string=} syscall syscall */ /** * @template T * @callback FileSystemCallback - * @param {PossibleFileSystemError & Error | null | undefined} err + * @param {PossibleFileSystemError & Error | null} err * @param {T=} result */ /** - * @typedef {Object} FileSystem - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readFile - * @property {(function(string, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void) & function(string, object, FileSystemCallback<(Buffer | string)[] | FileSystemDirent[]>): void} readdir - * @property {((function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void)=} readJson - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} readlink - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void=} lstat - * @property {(function(string, FileSystemCallback): void) & function(string, object, FileSystemCallback): void} stat + * @typedef {string | Buffer | URL} PathLike + */ + +/** + * @typedef {PathLike | number} PathOrFileDescriptor + */ + +/** + * @typedef {object} ObjectEncodingOptions + * @property {BufferEncoding | null | undefined=} encoding encoding + */ + +/** + * @typedef {ObjectEncodingOptions | BufferEncoding | undefined | null} EncodingOption + */ + +/** @typedef {(err: NodeJS.ErrnoException | null, result?: string) => void} StringCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: Buffer) => void} BufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: (string | Buffer)) => void} StringOrBufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IStats) => void} StatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IBigIntStats) => void} BigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: (IStats | IBigIntStats)) => void} StatsOrBigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | Error | null, result?: JsonObject) => void} ReadJsonCallback */ + +/** + * @template T + * @typedef {object} IStatsBase + * @property {() => boolean} isFile is file + * @property {() => boolean} isDirectory is directory + * @property {() => boolean} isBlockDevice is block device + * @property {() => boolean} isCharacterDevice is character device + * @property {() => boolean} isSymbolicLink is symbolic link + * @property {() => boolean} isFIFO is FIFO + * @property {() => boolean} isSocket is socket + * @property {T} dev dev + * @property {T} ino ino + * @property {T} mode mode + * @property {T} nlink nlink + * @property {T} uid uid + * @property {T} gid gid + * @property {T} rdev rdev + * @property {T} size size + * @property {T} blksize blksize + * @property {T} blocks blocks + * @property {T} atimeMs atime ms + * @property {T} mtimeMs mtime ms + * @property {T} ctimeMs ctime ms + * @property {T} birthtimeMs birthtime ms + * @property {Date} atime atime + * @property {Date} mtime mtime + * @property {Date} ctime ctime + * @property {Date} birthtime birthtime + */ + +/** + * @typedef {IStatsBase} IStats + */ + +/** + * @typedef {IStatsBase & { atimeNs: bigint, mtimeNs: bigint, ctimeNs: bigint, birthtimeNs: bigint }} IBigIntStats + */ + +/** + * @template {string | Buffer} [T=string] + * @typedef {object} Dirent + * @property {() => boolean} isFile true when is file, otherwise false + * @property {() => boolean} isDirectory true when is directory, otherwise false + * @property {() => boolean} isBlockDevice true when is block device, otherwise false + * @property {() => boolean} isCharacterDevice true when is character device, otherwise false + * @property {() => boolean} isSymbolicLink true when is symbolic link, otherwise false + * @property {() => boolean} isFIFO true when is FIFO, otherwise false + * @property {() => boolean} isSocket true when is socket, otherwise false + * @property {T} name name + * @property {string} parentPath path + * @property {string=} path path + */ + +/** + * @typedef {object} StatOptions + * @property {(boolean | undefined)=} bigint need bigint values */ /** - * @typedef {Object} SyncFileSystem - * @property {function(string, object=): Buffer | string} readFileSync - * @property {function(string, object=): (Buffer | string)[] | FileSystemDirent[]} readdirSync - * @property {(function(string, object=): object)=} readJsonSync - * @property {function(string, object=): Buffer | string} readlinkSync - * @property {function(string, object=): FileSystemStats=} lstatSync - * @property {function(string, object=): FileSystemStats} statSync + * @typedef {object} StatSyncOptions + * @property {(boolean | undefined)=} bigint need bigint values + * @property {(boolean | undefined)=} throwIfNoEntry throw if no entry */ /** - * @typedef {Object} ParsedIdentifier - * @property {string} request - * @property {string} query - * @property {string} fragment - * @property {boolean} directory - * @property {boolean} module - * @property {boolean} file - * @property {boolean} internal + * @typedef {{ + * (path: PathOrFileDescriptor, options: ({ encoding?: null | undefined, flag?: string | undefined } & import("events").Abortable) | undefined | null, callback: BufferCallback): void, + * (path: PathOrFileDescriptor, options: ({ encoding: BufferEncoding, flag?: string | undefined } & import("events").Abortable) | BufferEncoding, callback: StringCallback): void, + * (path: PathOrFileDescriptor, options: (ObjectEncodingOptions & { flag?: string | undefined } & import("events").Abortable) | BufferEncoding | undefined | null, callback: StringOrBufferCallback): void, + * (path: PathOrFileDescriptor, callback: BufferCallback): void, + * }} ReadFile */ /** - * @typedef {Object} BaseResolveRequest - * @property {string | false} path - * @property {string=} descriptionFilePath - * @property {string=} descriptionFileRoot - * @property {object=} descriptionFileData - * @property {string=} relativePath - * @property {boolean=} ignoreSymlinks - * @property {boolean=} fullySpecified + * @typedef {"buffer" | { encoding: "buffer" }} BufferEncodingOption + */ + +/** + * @typedef {{ + * (path: PathOrFileDescriptor, options?: { encoding?: null | undefined, flag?: string | undefined } | null): Buffer, + * (path: PathOrFileDescriptor, options: { encoding: BufferEncoding, flag?: string | undefined } | BufferEncoding): string, + * (path: PathOrFileDescriptor, options?: (ObjectEncodingOptions & { flag?: string | undefined }) | BufferEncoding | null): string | Buffer, + * }} ReadFileSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void, + * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer", callback: (err: NodeJS.ErrnoException | null, files?: Buffer[]) => void): void, + * (path: PathLike, options: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[] | Buffer[]) => void): void, + * (path: PathLike, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void, + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files?: Dirent[]) => void): void, + * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void, + * }} Readdir + */ + +/** + * @typedef {{ + * (path: PathLike, options?: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | null): string[], + * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer"): Buffer[], + * (path: PathLike, options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | null): string[] | Buffer[], + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }): Dirent[], + * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }): Dirent[], + * }} ReaddirSync + */ + +/** + * @typedef {(pathOrFileDescription: PathOrFileDescriptor, callback: ReadJsonCallback) => void} ReadJson + */ + +/** + * @typedef {(pathOrFileDescription: PathOrFileDescriptor) => JsonObject} ReadJsonSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void, + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void, + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void, + * (path: PathLike, callback: StringCallback): void, + * }} Readlink + */ + +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string, + * (path: PathLike, options: BufferEncodingOption): Buffer, + * (path: PathLike, options?: EncodingOption): string | Buffer, + * }} ReadlinkSync + */ + +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void, + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void, + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void, + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void, + * }} LStat + */ + +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats, + * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats, + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats, + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, + * }} LStatSync + */ + +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void, + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void, + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void, + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void, + * }} Stat + */ + +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined }): IStats, + * (path: PathLike, options: StatSyncOptions & { bigint: true }): IBigIntStats, + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: false | undefined }): IStats | IBigIntStats, + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, + * }} StatSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void, + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void, + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void, + * (path: PathLike, callback: StringCallback): void, + * }} RealPath + */ + +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string, + * (path: PathLike, options: BufferEncodingOption): Buffer, + * (path: PathLike, options?: EncodingOption): string | Buffer, + * }} RealPathSync + */ + +/** + * @typedef {object} FileSystem + * @property {ReadFile} readFile read file method + * @property {Readdir} readdir readdir method + * @property {ReadJson=} readJson read json method + * @property {Readlink} readlink read link method + * @property {LStat=} lstat lstat method + * @property {Stat} stat stat method + * @property {RealPath=} realpath realpath method + */ + +/** + * @typedef {object} SyncFileSystem + * @property {ReadFileSync} readFileSync read file sync method + * @property {ReaddirSync} readdirSync read dir sync method + * @property {ReadJsonSync=} readJsonSync read json sync method + * @property {ReadlinkSync} readlinkSync read link sync method + * @property {LStatSync=} lstatSync lstat sync method + * @property {StatSync} statSync stat sync method + * @property {RealPathSync=} realpathSync real path sync method + */ + +/** + * @typedef {object} ParsedIdentifier + * @property {string} request request + * @property {string} query query + * @property {string} fragment fragment + * @property {boolean} directory is directory + * @property {boolean} module is module + * @property {boolean} file is file + * @property {boolean} internal is internal + */ + +/** @typedef {string | number | boolean | null} JsonPrimitive */ +/** @typedef {JsonValue[]} JsonArray */ +/** @typedef {JsonPrimitive | JsonObject | JsonArray} JsonValue */ +/** @typedef {{ [Key in string]?: JsonValue | undefined }} JsonObject */ + +/** + * @typedef {object} TsconfigPathsMap + * @property {TsconfigPathsData} main main tsconfig paths data + * @property {string} mainContext main tsconfig base URL (absolute path) + * @property {{ [baseUrl: string]: TsconfigPathsData }} refs referenced tsconfig paths data mapped by baseUrl + * @property {{ [context: string]: TsconfigPathsData }} allContexts all contexts (main + refs) for quick lookup + * @property {string[]} contextList precomputed `Object.keys(allContexts)` — read-only; used on the `_selectPathsDataForContext` hot path + * @property {Set} fileDependencies file dependencies + */ + +/** + * @typedef {object} TsconfigPathsData + * @property {import("./AliasUtils").CompiledAliasOptions} alias tsconfig file data + * @property {string[]} modules tsconfig file data + */ + +/** + * @typedef {object} BaseResolveRequest + * @property {string | false} path path + * @property {Context=} context content + * @property {string=} descriptionFilePath description file path + * @property {string=} descriptionFileRoot description file root + * @property {JsonObject=} descriptionFileData description file data + * @property {TsconfigPathsMap | null | undefined=} tsconfigPathsMap tsconfig paths map + * @property {string=} relativePath relative path + * @property {boolean=} ignoreSymlinks true when need to ignore symlinks, otherwise false + * @property {boolean=} fullySpecified true when full specified, otherwise false + * @property {string=} __innerRequest inner request for internal usage + * @property {string=} __innerRequest_request inner request for internal usage + * @property {string=} __innerRequest_relativePath inner relative path for internal usage + * @property {{ blocked: boolean }=} __restrictionsMarker internal: shared marker `RestrictionsPlugin` flips when it filters out an existing target, letting `ExportsFieldPlugin` fall back instead of erroring */ /** @typedef {BaseResolveRequest & Partial} ResolveRequest */ /** - * String with special formatting - * @typedef {string} StackEntry + * @template T + * @typedef {{ add: (item: T) => void }} WriteOnlySet */ -/** @template T @typedef {{ add: (T) => void }} WriteOnlySet */ +/** @typedef {(request: ResolveRequest) => void} ResolveContextYield */ + +/** + * Singly-linked stack entry that also exposes a Set-like API + * (`has`, `size`, iteration). Each `doResolve` call prepends a new + * `StackEntry` that points at the previous tip via `.parent`, so pushing + * is O(1) in time and memory. Recursion detection walks the linked list + * (O(n)) but the stack is typically shallow, so this is cheaper overall + * than cloning a `Set` per call. + */ +class StackEntry { + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {StackEntry=} parent previous tip + * @param {Set=} preSeeded entries pre-seeded via the legacy `Set` API + */ + constructor(hook, request, parent, preSeeded) { + this.name = hook.name; + this.path = request.path; + this.request = request.request || ""; + this.query = request.query || ""; + this.fragment = request.fragment || ""; + this.directory = Boolean(request.directory); + this.module = Boolean(request.module); + /** @type {StackEntry | undefined} */ + this.parent = parent; + /** + * Strings seeded by callers that still pass `stack: new Set([...])`. + * Propagated through the chain so deeper `doResolve` calls still see + * them during recursion checks. `undefined` in the common case so + * there is no extra work on the hot path. + * @type {Set | undefined} + */ + this.preSeeded = preSeeded; + } + + /** + * Walk the linked list looking for an entry with the same request shape. + * Set-compatible: callers that used `stack.has(entry)` keep working. + * + * NOTE: kept monomorphic on purpose. An earlier draft accepted a string + * query too (so pre-5.21 plugins keeping their own `Set` of + * seen entries could probe the live stack with the formatted form), + * but adding the second shape regressed `doResolve`'s heap profile by + * ~1 MiB / 200 resolves on stack-churn — V8 keeps a polymorphic + * call-site state for `parent.has(stackEntry)` once `has` has two + * argument shapes. Plugins that need string membership can reach for + * `[...stack].find(e => e.includes(formattedString))` via the + * `String`-method proxies on `StackEntry` instead. + * @param {StackEntry} query entry to look for + * @returns {boolean} whether the stack already contains an equivalent entry + */ + has(query) { + /** @type {StackEntry | undefined} */ + let node = this; + while (node) { + if ( + node.name === query.name && + node.path === query.path && + node.request === query.request && + node.query === query.query && + node.fragment === query.fragment && + node.directory === query.directory && + node.module === query.module + ) { + return true; + } + node = node.parent; + } + return this.preSeeded !== undefined && this.preSeeded.has(query.toString()); + } + + /** + * Number of entries on the stack (oldest-to-newest length). + * @returns {number} size + */ + get size() { + let count = this.preSeeded ? this.preSeeded.size : 0; + /** @type {StackEntry | undefined} */ + let node = this; + while (node) { + count++; + node = node.parent; + } + return count; + } + + /** + * Iterate entries from oldest (root) to newest (tip), matching how a + * `Set` that was populated in insertion order would iterate. Pre-seeded + * legacy `Set` entries come first so error-message output stays + * ordered oldest-to-newest. + * + * Yields each entry as its formatted `toString()` form. Plugins written + * against the pre-5.21 `Set` shape — e.g. + * `[...resolveContext.stack].find(a => a.includes("module:"))` — keep + * working unchanged because each yielded value is a plain string with + * all of `String.prototype` available natively. Resolves that never + * iterate the stack pay nothing; iteration costs one `toString()` + * allocation per stack frame. + * @returns {IterableIterator} iterator + */ + *[Symbol.iterator]() { + if (this.preSeeded !== undefined) { + for (const entry of this.preSeeded) yield entry; + } + /** @type {StackEntry[]} */ + const entries = []; + /** @type {StackEntry | undefined} */ + let node = this; + while (node) { + entries.push(node); + node = node.parent; + } + for (let i = entries.length - 1; i >= 0; i--) yield entries[i].toString(); + } + + /** + * Human-readable form used in recursion error messages, logs, and the + * iterator above. Not memoized: caching would require an extra slot on + * every `StackEntry`, which costs heap even on resolves that never look + * at the formatted form. + * @returns {string} formatted entry + */ + toString() { + return `${this.name}: (${this.path}) ${this.request}${this.query}${ + this.fragment + }${this.directory ? " directory" : ""}${this.module ? " module" : ""}`; + } +} /** * Resolve context - * @typedef {Object} ResolveContext - * @property {WriteOnlySet=} contextDependencies + * @typedef {object} ResolveContext + * @property {WriteOnlySet=} contextDependencies directories that was found on file system * @property {WriteOnlySet=} fileDependencies files that was found on file system * @property {WriteOnlySet=} missingDependencies dependencies that was not found on file system - * @property {Set=} stack set of hooks' calls. For instance, `resolve → parsedResolve → describedResolve`, - * @property {(function(string): void)=} log log function - * @property {(function (ResolveRequest): void)=} yield yield result, if provided plugins can return several results + * @property {StackEntry | Set=} stack tip of the resolver call stack (a singly-linked list with Set-like API). For instance, `resolve → parsedResolve → describedResolve`. Accepts a legacy `Set` for back-compat with older callers; it is normalized internally without a hot-path branch. + * @property {((str: string) => void)=} log log function + * @property {ResolveContextYield=} yield yield result, if provided plugins can return several results */ /** @typedef {AsyncSeriesBailHook<[ResolveRequest, ResolveContext], ResolveRequest | null>} ResolveStepHook */ +/** + * @typedef {object} KnownHooks + * @property {SyncHook<[ResolveStepHook, ResolveRequest], void>} resolveStep resolve step hook + * @property {SyncHook<[ResolveRequest, Error]>} noResolve no resolve hook + * @property {ResolveStepHook} resolve resolve hook + * @property {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} result result hook + */ + +/** + * @typedef {{ [key: string]: ResolveStepHook }} EnsuredHooks + */ + /** * @param {string} str input string * @returns {string} in camel case */ function toCamelCase(str) { - return str.replace(/-([a-z])/g, str => str.substr(1).toUpperCase()); + return str.replace(/-([a-z])/g, (str) => str.slice(1).toUpperCase()); } class Resolver { /** * @param {ResolveStepHook} hook hook * @param {ResolveRequest} request request + * @param {StackEntry=} parent previous tip of the stack + * @param {Set=} preSeeded entries pre-seeded via the legacy `Set` API * @returns {StackEntry} stack entry */ - static createStackEntry(hook, request) { - return ( - hook.name + - ": (" + - request.path + - ") " + - (request.request || "") + - (request.query || "") + - (request.fragment || "") + - (request.directory ? " directory" : "") + - (request.module ? " module" : "") - ); + static createStackEntry(hook, request, parent, preSeeded) { + return new StackEntry(hook, request, parent, preSeeded); } /** @@ -15673,20 +17518,30 @@ class Resolver { * @param {ResolveOptions} options options */ constructor(fileSystem, options) { + /** @type {FileSystem} */ this.fileSystem = fileSystem; + /** @type {ResolveOptions} */ this.options = options; + let pathCache = _pathCacheByFs.get(fileSystem); + if (!pathCache) { + pathCache = { + join: createCachedJoin(), + dirname: createCachedDirname(), + basename: createCachedBasename(), + }; + _pathCacheByFs.set(fileSystem, pathCache); + } + /** @type {PathCacheFunctions} */ + this.pathCache = pathCache; + /** @type {KnownHooks} */ this.hooks = { - /** @type {SyncHook<[ResolveStepHook, ResolveRequest], void>} */ resolveStep: new SyncHook(["hook", "request"], "resolveStep"), - /** @type {SyncHook<[ResolveRequest, Error]>} */ noResolve: new SyncHook(["request", "error"], "noResolve"), - /** @type {ResolveStepHook} */ resolve: new AsyncSeriesBailHook( ["request", "resolveContext"], - "resolve" + "resolve", ), - /** @type {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} */ - result: new AsyncSeriesHook(["result", "resolveContext"], "result") + result: new AsyncSeriesHook(["result", "resolveContext"], "result"), }; } @@ -15699,26 +17554,30 @@ class Resolver { return name; } name = toCamelCase(name); - if (/^before/.test(name)) { - return /** @type {ResolveStepHook} */ (this.ensureHook( - name[6].toLowerCase() + name.substr(7) - ).withOptions({ - stage: -10 - })); + if (name.startsWith("before")) { + return /** @type {ResolveStepHook} */ ( + this.ensureHook(name[6].toLowerCase() + name.slice(7)).withOptions({ + stage: -10, + }) + ); } - if (/^after/.test(name)) { - return /** @type {ResolveStepHook} */ (this.ensureHook( - name[5].toLowerCase() + name.substr(6) - ).withOptions({ - stage: 10 - })); + if (name.startsWith("after")) { + return /** @type {ResolveStepHook} */ ( + this.ensureHook(name[5].toLowerCase() + name.slice(6)).withOptions({ + stage: 10, + }) + ); } - const hook = this.hooks[name]; + /** @type {ResolveStepHook} */ + const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name]; if (!hook) { - return (this.hooks[name] = new AsyncSeriesBailHook( + /** @type {KnownHooks & EnsuredHooks} */ + (this.hooks)[name] = new AsyncSeriesBailHook( ["request", "resolveContext"], - name - )); + name, + ); + + return /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name]; } return hook; } @@ -15732,21 +17591,22 @@ class Resolver { return name; } name = toCamelCase(name); - if (/^before/.test(name)) { - return /** @type {ResolveStepHook} */ (this.getHook( - name[6].toLowerCase() + name.substr(7) - ).withOptions({ - stage: -10 - })); + if (name.startsWith("before")) { + return /** @type {ResolveStepHook} */ ( + this.getHook(name[6].toLowerCase() + name.slice(7)).withOptions({ + stage: -10, + }) + ); } - if (/^after/.test(name)) { - return /** @type {ResolveStepHook} */ (this.getHook( - name[5].toLowerCase() + name.substr(6) - ).withOptions({ - stage: 10 - })); + if (name.startsWith("after")) { + return /** @type {ResolveStepHook} */ ( + this.getHook(name[5].toLowerCase() + name.slice(6)).withOptions({ + stage: 10, + }) + ); } - const hook = this.hooks[name]; + /** @type {ResolveStepHook} */ + const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name]; if (!hook) { throw new Error(`Hook ${name} doesn't exist`); } @@ -15754,25 +17614,50 @@ class Resolver { } /** - * @param {object} context context information object - * @param {string} path context path - * @param {string} request request string + * @overload + * @param {string | URL} parent context path or a `file:` URL instance + * @param {string | URL} specifier request string or a `file:` URL instance + * @param {ResolveContext=} resolveContext resolve context * @returns {string | false} result */ - resolveSync(context, path, request) { + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL instance + * @param {string | URL} specifier request string or a `file:` URL instance + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + /** + * @param {Context | string | URL} context context information object, or the context path (string or `file:` URL instance) when no context is provided + * @param {string | URL | ResolveContext=} parent context path (string or `file:` URL instance) or resolve context when no context is provided + * @param {string | URL | ResolveContext=} specifier request string (or `file:` URL instance) or resolve context when no context is provided + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + resolveSync(context, parent, specifier, resolveContext) { /** @type {Error | null | undefined} */ - let err = undefined; + let err; /** @type {string | false | undefined} */ - let result = undefined; + let result; let sync = false; - this.resolve(context, path, request, {}, (e, r) => { - err = e; - result = r; - sync = true; - }); + // `|| {}` so the underlying `resolve()` hits its 5-arg fast path + // (skips the overload-shifting prologue) regardless of whether the + // caller supplied a resolveContext. + this.resolve( + /** @type {Context} */ (context), + /** @type {string} */ (parent), + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext) || {}, + (_err, r) => { + err = _err; + result = r; + sync = true; + }, + ); if (!sync) { throw new Error( - "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!" + "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!", ); } if (err) throw err; @@ -15781,78 +17666,229 @@ class Resolver { } /** - * @param {object} context context information object - * @param {string} path context path - * @param {string} request request string + * @overload + * @param {string | URL} parent context path or a `file:` URL instance + * @param {string | URL} specifier request string or a `file:` URL instance + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL instance + * @param {string | URL} specifier request string or a `file:` URL instance + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + /** + * @param {Context | string | URL} context context information object, or the context path (string or `file:` URL instance) when no context is provided + * @param {string | URL | ResolveContext=} parent context path (string or `file:` URL instance) or resolve context when no context is provided + * @param {string | URL | ResolveContext=} specifier request string (or `file:` URL instance) or resolve context when no context is provided + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + resolvePromise(context, parent, specifier, resolveContext) { + // `|| {}` ensures the 5-arg fast path inside `resolve()` is reached + // even when the caller doesn't pass a resolveContext. + return _withResolvers( + this, + /** @type {Context} */ (context), + /** @type {string} */ (parent), + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext) || {}, + ); + } + + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL instance + * @param {string | URL} specifier request string or a `file:` URL instance + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL instance + * @param {string | URL} specifier request string or a `file:` URL instance * @param {ResolveContext} resolveContext resolve context - * @param {function(Error | null, (string|false)=, ResolveRequest=): void} callback callback function + * @param {ResolveCallback} callback callback function * @returns {void} */ - resolve(context, path, request, resolveContext, callback) { - if (!context || typeof context !== "object") - return callback(new Error("context argument is not an object")); - if (typeof path !== "string") - return callback(new Error("path argument is not a string")); - if (typeof request !== "string") - return callback(new Error("request argument is not a string")); - if (!resolveContext) - return callback(new Error("resolveContext argument is not set")); + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL instance + * @param {string | URL} specifier request string or a `file:` URL instance + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL instance + * @param {string | URL} specifier request string or a `file:` URL instance + * @param {ResolveContext} resolveContext resolve context + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @param {Context | string | URL} context context information object, or the context path (string or `file:` URL instance) when no context is provided + * @param {string | URL | ResolveContext | ResolveCallback=} parent context path (string or `file:` URL instance) or (when no context) resolve context or callback + * @param {string | URL | ResolveContext | ResolveCallback=} specifier request string (or `file:` URL instance) or (when no context) resolve context or callback + * @param {ResolveContext | ResolveCallback=} resolveContext resolve context or callback when no resolve context is provided + * @param {ResolveCallback=} callback callback function + * @returns {void} + */ + resolve(context, parent, specifier, resolveContext, callback) { + // Fast path for the common 5-arg call (`resolver.resolve(ctx, from, + // req, resolveCtx, cb)`) — every call from `resolveSync` / + // `resolvePromise` plus the vast majority of direct API callers. + // PR #536 added runtime overload-shifting to support optional + // `context` / `resolveContext`; that adds several `typeof` checks + // per resolve which show up as a measurable instruction-count + // regression on every benchmark that calls into this method. Skip + // the shifting entirely when all 5 args are already well-typed. + if ( + typeof callback === "function" && + typeof context === "object" && + context !== null && + typeof resolveContext === "object" && + resolveContext !== null + ) { + // proceed straight to per-arg validation below + } else { + // Slow path: shift positional args based on what was supplied. + // Shift when context is omitted (first positional arg is the parent, + // either a string or a `file:` URL instance). + if (typeof context === "string" || context instanceof URL) { + // Keep an already-supplied callback (resolveSync / resolvePromise + // always pass one in the 5th position). + if (typeof callback !== "function") { + callback = /** @type {ResolveCallback | undefined} */ ( + resolveContext + ); + } + resolveContext = + /** @type {ResolveContext | ResolveCallback | undefined} */ ( + specifier + ); + specifier = /** @type {string} */ (parent); + parent = context; + context = {}; + } + // 4-arg form: the resolveContext slot holds the callback. + if (typeof resolveContext === "function") { + callback = resolveContext; + resolveContext = {}; + } else if (!resolveContext || typeof resolveContext !== "object") { + resolveContext = {}; + } + if (typeof callback !== "function") { + throw new TypeError("callback argument is not a function"); + } + if (!context || typeof context !== "object") { + context = {}; + } + } + // Accept `file:` URL instances for parent/specifier, converting to a + // filesystem path (mirrors the URL support in resolve options). The + // `instanceof` check sits on the error branch, so the common string + // case keeps its single `typeof` check on this hot path. + if (typeof parent !== "string") { + if (parent instanceof URL) parent = toPath(parent); + else return callback(new Error("path argument is not a string")); + } + if (typeof specifier !== "string") { + if (specifier instanceof URL) specifier = toPath(specifier); + else return callback(new Error("request argument is not a string")); + } + /** @type {ResolveRequest} */ const obj = { - context: context, - path: path, - request: request + context, + path: parent, + request: specifier, }; + /** @type {ResolveContextYield | undefined} */ let yield_; let yieldCalled = false; + /** @type {ResolveContextYield | undefined} */ let finishYield; if (typeof resolveContext.yield === "function") { const old = resolveContext.yield; - yield_ = obj => { + /** + * @param {ResolveRequest} obj object + */ + yield_ = (obj) => { old(obj); yieldCalled = true; }; - finishYield = result => { - if (result) yield_(result); + /** + * @param {ResolveRequest} result result + * @returns {void} + */ + finishYield = (result) => { + if (result) { + /** @type {ResolveContextYield} */ (yield_)(result); + } callback(null); }; } - const message = `resolve '${request}' in '${path}'`; - - const finishResolved = result => { + /** + * @param {ResolveRequest} result result + * @returns {void} + */ + const finishResolved = (result) => { + const resultPath = result.path; + if (resultPath === false) return callback(null, false, result); + const escapedPath = resultPath.includes("#") + ? resultPath.replace(HASH_ESCAPE_RE, "\0#") + : resultPath; + const resultQuery = result.query; + let escapedQuery; + if (resultQuery) { + escapedQuery = resultQuery.includes("#") + ? resultQuery.replace(HASH_ESCAPE_RE, "\0#") + : resultQuery; + } else { + escapedQuery = ""; + } return callback( null, - result.path === false - ? false - : `${result.path.replace(/#/g, "\0#")}${ - result.query ? result.query.replace(/#/g, "\0#") : "" - }${result.fragment || ""}`, - result + `${escapedPath}${escapedQuery}${result.fragment || ""}`, + result, ); }; - const finishWithoutResolve = log => { + /** + * @param {string} message resolve message + * @param {string[]} log logs + * @returns {void} + */ + const finishWithoutResolve = (message, log) => { /** - * @type {Error & {details?: string}} + * @type {ErrorWithDetail} */ - const error = new Error("Can't " + message); + const error = new Error(`Can't ${message}`); error.details = log.join("\n"); this.hooks.noResolve.call(obj, error); return callback(error); }; if (resolveContext.log) { + const message = `resolve '${specifier}' in '${parent}'`; // We need log anyway to capture it in case of an error const parentLog = resolveContext.log; + /** @type {string[]} */ const log = []; return this.doResolve( this.hooks.resolve, obj, message, { - log: msg => { + log: (msg) => { parentLog(msg); log.push(msg); }, @@ -15860,114 +17896,165 @@ class Resolver { fileDependencies: resolveContext.fileDependencies, contextDependencies: resolveContext.contextDependencies, missingDependencies: resolveContext.missingDependencies, - stack: resolveContext.stack + stack: resolveContext.stack, }, (err, result) => { if (err) return callback(err); - if (yieldCalled || (result && yield_)) return finishYield(result); + if (yieldCalled || (result && yield_)) { + return /** @type {ResolveContextYield} */ (finishYield)( + /** @type {ResolveRequest} */ (result), + ); + } + if (result) return finishResolved(result); - return finishWithoutResolve(log); - } + return finishWithoutResolve(message, log); + }, ); - } else { - // Try to resolve assuming there is no error - // We don't log stuff in this case - return this.doResolve( - this.hooks.resolve, - obj, - message, - { + } + // Try to resolve assuming there is no error + // We don't log stuff in this case + // When there is no yield wrapper, the caller's resolveContext can + // be passed directly — its `log` is already falsy (we are in the + // !log branch) and `yield` is undefined, so a fresh wrapper would + // be an identical copy. + const rc = yield_ + ? { log: undefined, yield: yield_, fileDependencies: resolveContext.fileDependencies, contextDependencies: resolveContext.contextDependencies, missingDependencies: resolveContext.missingDependencies, - stack: resolveContext.stack - }, - (err, result) => { - if (err) return callback(err); + stack: resolveContext.stack, + } + : resolveContext; + return this.doResolve(this.hooks.resolve, obj, null, rc, (err, result) => { + if (err) return callback(err); - if (yieldCalled || (result && yield_)) return finishYield(result); - if (result) return finishResolved(result); + if (yieldCalled || (result && yield_)) { + return /** @type {ResolveContextYield} */ (finishYield)( + /** @type {ResolveRequest} */ (result), + ); + } - // log is missing for the error details - // so we redo the resolving for the log info - // this is more expensive to the success case - // is assumed by default + if (result) return finishResolved(result); - const log = []; + // log is missing for the error details + // so we redo the resolving for the log info + // this is more expensive to the success case + // is assumed by default + const message = `resolve '${specifier}' in '${parent}'`; + /** @type {string[]} */ + const log = []; - return this.doResolve( - this.hooks.resolve, - obj, - message, - { - log: msg => log.push(msg), - yield: yield_, - stack: resolveContext.stack - }, - (err, result) => { - if (err) return callback(err); + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: (msg) => log.push(msg), + yield: yield_, + stack: resolveContext.stack, + }, + (err, result) => { + if (err) return callback(err); - // In a case that there is a race condition and yield will be called - if (yieldCalled || (result && yield_)) return finishYield(result); + // In a case that there is a race condition and yield will be called + if (yieldCalled || (result && yield_)) { + return /** @type {ResolveContextYield} */ (finishYield)( + /** @type {ResolveRequest} */ (result), + ); + } - return finishWithoutResolve(log); - } - ); - } + return finishWithoutResolve(message, log); + }, ); - } + }); } + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {null | string} message string + * @param {ResolveContext} resolveContext resolver context + * @param {(err?: null | Error, result?: ResolveRequest) => void} callback callback + * @returns {void} + */ doResolve(hook, request, message, resolveContext, callback) { - const stackEntry = Resolver.createStackEntry(hook, request); + const rawStack = resolveContext.stack; + /** @type {StackEntry | undefined} */ + let parent; + /** @type {Set | undefined} */ + let preSeeded; + if (rawStack instanceof StackEntry) { + parent = rawStack; + preSeeded = rawStack.preSeeded; + } else if (rawStack) { + // TODO in the next major remove `Set` support in favor of `StackEntry` + // Legacy `stack: new Set()` API: don't link the Set into + // the parent chain (it would pollute iteration and field-compare + // walks). Carry the strings on the StackEntry itself instead so + // deeper `doResolve` calls keep seeing pre-seeded entries. + preSeeded = /** @type {Set} */ (rawStack); + } + // Prepend a new linked-list node. O(1) allocation, no Set clone. + const stackEntry = Resolver.createStackEntry( + hook, + request, + parent, + preSeeded, + ); - let newStack; - if (resolveContext.stack) { - newStack = new Set(resolveContext.stack); - if (resolveContext.stack.has(stackEntry)) { - /** - * Prevent recursion - * @type {Error & {recursion?: boolean}} - */ - const recursionError = new Error( - "Recursion in resolving\nStack:\n " + - Array.from(newStack).join("\n ") - ); - recursionError.recursion = true; - if (resolveContext.log) - resolveContext.log("abort resolving because of recursion"); - return callback(recursionError); + // When `parent` exists, its `has()` already consults `preSeeded` + // (inherited from the same chain), so we only need the direct Set + // lookup on the very first `doResolve` call (no parent yet). + if ( + parent !== undefined + ? parent.has(stackEntry) + : preSeeded !== undefined && preSeeded.has(stackEntry.toString()) + ) { + /** + * Prevent recursion + * @type {Error & { recursion?: boolean }} + */ + const recursionError = new Error( + `Recursion in resolving\nStack:\n ${[...stackEntry].join("\n ")}`, + ); + recursionError.recursion = true; + if (resolveContext.log) { + resolveContext.log("abort resolving because of recursion"); } - newStack.add(stackEntry); - } else { - newStack = new Set([stackEntry]); + return callback(recursionError); } this.hooks.resolveStep.call(hook, request); if (hook.isUsed()) { + // No-log fast path: when the context was created internally + // (stack is already a StackEntry from a prior doResolve), we + // can mutate stack in-place and restore it in the callback, + // avoiding the createInnerContext allocation entirely. + if (!resolveContext.log && rawStack instanceof StackEntry) { + resolveContext.stack = stackEntry; + return hook.callAsync(request, resolveContext, (err, result) => { + resolveContext.stack = rawStack; + if (err) return callback(err); + if (result) return callback(null, result); + callback(); + }); + } const innerContext = createInnerContext( - { - log: resolveContext.log, - yield: resolveContext.yield, - fileDependencies: resolveContext.fileDependencies, - contextDependencies: resolveContext.contextDependencies, - missingDependencies: resolveContext.missingDependencies, - stack: newStack - }, - message + resolveContext, + stackEntry, + message, ); return hook.callAsync(request, innerContext, (err, result) => { if (err) return callback(err); if (result) return callback(null, result); callback(); }); - } else { - callback(); } + callback(); } /** @@ -15975,6 +18062,7 @@ class Resolver { * @returns {ParsedIdentifier} parsed identifier */ parse(identifier) { + /** @type {ParsedIdentifier} */ const part = { request: "", query: "", @@ -15982,7 +18070,7 @@ class Resolver { module: false, directory: false, file: false, - internal: false + internal: false, }; const parsedIdentifier = parseIdentifier(identifier); @@ -15992,21 +18080,45 @@ class Resolver { [part.request, part.query, part.fragment] = parsedIdentifier; if (part.request.length > 0) { - part.internal = this.isPrivate(identifier); - part.module = this.isModule(part.request); - part.directory = this.isDirectory(part.request); + // `getType` looks at the prefix of its input and the prefix is + // identical between `identifier` and `part.request` in every + // non-`\0`-escape case (slicing off `?query` / `#fragment` doesn't + // touch the head). `parseIdentifier`'s common fast path returns + // the same `identifier` reference as `parsedIdentifier[0]`, so a + // pointer-equality check detects the case where we can compute + // `getType` once and use it for both `module` and `internal`. The + // `\0#…` escape path produces a fresh `part.request` and falls + // through to the second `getType(identifier)` call to preserve + // the original `internal` flag. + const requestType = getType(part.request); + part.module = requestType === PathType.Normal; + part.internal = + identifier === part.request + ? requestType === PathType.Internal + : getType(identifier) === PathType.Internal; + // `isDirectory` is just `endsWith("/")` — inline so `parse()` + // doesn't pay for the extra method dispatch on every resolve. + part.directory = part.request.endsWith("/"); if (part.directory) { - part.request = part.request.substr(0, part.request.length - 1); + part.request = part.request.slice(0, -1); } } return part; } + /** + * @param {string} path path + * @returns {boolean} true, if the path is a module + */ isModule(path) { return getType(path) === PathType.Normal; } + /** + * @param {string} path path + * @returns {boolean} true, if the path is private + */ isPrivate(path) { return getType(path) === PathType.Internal; } @@ -16019,12 +18131,38 @@ class Resolver { return path.endsWith("/"); } + /** + * @param {string} path path + * @returns {string} normalized path + */ + normalize(path) { + return normalize(path); + } + + /** + * @param {string} path path + * @param {string} request request + * @returns {string} joined path + */ join(path, request) { - return join(path, request); + return this.pathCache.join.fn(path, request); } - normalize(path) { - return normalize(path); + /** + * @param {string} path path + * @returns {string} parent directory + */ + dirname(path) { + return this.pathCache.dirname.fn(path); + } + + /** + * @param {string} path the path to evaluate + * @param {string=} suffix an extension to remove from the result + * @returns {string} the last portion of a path + */ + basename(path, suffix) { + return this.pathCache.basename.fn(path, suffix); } } @@ -16033,8 +18171,8 @@ module.exports = Resolver; /***/ }), -/***/ 5429: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 25429: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* @@ -16044,58 +18182,81 @@ module.exports = Resolver; -const versions = (__nccwpck_require__(7282).versions); -const Resolver = __nccwpck_require__(2009); -const { getType, PathType } = __nccwpck_require__(4030); - -const SyncAsyncFileSystemDecorator = __nccwpck_require__(4233); +// eslint-disable-next-line n/prefer-global/process +const { versions } = __nccwpck_require__(77282); const AliasFieldPlugin = __nccwpck_require__(3645); -const AliasPlugin = __nccwpck_require__(7222); +const AliasPlugin = __nccwpck_require__(77222); const AppendPlugin = __nccwpck_require__(5864); -const ConditionalPlugin = __nccwpck_require__(5315); -const DescriptionFilePlugin = __nccwpck_require__(7644); -const DirectoryExistsPlugin = __nccwpck_require__(674); -const ExportsFieldPlugin = __nccwpck_require__(1866); -const ExtensionAliasPlugin = __nccwpck_require__(2894); +const ConditionalPlugin = __nccwpck_require__(55607); +const DescriptionFilePlugin = __nccwpck_require__(87644); +const DirectoryExistsPlugin = __nccwpck_require__(80674); +const ExportsFieldPlugin = __nccwpck_require__(81866); +const ExtensionAliasPlugin = __nccwpck_require__(82894); const FileExistsPlugin = __nccwpck_require__(6157); const ImportsFieldPlugin = __nccwpck_require__(5860); -const JoinRequestPartPlugin = __nccwpck_require__(8095); -const JoinRequestPlugin = __nccwpck_require__(2010); -const MainFieldPlugin = __nccwpck_require__(3438); -const ModulesInHierarchicalDirectoriesPlugin = __nccwpck_require__(8409); -const ModulesInRootPlugin = __nccwpck_require__(9650); -const NextPlugin = __nccwpck_require__(8530); -const ParsePlugin = __nccwpck_require__(3103); +const JoinRequestPartPlugin = __nccwpck_require__(58095); +const JoinRequestPlugin = __nccwpck_require__(22010); +const MainFieldPlugin = __nccwpck_require__(83438); +const ModulesInHierarchicalDirectoriesPlugin = __nccwpck_require__(78409); +const ModulesInRootPlugin = __nccwpck_require__(59650); +const NextPlugin = __nccwpck_require__(86695); +const ParsePlugin = __nccwpck_require__(83103); const PnpPlugin = __nccwpck_require__(2049); +const Resolver = __nccwpck_require__(42009); const RestrictionsPlugin = __nccwpck_require__(7659); -const ResultPlugin = __nccwpck_require__(7534); -const RootsPlugin = __nccwpck_require__(6836); -const SelfReferencePlugin = __nccwpck_require__(2148); -const SymlinkPlugin = __nccwpck_require__(7138); -const TryNextPlugin = __nccwpck_require__(2351); -const UnsafeCachePlugin = __nccwpck_require__(7604); -const UseFilePlugin = __nccwpck_require__(2229); +const ResultPlugin = __nccwpck_require__(53254); +const RootsPlugin = __nccwpck_require__(36836); +const SelfReferencePlugin = __nccwpck_require__(53600); +const SymlinkPlugin = __nccwpck_require__(67138); +const SyncAsyncFileSystemDecorator = __nccwpck_require__(14233); +const TryNextPlugin = __nccwpck_require__(22351); +const TsconfigPathsPlugin = __nccwpck_require__(19012); +const UnsafeCachePlugin = __nccwpck_require__(97604); +const UseFilePlugin = __nccwpck_require__(92229); +const { PathType, getType, toPath } = __nccwpck_require__(64030); /** @typedef {import("./AliasPlugin").AliasOption} AliasOptionEntry */ /** @typedef {import("./ExtensionAliasPlugin").ExtensionAliasOption} ExtensionAliasOption */ /** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver").EnsuredHooks} EnsuredHooks */ /** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").KnownHooks} KnownHooks */ /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +/** @typedef {import("./UnsafeCachePlugin").Cache} Cache */ -/** @typedef {string|string[]|false} AliasOptionNewRequest */ -/** @typedef {{[k: string]: AliasOptionNewRequest}} AliasOptions */ -/** @typedef {{[k: string]: string|string[] }} ExtensionAliasOptions */ -/** @typedef {{apply: function(Resolver): void} | function(this: Resolver, Resolver): void} Plugin */ +/** @typedef {string | string[] | false} AliasOptionNewRequest */ +/** @typedef {{ [k: string]: AliasOptionNewRequest }} AliasOptions */ +/** @typedef {string | URL | (string | URL)[] | false} UserAliasOptionNewRequest */ +/** @typedef {{ [k: string]: UserAliasOptionNewRequest }} UserAliasOptions */ +/** @typedef {{ alias: UserAliasOptionNewRequest, name: string, onlyModule?: boolean }} UserAliasOptionEntry */ +/** @typedef {{ [k: string]: string | string[] }} ExtensionAliasOptions */ +/** @typedef {false | 0 | "" | null | undefined} Falsy */ +/** @typedef {{ apply: (resolver: Resolver) => void } | ((this: Resolver, resolver: Resolver) => void) | Falsy} Plugin */ /** - * @typedef {Object} UserResolveOptions - * @property {(AliasOptions | AliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value - * @property {(AliasOptions | AliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option + * @typedef {object} TsconfigOptions + * @property {string=} configFile A relative path to the tsconfig file based on cwd, or an absolute path of tsconfig file + * @property {string[] | "auto"=} references References to other tsconfig files. 'auto' inherits from TypeScript config, or an array of relative/absolute paths + * @property {string=} baseUrl Override baseUrl from tsconfig.json. If provided, this value will be used instead of the baseUrl in the tsconfig file + */ + +/** + * @typedef {object} UserTsconfigOptions + * @property {(string | URL)=} configFile A path, or `file:` `URL` instance, pointing at the tsconfig file + * @property {((string | URL)[] | "auto")=} references References to other tsconfig files. 'auto' inherits from TypeScript config, or an array of relative/absolute paths or `file:` `URL` instances + * @property {(string | URL)=} baseUrl Override baseUrl from tsconfig.json with a path or `file:` `URL` instance + */ + +/** + * @typedef {object} UserResolveOptions + * @property {(UserAliasOptions | UserAliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value + * @property {(UserAliasOptions | UserAliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option * @property {ExtensionAliasOptions=} extensionAlias An object which maps extension to extension aliases + * @property {boolean=} extensionAliasForExports Also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default (Node.js-aligned); when enabled, matches TypeScript's behavior for packages that ship TS sources alongside compiled JS. * @property {(string | string[])[]=} aliasFields A list of alias fields in description files - * @property {(function(ResolveRequest): boolean)=} cachePredicate A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. + * @property {((predicate: ResolveRequest) => boolean)=} cachePredicate A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. * @property {boolean=} cacheWithContext Whether or not the unsafeCache should include request context as part of the cache key. * @property {string[]=} descriptionFiles A list of description files to read from * @property {string[]=} conditionNames A list of exports field condition names. @@ -16104,52 +18265,55 @@ const UseFilePlugin = __nccwpck_require__(2229); * @property {(string | string[])[]=} importsFields A list of imports fields in description files * @property {string[]=} extensions A list of extensions which should be tried for files * @property {FileSystem} fileSystem The file system which should be used - * @property {(object | boolean)=} unsafeCache Use this cache object to unsafely cache the successful requests + * @property {(Cache | boolean)=} unsafeCache Use this cache object to unsafely cache the successful requests * @property {boolean=} symlinks Resolve symlinks to their symlinked location * @property {Resolver=} resolver A prepared Resolver to which the plugins are attached - * @property {string[] | string=} modules A list of directories to resolve modules from, can be absolute path or folder name - * @property {(string | string[] | {name: string | string[], forceRelative: boolean})[]=} mainFields A list of main fields in description files - * @property {string[]=} mainFiles A list of main files in directories + * @property {(string | URL)[] | string | URL=} modules A list of directories to resolve modules from, can be absolute path, folder name, or a `file:` `URL` instance + * @property {(string | string[] | { name: string | string[], forceRelative: boolean })[]=} mainFields A list of main fields in description files + * @property {string[]=} mainFiles A list of main files in directories * @property {Plugin[]=} plugins A list of additional resolve plugins which should be applied * @property {PnpApi | null=} pnpApi A PnP API that should be used - null is "never", undefined is "auto" - * @property {string[]=} roots A list of root paths + * @property {(string | URL)[]=} roots A list of root paths, each an absolute path or a `file:` `URL` instance * @property {boolean=} fullySpecified The request is already fully specified and no extensions or directories are resolved for it * @property {boolean=} resolveToContext Resolve to a context instead of a file - * @property {(string|RegExp)[]=} restrictions A list of resolve restrictions + * @property {(string | URL | RegExp)[]=} restrictions A list of resolve restrictions, each an absolute path, a `file:` `URL` instance, or a RegExp * @property {boolean=} useSyncFileSystemCalls Use only the sync constraints of the file system calls * @property {boolean=} preferRelative Prefer to resolve module requests as relative requests before falling back to modules * @property {boolean=} preferAbsolute Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots + * @property {string | URL | boolean | UserTsconfigOptions=} tsconfig TypeScript config file path (or `file:` `URL` instance) or config object with configFile and references */ /** - * @typedef {Object} ResolveOptions - * @property {AliasOptionEntry[]} alias - * @property {AliasOptionEntry[]} fallback - * @property {Set} aliasFields - * @property {ExtensionAliasOption[]} extensionAlias - * @property {(function(ResolveRequest): boolean)} cachePredicate - * @property {boolean} cacheWithContext + * @typedef {object} ResolveOptions + * @property {AliasOptionEntry[]} alias alias + * @property {AliasOptionEntry[]} fallback fallback + * @property {Set} aliasFields alias fields + * @property {ExtensionAliasOption[]} extensionAlias extension alias + * @property {boolean} extensionAliasForExports apply extension alias to exports field targets + * @property {(predicate: ResolveRequest) => boolean} cachePredicate cache predicate + * @property {boolean} cacheWithContext cache with context * @property {Set} conditionNames A list of exports field condition names. - * @property {string[]} descriptionFiles - * @property {boolean} enforceExtension - * @property {Set} exportsFields - * @property {Set} importsFields - * @property {Set} extensions - * @property {FileSystem} fileSystem - * @property {object | false} unsafeCache - * @property {boolean} symlinks - * @property {Resolver=} resolver - * @property {Array} modules - * @property {{name: string[], forceRelative: boolean}[]} mainFields - * @property {Set} mainFiles - * @property {Plugin[]} plugins - * @property {PnpApi | null} pnpApi - * @property {Set} roots - * @property {boolean} fullySpecified - * @property {boolean} resolveToContext - * @property {Set} restrictions - * @property {boolean} preferRelative - * @property {boolean} preferAbsolute + * @property {string[]} descriptionFiles description files + * @property {boolean} enforceExtension enforce extension + * @property {Set} exportsFields exports fields + * @property {Set} importsFields imports fields + * @property {Set} extensions extensions + * @property {FileSystem} fileSystem fileSystem + * @property {Cache | false} unsafeCache unsafe cache + * @property {boolean} symlinks symlinks + * @property {Resolver=} resolver resolver + * @property {(string | string[])[]} modules modules + * @property {{ name: string[], forceRelative: boolean }[]} mainFields main fields + * @property {Set} mainFiles main files + * @property {Plugin[]} plugins plugins + * @property {PnpApi | null} pnpApi pnp API + * @property {Set} roots roots + * @property {boolean} fullySpecified fully specified + * @property {boolean} resolveToContext resolve to context + * @property {Set} restrictions restrictions + * @property {boolean} preferRelative prefer relative + * @property {boolean} preferAbsolute prefer absolute + * @property {string | boolean | TsconfigOptions} tsconfig tsconfig file path or config object */ /** @@ -16159,33 +18323,126 @@ const UseFilePlugin = __nccwpck_require__(2229); function processPnpApiOption(option) { if ( option === undefined && - /** @type {NodeJS.ProcessVersions & {pnp: string}} */ versions.pnp + /** @type {NodeJS.ProcessVersions & { pnp: string }} */ versions.pnp ) { - // @ts-ignore - return __nccwpck_require__(5125); // eslint-disable-line node/no-missing-require + const _findPnpApi = + /** @type {(issuer: string) => PnpApi | null}} */ + ( + // @ts-expect-error maybe nothing + (__nccwpck_require__(98188).findPnpApi) + ); + + if (_findPnpApi) { + return { + resolveToUnqualified(request, issuer, opts) { + const pnpapi = _findPnpApi(issuer); + + if (!pnpapi) { + // Issuer isn't managed by PnP + return null; + } + + return pnpapi.resolveToUnqualified(request, issuer, opts); + }, + }; + } } return option || null; } /** - * @param {AliasOptions | AliasOptionEntry[] | undefined} alias alias + * @param {UserAliasOptionNewRequest} alias alias target(s) + * @returns {AliasOptionNewRequest} target(s) with file `URL` instances converted to paths + */ +function toPathAlias(alias) { + if (alias === false) return false; + return Array.isArray(alias) ? alias.map(toPath) : toPath(alias); +} + +/** + * @param {UserAliasOptions | UserAliasOptionEntry[] | undefined} alias alias * @returns {AliasOptionEntry[]} normalized aliases */ function normalizeAlias(alias) { - return typeof alias === "object" && !Array.isArray(alias) && alias !== null - ? Object.keys(alias).map(key => { - /** @type {AliasOptionEntry} */ - const obj = { name: key, onlyModule: false, alias: alias[key] }; - - if (/\$$/.test(key)) { - obj.onlyModule = true; - obj.name = key.substr(0, key.length - 1); - } + if (typeof alias === "object" && !Array.isArray(alias) && alias !== null) { + return Object.keys(alias).map((key) => { + /** @type {AliasOptionEntry} */ + const obj = { + name: key, + onlyModule: false, + alias: toPathAlias(alias[key]), + }; + + if (/\$$/.test(key)) { + obj.onlyModule = true; + obj.name = key.slice(0, -1); + } + + return obj; + }); + } + + return alias + ? alias.map((item) => ({ ...item, alias: toPathAlias(item.alias) })) + : []; +} + +/** + * @param {string | URL | boolean | UserTsconfigOptions | undefined} tsconfig tsconfig option + * @returns {string | boolean | TsconfigOptions} normalized tsconfig with file `URL` instances converted to paths + */ +function normalizeTsconfig(tsconfig) { + if (tsconfig === undefined) return false; + if (typeof tsconfig === "boolean") return tsconfig; + if (typeof tsconfig === "string" || tsconfig instanceof URL) { + return toPath(tsconfig); + } + + /** @type {TsconfigOptions} */ + const result = {}; + + if (tsconfig.configFile !== undefined) { + result.configFile = toPath(tsconfig.configFile); + } + if (tsconfig.baseUrl !== undefined) { + result.baseUrl = toPath(tsconfig.baseUrl); + } + if (tsconfig.references !== undefined) { + result.references = Array.isArray(tsconfig.references) + ? tsconfig.references.map(toPath) + : tsconfig.references; + } + + return result; +} + +/** + * Merging filtered elements + * @param {string[]} array source array + * @param {(item: string) => boolean} filter predicate + * @returns {(string | string[])[]} merge result + */ +function mergeFilteredToArray(array, filter) { + /** @type {(string | string[])[]} */ + const result = []; + const set = new Set(array); + + for (const item of set) { + if (filter(item)) { + const lastElement = + result.length > 0 ? result[result.length - 1] : undefined; + if (Array.isArray(lastElement)) { + lastElement.push(item); + } else { + result.push([item]); + } + } else { + result.push(item); + } + } - return obj; - }) - : /** @type {Array} */ (alias) || []; + return result; } /** @@ -16194,23 +18451,24 @@ function normalizeAlias(alias) { */ function createOptions(options) { const mainFieldsSet = new Set(options.mainFields || ["main"]); + /** @type {ResolveOptions["mainFields"]} */ const mainFields = []; for (const item of mainFieldsSet) { if (typeof item === "string") { mainFields.push({ name: [item], - forceRelative: true + forceRelative: true, }); } else if (Array.isArray(item)) { mainFields.push({ name: item, - forceRelative: true + forceRelative: true, }); } else { mainFields.push({ name: Array.isArray(item.name) ? item.name : [item.name], - forceRelative: item.forceRelative + forceRelative: item.forceRelative, }); } } @@ -16221,7 +18479,7 @@ function createOptions(options) { aliasFields: new Set(options.aliasFields), cachePredicate: options.cachePredicate || - function () { + function trueFn() { return true; }, cacheWithContext: @@ -16231,58 +18489,61 @@ function createOptions(options) { exportsFields: new Set(options.exportsFields || ["exports"]), importsFields: new Set(options.importsFields || ["imports"]), conditionNames: new Set(options.conditionNames), - descriptionFiles: Array.from( - new Set(options.descriptionFiles || ["package.json"]) - ), + descriptionFiles: [ + ...new Set(options.descriptionFiles || ["package.json"]), + ], enforceExtension: options.enforceExtension === undefined - ? options.extensions && options.extensions.includes("") - ? true - : false + ? Boolean(options.extensions && options.extensions.includes("")) : options.enforceExtension, extensions: new Set(options.extensions || [".js", ".json", ".node"]), extensionAlias: options.extensionAlias - ? Object.keys(options.extensionAlias).map(k => ({ + ? Object.keys(options.extensionAlias).map((k) => ({ extension: k, alias: /** @type {ExtensionAliasOptions} */ (options.extensionAlias)[ k - ] - })) + ], + })) : [], + extensionAliasForExports: options.extensionAliasForExports || false, fileSystem: options.useSyncFileSystemCalls ? new SyncAsyncFileSystemDecorator( /** @type {SyncFileSystem} */ ( /** @type {unknown} */ (options.fileSystem) - ) - ) + ), + ) : options.fileSystem, unsafeCache: options.unsafeCache && typeof options.unsafeCache !== "object" - ? {} + ? /** @type {Cache} */ ({}) : options.unsafeCache || false, symlinks: typeof options.symlinks !== "undefined" ? options.symlinks : true, resolver: options.resolver, modules: mergeFilteredToArray( Array.isArray(options.modules) - ? options.modules + ? options.modules.map(toPath) : options.modules - ? [options.modules] - : ["node_modules"], - item => { + ? [toPath(options.modules)] + : ["node_modules"], + (item) => { const type = getType(item); return type === PathType.Normal || type === PathType.Relative; - } + }, ), mainFields, mainFiles: new Set(options.mainFiles || ["index"]), plugins: options.plugins || [], pnpApi: processPnpApiOption(options.pnpApi), - roots: new Set(options.roots || undefined), + roots: new Set(options.roots ? options.roots.map(toPath) : undefined), fullySpecified: options.fullySpecified || false, resolveToContext: options.resolveToContext || false, preferRelative: options.preferRelative || false, preferAbsolute: options.preferAbsolute || false, - restrictions: new Set(options.restrictions) + restrictions: new Set( + options.restrictions && + options.restrictions.map((r) => (r instanceof RegExp ? r : toPath(r))), + ), + tsconfig: normalizeTsconfig(options.tsconfig), }; } @@ -16290,13 +18551,14 @@ function createOptions(options) { * @param {UserResolveOptions} options resolve options * @returns {Resolver} created resolver */ -exports.createResolver = function (options) { +module.exports.createResolver = function createResolver(options) { const normalizedOptions = createOptions(options); const { alias, fallback, aliasFields, + extensionAliasForExports, cachePredicate, cacheWithContext, conditionNames, @@ -16320,31 +18582,37 @@ exports.createResolver = function (options) { unsafeCache, resolver: customResolver, restrictions, - roots + roots, + tsconfig, } = normalizedOptions; - const plugins = userPlugins.slice(); + const plugins = [...userPlugins]; - const resolver = customResolver - ? customResolver - : new Resolver(fileSystem, normalizedOptions); + const resolver = + customResolver || new Resolver(fileSystem, normalizedOptions); - //// pipeline //// + // // pipeline //// resolver.ensureHook("resolve"); resolver.ensureHook("internalResolve"); resolver.ensureHook("newInternalResolve"); + resolver.ensureHook("importsResolve"); resolver.ensureHook("parsedResolve"); resolver.ensureHook("describedResolve"); resolver.ensureHook("rawResolve"); resolver.ensureHook("normalResolve"); resolver.ensureHook("internal"); resolver.ensureHook("rawModule"); + resolver.ensureHook("alternateRawModule"); resolver.ensureHook("module"); resolver.ensureHook("resolveAsModule"); resolver.ensureHook("undescribedResolveInPackage"); resolver.ensureHook("resolveInPackage"); resolver.ensureHook("resolveInExistingDirectory"); + resolver.ensureHook("importsFieldRelative"); + if (extensionAliasForExports) { + resolver.ensureHook("exportsFieldRelative"); + } resolver.ensureHook("relative"); resolver.ensureHook("describedRelative"); resolver.ensureHook("directory"); @@ -16360,29 +18628,24 @@ exports.createResolver = function (options) { // TODO remove in next major // cspell:word Interal // Backward-compat + // @ts-expect-error resolver.hooks.newInteralResolve = resolver.hooks.newInternalResolve; // resolve for (const { source, resolveOptions } of [ { source: "resolve", resolveOptions: { fullySpecified } }, - { source: "internal-resolve", resolveOptions: { fullySpecified: false } } + { source: "internal-resolve", resolveOptions: { fullySpecified: false } }, + // Entry point for non-relative targets from the imports field. + // Sets internal: false to prevent re-entering imports resolution, + // aligning with the Node.js ESM spec where PACKAGE_IMPORTS_RESOLVE + // does not recursively resolve # specifiers. + // https://nodejs.org/api/esm.html#resolution-algorithm-specification + { + source: "imports-resolve", + resolveOptions: { fullySpecified: false, internal: false }, + }, ]) { - if (unsafeCache) { - plugins.push( - new UnsafeCachePlugin( - source, - cachePredicate, - unsafeCache, - cacheWithContext, - `new-${source}` - ) - ); - plugins.push( - new ParsePlugin(`new-${source}`, resolveOptions, "parsed-resolve") - ); - } else { - plugins.push(new ParsePlugin(source, resolveOptions, "parsed-resolve")); - } + plugins.push(new ParsePlugin(source, resolveOptions, "parsed-resolve")); } // parsed-resolve @@ -16391,31 +18654,45 @@ exports.createResolver = function (options) { "parsed-resolve", descriptionFiles, false, - "described-resolve" - ) + "described-resolve", + ), ); plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve")); // described-resolve - plugins.push(new NextPlugin("described-resolve", "raw-resolve")); + if (unsafeCache) { + plugins.push( + new UnsafeCachePlugin( + "described-resolve", + cachePredicate, + /** @type {import("./UnsafeCachePlugin").Cache} */ (unsafeCache), + cacheWithContext, + "raw-resolve", + ), + ); + } else { + plugins.push(new NextPlugin("described-resolve", "raw-resolve")); + } if (fallback.length > 0) { plugins.push( - new AliasPlugin("described-resolve", fallback, "internal-resolve") + new AliasPlugin("described-resolve", fallback, "internal-resolve"), ); } - // raw-resolve if (alias.length > 0) { plugins.push(new AliasPlugin("raw-resolve", alias, "internal-resolve")); } - aliasFields.forEach(item => { + if (tsconfig) { + plugins.push(new TsconfigPathsPlugin(tsconfig)); + } + for (const item of aliasFields) { plugins.push(new AliasFieldPlugin("raw-resolve", item, "internal-resolve")); - }); - extensionAlias.forEach(item => + } + for (const item of extensionAlias) { plugins.push( - new ExtensionAliasPlugin("raw-resolve", item, "normal-resolve") - ) - ); + new ExtensionAliasPlugin("raw-resolve", item, "normal-resolve"), + ); + } plugins.push(new NextPlugin("raw-resolve", "normal-resolve")); // normal-resolve @@ -16428,8 +18705,8 @@ exports.createResolver = function (options) { { module: true }, "resolve as module", false, - "raw-module" - ) + "raw-module", + ), ); plugins.push( new ConditionalPlugin( @@ -16437,8 +18714,8 @@ exports.createResolver = function (options) { { internal: true }, "resolve as internal import", false, - "internal" - ) + "internal", + ), ); if (preferAbsolute) { plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); @@ -16451,50 +18728,75 @@ exports.createResolver = function (options) { } // internal - importsFields.forEach(importsField => { + for (const importsField of importsFields) { plugins.push( new ImportsFieldPlugin( "internal", conditionNames, importsField, - "relative", - "internal-resolve" - ) + "imports-field-relative", + "imports-resolve", + ), ); - }); + } + // imports-field-relative: apply extensionAlias to paths produced by the + // imports field (TypeScript-style extension substitution for self-package + // imports like `#foo` -> `./foo.js` -> `./foo.ts`). Unlike the exports + // field, the imports field is internal to the package, so applying the + // consumer's extension aliases does not expose files the package author + // did not intend to export. See issue #413. + for (const item of extensionAlias) { + plugins.push( + new ExtensionAliasPlugin("imports-field-relative", item, "relative"), + ); + } + plugins.push(new NextPlugin("imports-field-relative", "relative")); // raw-module - exportsFields.forEach(exportsField => { + for (const exportsField of exportsFields) { plugins.push( - new SelfReferencePlugin("raw-module", exportsField, "resolve-as-module") + new SelfReferencePlugin("raw-module", exportsField, "resolve-as-module"), ); - }); - modules.forEach(item => { + } + for (const item of modules) { if (Array.isArray(item)) { if (item.includes("node_modules") && pnpApi) { plugins.push( new ModulesInHierarchicalDirectoriesPlugin( "raw-module", - item.filter(i => i !== "node_modules"), - "module" - ) + item.filter((i) => i !== "node_modules"), + "module", + ), ); plugins.push( - new PnpPlugin("raw-module", pnpApi, "undescribed-resolve-in-package") + new PnpPlugin( + "raw-module", + pnpApi, + "undescribed-resolve-in-package", + "alternate-raw-module", + ), + ); + + plugins.push( + new ModulesInHierarchicalDirectoriesPlugin( + "alternate-raw-module", + ["node_modules"], + "module", + ), ); } else { plugins.push( new ModulesInHierarchicalDirectoriesPlugin( "raw-module", item, - "module" - ) + "module", + ), ); } } else { plugins.push(new ModulesInRootPlugin("raw-module", item, "module")); } - }); + } // module plugins.push(new JoinRequestPartPlugin("module", "resolve-as-module")); @@ -16507,15 +18809,15 @@ exports.createResolver = function (options) { { directory: false, request: "." }, "single file module", true, - "undescribed-raw-file" - ) + "undescribed-raw-file", + ), ); } plugins.push( new DirectoryExistsPlugin( "resolve-as-module", - "undescribed-resolve-in-package" - ) + "undescribed-resolve-in-package", + ), ); // undescribed-resolve-in-package @@ -16524,31 +18826,52 @@ exports.createResolver = function (options) { "undescribed-resolve-in-package", descriptionFiles, false, - "resolve-in-package" - ) + "resolve-in-package", + ), ); plugins.push( - new NextPlugin("after-undescribed-resolve-in-package", "resolve-in-package") + new NextPlugin( + "after-undescribed-resolve-in-package", + "resolve-in-package", + ), ); // resolve-in-package - exportsFields.forEach(exportsField => { + const exportsFieldTarget = extensionAliasForExports + ? "exports-field-relative" + : "relative"; + for (const exportsField of exportsFields) { plugins.push( new ExportsFieldPlugin( "resolve-in-package", conditionNames, exportsField, - "relative" - ) + exportsFieldTarget, + restrictions.size > 0, + ), ); - }); + } plugins.push( - new NextPlugin("resolve-in-package", "resolve-in-existing-directory") + new NextPlugin("resolve-in-package", "resolve-in-existing-directory"), ); + // exports-field-relative (opt-in via `extensionAliasForExports`): + // apply `extensionAlias` to paths produced by the exports field. This is + // off by default to match Node.js (which does not substitute extensions on + // bare-module targets), and on opt-in aligns with TypeScript for packages + // that ship TS sources alongside the compiled JS they list in `exports`. + if (extensionAliasForExports) { + for (const item of extensionAlias) { + plugins.push( + new ExtensionAliasPlugin("exports-field-relative", item, "relative"), + ); + } + plugins.push(new NextPlugin("exports-field-relative", "relative")); + } + // resolve-in-existing-directory plugins.push( - new JoinRequestPlugin("resolve-in-existing-directory", "relative") + new JoinRequestPlugin("resolve-in-existing-directory", "relative"), ); // relative @@ -16557,8 +18880,8 @@ exports.createResolver = function (options) { "relative", descriptionFiles, true, - "described-relative" - ) + "described-relative", + ), ); plugins.push(new NextPlugin("after-relative", "described-relative")); @@ -16572,8 +18895,8 @@ exports.createResolver = function (options) { { directory: false }, null, true, - "raw-file" - ) + "raw-file", + ), ); plugins.push( new ConditionalPlugin( @@ -16581,14 +18904,14 @@ exports.createResolver = function (options) { { fullySpecified: false }, "as directory", true, - "directory" - ) + "directory", + ), ); } // directory plugins.push( - new DirectoryExistsPlugin("directory", "undescribed-existing-directory") + new DirectoryExistsPlugin("directory", "undescribed-existing-directory"), ); if (resolveToContext) { @@ -16601,34 +18924,34 @@ exports.createResolver = function (options) { "undescribed-existing-directory", descriptionFiles, false, - "existing-directory" - ) + "existing-directory", + ), ); - mainFiles.forEach(item => { + for (const item of mainFiles) { plugins.push( new UseFilePlugin( "undescribed-existing-directory", item, - "undescribed-raw-file" - ) + "undescribed-raw-file", + ), ); - }); + } // described-existing-directory - mainFields.forEach(item => { + for (const item of mainFields) { plugins.push( new MainFieldPlugin( "existing-directory", item, - "resolve-in-existing-directory" - ) + "resolve-in-existing-directory", + ), ); - }); - mainFiles.forEach(item => { + } + for (const item of mainFiles) { plugins.push( - new UseFilePlugin("existing-directory", item, "undescribed-raw-file") + new UseFilePlugin("existing-directory", item, "undescribed-raw-file"), ); - }); + } // undescribed-raw-file plugins.push( @@ -16636,8 +18959,8 @@ exports.createResolver = function (options) { "undescribed-raw-file", descriptionFiles, true, - "raw-file" - ) + "raw-file", + ), ); plugins.push(new NextPlugin("after-undescribed-raw-file", "raw-file")); @@ -16648,45 +18971,53 @@ exports.createResolver = function (options) { { fullySpecified: true }, null, false, - "file" - ) + "file", + ), ); if (!enforceExtension) { plugins.push(new TryNextPlugin("raw-file", "no extension", "file")); } - extensions.forEach(item => { + for (const item of extensions) { plugins.push(new AppendPlugin("raw-file", item, "file")); - }); + } // file - if (alias.length > 0) + if (alias.length > 0) { plugins.push(new AliasPlugin("file", alias, "internal-resolve")); - aliasFields.forEach(item => { + } + for (const item of aliasFields) { plugins.push(new AliasFieldPlugin("file", item, "internal-resolve")); - }); + } plugins.push(new NextPlugin("file", "final-file")); // final-file plugins.push(new FileExistsPlugin("final-file", "existing-file")); // existing-file - if (symlinks) + if (symlinks) { plugins.push(new SymlinkPlugin("existing-file", "existing-file")); + } plugins.push(new NextPlugin("existing-file", "resolved")); } + const { resolved } = + /** @type {KnownHooks & EnsuredHooks} */ + (resolver.hooks); + // resolved if (restrictions.size > 0) { - plugins.push(new RestrictionsPlugin(resolver.hooks.resolved, restrictions)); + plugins.push(new RestrictionsPlugin(resolved, restrictions)); } - plugins.push(new ResultPlugin(resolver.hooks.resolved)); - //// RESOLVER //// + plugins.push(new ResultPlugin(resolved)); + + // // RESOLVER //// for (const plugin of plugins) { if (typeof plugin === "function") { - plugin.call(resolver, resolver); - } else { + /** @type {(this: Resolver, resolver: Resolver) => void} */ + (plugin).call(resolver, resolver); + } else if (plugin) { plugin.apply(resolver); } } @@ -16694,34 +19025,6 @@ exports.createResolver = function (options) { return resolver; }; -/** - * Merging filtered elements - * @param {string[]} array source array - * @param {function(string): boolean} filter predicate - * @returns {Array} merge result - */ -function mergeFilteredToArray(array, filter) { - /** @type {Array} */ - const result = []; - const set = new Set(array); - - for (const item of set) { - if (filter(item)) { - const lastElement = - result.length > 0 ? result[result.length - 1] : undefined; - if (Array.isArray(lastElement)) { - lastElement.push(item); - } else { - result.push([item]); - } - } else { - result.push(item); - } - } - - return result; -} - /***/ }), @@ -16742,6 +19045,11 @@ function mergeFilteredToArray(array, filter) { const slashCode = "/".charCodeAt(0); const backslashCode = "\\".charCodeAt(0); +/** + * @param {string} path path + * @param {string} parent parent path + * @returns {boolean} true, if path is inside of parent + */ const isInside = (path, parent) => { if (!path.startsWith(parent)) return false; if (path.length === parent.length) return true; @@ -16768,23 +19076,31 @@ module.exports = class RestrictionsPlugin { .getHook(this.source) .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => { if (typeof request.path === "string") { - const path = request.path; + const { path } = request; for (const rule of this.restrictions) { if (typeof rule === "string") { if (!isInside(path, rule)) { if (resolveContext.log) { resolveContext.log( - `${path} is not inside of the restriction ${rule}` + `${path} is not inside of the restriction ${rule}`, ); } + // Target existed (FileExistsPlugin already passed) but is + // outside the jail; signal ExportsFieldPlugin to fall back. + if (request.__restrictionsMarker) { + request.__restrictionsMarker.blocked = true; + } return callback(null, null); } } else if (!rule.test(path)) { if (resolveContext.log) { resolveContext.log( - `${path} doesn't match the restriction ${rule}` + `${path} doesn't match the restriction ${rule}`, ); } + if (request.__restrictionsMarker) { + request.__restrictionsMarker.blocked = true; + } return callback(null, null); } } @@ -16798,7 +19114,7 @@ module.exports = class RestrictionsPlugin { /***/ }), -/***/ 7534: +/***/ 53254: /***/ ((module) => { "use strict"; @@ -16829,9 +19145,10 @@ module.exports = class ResultPlugin { "ResultPlugin", (request, resolverContext, callback) => { const obj = { ...request }; - if (resolverContext.log) - resolverContext.log("reporting result " + obj.path); - resolver.hooks.result.callAsync(obj, resolverContext, err => { + if (resolverContext.log) { + resolverContext.log(`reporting result ${obj.path}`); + } + resolver.hooks.result.callAsync(obj, resolverContext, (err) => { if (err) return callback(err); if (typeof resolverContext.yield === "function") { resolverContext.yield(obj); @@ -16840,7 +19157,7 @@ module.exports = class ResultPlugin { callback(null, obj); } }); - } + }, ); } }; @@ -16848,7 +19165,7 @@ module.exports = class ResultPlugin { /***/ }), -/***/ 6836: +/***/ 36836: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -16859,9 +19176,10 @@ module.exports = class ResultPlugin { -const forEachBail = __nccwpck_require__(4833); +const forEachBail = __nccwpck_require__(34833); /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ class RootsPlugin { @@ -16871,7 +19189,7 @@ class RootsPlugin { * @param {string | ResolveStepHook} target target hook */ constructor(source, roots, target) { - this.roots = Array.from(roots); + this.roots = [...roots]; this.source = source; this.target = target; } @@ -16892,22 +19210,28 @@ class RootsPlugin { forEachBail( this.roots, + /** + * @param {string} root root + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @returns {void} + */ (root, callback) => { const path = resolver.join(root, req.slice(1)); + /** @type {ResolveRequest} */ const obj = { ...request, path, - relativePath: request.relativePath && path + relativePath: request.relativePath && path, }; resolver.doResolve( target, obj, `root path ${root}`, resolveContext, - callback + callback, ); }, - callback + callback, ); }); } @@ -16918,7 +19242,7 @@ module.exports = RootsPlugin; /***/ }), -/***/ 2148: +/***/ 53600: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -16929,13 +19253,19 @@ module.exports = RootsPlugin; -const DescriptionFileUtils = __nccwpck_require__(5387); +const DescriptionFileUtils = __nccwpck_require__(15387); /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ const slashCode = "/".charCodeAt(0); +// Sentinel stored in `_nameCache` when the description file either has no +// exports field (so self-reference can't apply) or no string `name`. +const NO_SELF_REF = Symbol("NoSelfRef"); + module.exports = class SelfReferencePlugin { /** * @param {string | ResolveStepHook} source source @@ -16946,6 +19276,13 @@ module.exports = class SelfReferencePlugin { this.source = source; this.target = target; this.fieldName = fieldNamePath; + // Self-reference needs both an exports field and a `"name"` string. + // Both are stable per description-file content, so cache the decision + // in one WeakMap: the resolved name when self-reference is possible, + // or `NO_SELF_REF` when it isn't. This skips the two per-resolve + // `DescriptionFileUtils.getField` walks for hot packages. + /** @type {WeakMap} */ + this._nameCache = new WeakMap(); } /** @@ -16957,23 +19294,36 @@ module.exports = class SelfReferencePlugin { resolver .getHook(this.source) .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => { - if (!request.descriptionFilePath) return callback(); + if (!request.descriptionFileData) return callback(); const req = request.request; if (!req) return callback(); - // Feature is only enabled when an exports field is present - const exportsField = DescriptionFileUtils.getField( - request.descriptionFileData, - this.fieldName - ); - if (!exportsField) return callback(); - - const name = DescriptionFileUtils.getField( - request.descriptionFileData, - "name" - ); - if (typeof name !== "string") return callback(); + const { descriptionFileData } = request; + let name = this._nameCache.get(descriptionFileData); + if (name === undefined) { + // Feature is only enabled when an exports field is present + const exportsField = DescriptionFileUtils.getField( + descriptionFileData, + this.fieldName, + ); + if (!exportsField) { + this._nameCache.set(descriptionFileData, NO_SELF_REF); + return callback(); + } + const rawName = DescriptionFileUtils.getField( + descriptionFileData, + "name", + ); + if (typeof rawName !== "string") { + this._nameCache.set(descriptionFileData, NO_SELF_REF); + return callback(); + } + name = rawName; + this._nameCache.set(descriptionFileData, name); + } else if (name === NO_SELF_REF) { + return callback(); + } if ( req.startsWith(name) && @@ -16981,12 +19331,12 @@ module.exports = class SelfReferencePlugin { req.charCodeAt(name.length) === slashCode) ) { const remainingRequest = `.${req.slice(name.length)}`; - + /** @type {ResolveRequest} */ const obj = { ...request, request: remainingRequest, path: /** @type {string} */ (request.descriptionFileRoot), - relativePath: "." + relativePath: ".", }; resolver.doResolve( @@ -16994,7 +19344,7 @@ module.exports = class SelfReferencePlugin { obj, "self reference", resolveContext, - callback + callback, ); } else { return callback(); @@ -17006,7 +19356,7 @@ module.exports = class SelfReferencePlugin { /***/ }), -/***/ 7138: +/***/ 67138: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -17017,11 +19367,12 @@ module.exports = class SelfReferencePlugin { -const forEachBail = __nccwpck_require__(4833); -const getPaths = __nccwpck_require__(4880); -const { getType, PathType } = __nccwpck_require__(4030); +const forEachBail = __nccwpck_require__(34833); +const { getPathsCached } = __nccwpck_require__(84880); +const { PathType, getType } = __nccwpck_require__(64030); /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ module.exports = class SymlinkPlugin { @@ -17045,21 +19396,44 @@ module.exports = class SymlinkPlugin { .getHook(this.source) .tapAsync("SymlinkPlugin", (request, resolveContext, callback) => { if (request.ignoreSymlinks) return callback(); - const pathsResult = getPaths(request.path); - const pathSegments = pathsResult.segments; - const paths = pathsResult.paths; + const pathsResult = getPathsCached( + fs, + /** @type {string} */ (request.path), + ); + const { paths, segments } = pathsResult; + // `pathsResult.segments` is shared across callers via the cache. + // The only place we need to mutate is `pathSegments[idx] = result` + // when `fs.readlink` succeeds — which is rare (the vast majority + // of paths contain no symlinks, e.g. every resolve on + // `cache-predicate`'s no-symlink fixture). Defer the copy until + // we actually see a symlink so the common no-symlink path stays + // allocation-free. + /** @type {string[] | null} */ + let pathSegments = null; let containsSymlink = false; let idx = -1; forEachBail( paths, + /** + * @param {string} path path + * @param {(err?: null | Error, result?: null | number) => void} callback callback + * @returns {void} + */ (path, callback) => { idx++; - if (resolveContext.fileDependencies) + if (resolveContext.fileDependencies) { resolveContext.fileDependencies.add(path); + } fs.readlink(path, (err, result) => { if (!err && result) { - pathSegments[idx] = result; + // First symlink seen — take our own copy now, so + // the cached `segments` array stays pristine for + // sibling resolves. + if (pathSegments === null) { + pathSegments = [...segments]; + } + pathSegments[idx] = /** @type {string} */ (result); containsSymlink = true; // Shortcut when absolute symlink found const resultType = getType(result.toString()); @@ -17073,27 +19447,47 @@ module.exports = class SymlinkPlugin { callback(); }); }, + /** + * @param {null | Error=} err error + * @param {null | number=} idx result + * @returns {void} + */ (err, idx) => { if (!containsSymlink) return callback(); + // `containsSymlink === true` implies we took a copy in + // `pathSegments` already, so it's non-null. The copy is + // our own, so `slice` to trim is fine and spreading to + // "unshare" is no longer necessary. + const own = /** @type {string[]} */ (pathSegments); const resultSegments = - typeof idx === "number" - ? pathSegments.slice(0, idx + 1) - : pathSegments.slice(); - const result = resultSegments.reduceRight((a, b) => { - return resolver.join(a, b); - }); + typeof idx === "number" ? own.slice(0, idx + 1) : own; + const result = resultSegments.reduceRight((a, b) => + resolver.join(a, b), + ); + /** @type {ResolveRequest} */ const obj = { ...request, - path: result + path: result, }; resolver.doResolve( target, obj, - "resolved symlink to " + result, + `resolved symlink to ${result}`, resolveContext, - callback + (err, innerResult) => { + if (err) return callback(err); + // The symlink-resolved (real) path is authoritative. If + // resolving it produced a result, use it. If it did not — + // e.g. a `restrictions` rule rejected the real target — + // stop here with no result instead of letting the next + // plugin report the original in-root symlink path, which + // would leave the symlink unresolved and bypass + // `restrictions`. + if (innerResult) return callback(null, innerResult); + return callback(null, null); + }, ); - } + }, ); }); } @@ -17102,7 +19496,7 @@ module.exports = class SymlinkPlugin { /***/ }), -/***/ 4233: +/***/ 14233: /***/ ((module) => { "use strict"; @@ -17114,8 +19508,14 @@ module.exports = class SymlinkPlugin { /** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").StringCallback} StringCallback */ /** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +// eslint-disable-next-line jsdoc/reject-function-type +/** @typedef {Function} SyncOrAsyncFunction */ +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {any} ResultOfSyncOrAsyncFunction */ + /** * @param {SyncFileSystem} fs file system implementation * @constructor @@ -17125,87 +19525,244 @@ function SyncAsyncFileSystemDecorator(fs) { this.lstat = undefined; this.lstatSync = undefined; - const lstatSync = fs.lstatSync; + const { lstatSync } = fs; if (lstatSync) { - this.lstat = (arg, options, callback) => { - let result; - try { - result = lstatSync.call(fs, arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.lstatSync = (arg, options) => lstatSync.call(fs, arg, options); + this.lstat = + /** @type {FileSystem["lstat"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? lstatSync.call(fs, arg, options) + : lstatSync.call(fs, arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.lstatSync = + /** @type {SyncFileSystem["lstatSync"]} */ + ((arg, options) => lstatSync.call(fs, arg, options)); } - this.stat = (arg, options, callback) => { - let result; - try { - result = callback ? fs.statSync(arg, options) : fs.statSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.statSync = (arg, options) => fs.statSync(arg, options); + this.stat = + /** @type {FileSystem["stat"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.statSync(arg, options) + : fs.statSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } - this.readdir = (arg, options, callback) => { - let result; - try { - result = fs.readdirSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.readdirSync = (arg, options) => fs.readdirSync(arg, options); + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.statSync = + /** @type {SyncFileSystem["statSync"]} */ + ((arg, options) => fs.statSync(arg, options)); + + this.readdir = + /** @type {FileSystem["readdir"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.readdirSync( + arg, + /** @type {Exclude[1], (err: NodeJS.ErrnoException | null, files: string[]) => void>} */ + (options), + ) + : fs.readdirSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + [], + ); + } - this.readFile = (arg, options, callback) => { - let result; - try { - result = fs.readFileSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.readFileSync = (arg, options) => fs.readFileSync(arg, options); + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.readdirSync = + /** @type {SyncFileSystem["readdirSync"]} */ + ( + (arg, options) => + fs.readdirSync( + arg, + /** @type {Parameters[1]} */ (options), + ) + ); - this.readlink = (arg, options, callback) => { - let result; - try { - result = fs.readlinkSync(arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; - this.readlinkSync = (arg, options) => fs.readlinkSync(arg, options); + this.readFile = + /** @type {FileSystem["readFile"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.readFileSync(arg, options) + : fs.readFileSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.readFileSync = + /** @type {SyncFileSystem["readFileSync"]} */ + ((arg, options) => fs.readFileSync(arg, options)); + + this.readlink = + /** @type {FileSystem["readlink"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.readlinkSync( + arg, + /** @type {Exclude[1], StringCallback>} */ + (options), + ) + : fs.readlinkSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.readlinkSync = + /** @type {SyncFileSystem["readlinkSync"]} */ + ( + (arg, options) => + fs.readlinkSync( + arg, + /** @type {Parameters[1]} */ ( + options + ), + ) + ); this.readJson = undefined; this.readJsonSync = undefined; - const readJsonSync = fs.readJsonSync; + const { readJsonSync } = fs; if (readJsonSync) { - this.readJson = (arg, options, callback) => { - let result; - try { - result = readJsonSync.call(fs, arg); - } catch (e) { - return (callback || options)(e); - } - (callback || options)(null, result); - }; + this.readJson = + /** @type {FileSystem["readJson"]} */ + ( + (arg, callback) => { + let result; + try { + result = readJsonSync.call(fs, arg); + } catch (err) { + return callback( + /** @type {NodeJS.ErrnoException | Error | null} */ (err), + ); + } + + callback(null, result); + } + ); + this.readJsonSync = + /** @type {SyncFileSystem["readJsonSync"]} */ + ((arg) => readJsonSync.call(fs, arg)); + } + + this.realpath = undefined; + this.realpathSync = undefined; + const { realpathSync } = fs; + if (realpathSync) { + this.realpath = + /** @type {FileSystem["realpath"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? realpathSync.call( + fs, + arg, + /** @type {Exclude>[1], StringCallback>} */ + (options), + ) + : realpathSync.call(fs, arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } - this.readJsonSync = (arg, options) => readJsonSync.call(fs, arg, options); + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.realpathSync = + /** @type {SyncFileSystem["realpathSync"]} */ + ( + (arg, options) => + realpathSync.call( + fs, + arg, + /** @type {Parameters>[1]} */ + (options), + ) + ); } } + module.exports = SyncAsyncFileSystemDecorator; /***/ }), -/***/ 2351: +/***/ 22351: /***/ ((module) => { "use strict"; @@ -17245,7 +19802,7 @@ module.exports = class TryNextPlugin { request, this.message, resolveContext, - callback + callback, ); }); } @@ -17254,8 +19811,881 @@ module.exports = class TryNextPlugin { /***/ }), -/***/ 7604: -/***/ ((module) => { +/***/ 19012: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx +*/ + + + +const { aliasResolveHandler, compileAliasOptions } = __nccwpck_require__(22943); +const { modulesResolveHandler } = __nccwpck_require__(70561); +const { readJson } = __nccwpck_require__(55524); +const { PathType: _PathType, isSubPath, normalize } = __nccwpck_require__(64030); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./AliasUtils").AliasOption} AliasOption */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").TsconfigPathsData} TsconfigPathsData */ +/** @typedef {import("./Resolver").TsconfigPathsMap} TsconfigPathsMap */ +/** @typedef {import("./ResolverFactory").TsconfigOptions} TsconfigOptions */ + +// Sentinel stored in `_contextSelectionCache` for `requestPath`s whose +// scan returned `null` ("no context matched"). Using a non-null marker +// lets the cache-hit path be a single `Map.get()` — we distinguish +// "cached null" from "not cached yet" without a second `has` lookup. +const NULL_CONTEXT = Symbol("NULL_CONTEXT"); + +/** + * Per-`TsconfigPathsMap` memoization of `_selectPathsDataForContext`. + * + * Real-world builds resolve hundreds of requests per source file (every + * import in the file), and webpack-style resolvers walk the same + * `requestPath` (= source-file directory) for each one. Without this + * cache every resolve re-scans the full `contextList` even though the + * answer is invariant for a given `(map, requestPath)` pair. + * + * The outer key is the `TsconfigPathsMap` itself — rebuilt on every + * tsconfig change — so a `WeakMap` lets the inner map be collected + * automatically once the map goes away. The inner Map is keyed by + * `requestPath` (string); a `Symbol` sentinel stands in for "no + * matching context" so `Map.get` alone distinguishes the three states + * (cached data / cached null / not cached). + * @type {WeakMap>} + */ +const _contextSelectionCache = new WeakMap(); + +/** + * @typedef {object} TsconfigCompilerOptions + * @property {string=} baseUrl Base URL for resolving paths + * @property {{ [key: string]: string[] }=} paths TypeScript paths mapping + */ + +/** + * @typedef {object} TsconfigReference + * @property {string} path Path to the referenced project + */ + +/** + * @typedef {object} Tsconfig + * @property {TsconfigCompilerOptions=} compilerOptions Compiler options + * @property {string | string[]=} extends Extended configuration paths + * @property {TsconfigReference[]=} references Project references + */ + +const DEFAULT_CONFIG_FILE = "tsconfig.json"; + +const READ_JSON_OPTIONS = { stripComments: true }; + +// Trailing `/*` or `\*` segment of a tsconfig `paths` mapping (e.g. +// `./src/*` → `./src`). Hoisted so we don't allocate a fresh regex per +// path entry on every tsconfig load — and so the same regex object can be +// reused for the matching `test` + `replace` pair below. +const WILDCARD_TAIL_RE = /[/\\]\*$/; + +/** + * @param {string} pattern Path pattern + * @returns {number} Length of the prefix + */ +function getPrefixLength(pattern) { + const prefixLength = pattern.indexOf("*"); + if (prefixLength === -1) { + return pattern.length; + } + return prefixLength; +} + +/** + * Sort path patterns. + * If a module name can be matched with multiple patterns then pattern with the longest prefix will be picked. + * @param {string[]} arr Array of path patterns + * @returns {string[]} Array of path patterns sorted by longest prefix + */ +function sortByLongestPrefix(arr) { + return [...arr].sort((a, b) => getPrefixLength(b) - getPrefixLength(a)); +} + +/** + * Merge two tsconfig objects + * @param {Tsconfig | null} base base config + * @param {Tsconfig | null} config config to merge + * @returns {Tsconfig} merged config + */ +function mergeTsconfigs(base, config) { + base = base || {}; + config = config || {}; + + return { + ...base, + ...config, + compilerOptions: { + .../** @type {TsconfigCompilerOptions} */ (base.compilerOptions), + .../** @type {TsconfigCompilerOptions} */ (config.compilerOptions), + }, + }; +} + +/** + * Substitute ${configDir} template variable in path + * @param {string} pathValue the path value + * @param {string} configDir the config directory + * @returns {string} the path with substituted template + */ +function substituteConfigDir(pathValue, configDir) { + // eslint-disable-next-line no-template-curly-in-string + if (!pathValue.includes("${configDir}")) return pathValue; + return pathValue.replace(/\$\{configDir\}/g, configDir); +} + +/** + * Convert tsconfig paths to resolver options + * @param {string} configDir Config file directory + * @param {{ [key: string]: string[] }} paths TypeScript paths mapping + * @param {Resolver} resolver resolver instance + * @param {string=} baseUrl Base URL for resolving paths (relative to configDir) + * @returns {TsconfigPathsData} the resolver options + */ +function tsconfigPathsToResolveOptions(configDir, paths, resolver, baseUrl) { + // Calculate absolute base URL + const absoluteBaseUrl = !baseUrl + ? configDir + : resolver.join(configDir, baseUrl); + + /** @type {string[]} */ + const sortedKeys = sortByLongestPrefix(Object.keys(paths)); + /** @type {AliasOption[]} */ + const alias = []; + /** @type {string[]} */ + const modules = []; + + for (const pattern of sortedKeys) { + const mappings = paths[pattern]; + // Substitute ${configDir} in path mappings + const absolutePaths = mappings.map((mapping) => { + const substituted = substituteConfigDir(mapping, configDir); + return resolver.join(absoluteBaseUrl, substituted); + }); + + if (absolutePaths.length > 0) { + if (pattern === "*") { + // Pull `dir/*` entries directly into `modules` with their + // trailing wildcard stripped, skipping anything else. The + // previous `.map(...).filter(Boolean)` form allocated two + // throwaway arrays plus a spread iterator per `*` mapping. + for (let j = 0; j < absolutePaths.length; j++) { + const dir = absolutePaths[j]; + if (WILDCARD_TAIL_RE.test(dir)) { + modules.push(dir.replace(WILDCARD_TAIL_RE, "")); + } + } + } else { + alias.push({ name: pattern, alias: absolutePaths }); + } + } + } + + if (baseUrl && absoluteBaseUrl && !modules.includes(absoluteBaseUrl)) { + modules.push(absoluteBaseUrl); + } + + return { + alias: compileAliasOptions(resolver, alias), + modules, + }; +} + +/** + * Get the base context for the current project + * @param {string} context the context + * @param {Resolver} resolver resolver instance + * @param {string=} baseUrl base URL for resolving paths + * @returns {string} the base context + */ +function getAbsoluteBaseUrl(context, resolver, baseUrl) { + return !baseUrl ? context : resolver.join(context, baseUrl); +} + +/** + * @param {TsconfigPathsData} main main paths data + * @param {string} mainContext main context + * @param {{ [baseUrl: string]: TsconfigPathsData }} refs references map + * @param {Set} fileDependencies file dependencies + * @returns {TsconfigPathsMap} the tsconfig paths map + */ +function buildTsconfigPathsMap(main, mainContext, refs, fileDependencies) { + const allContexts = /** @type {{ [context: string]: TsconfigPathsData }} */ ({ + [mainContext]: main, + ...refs, + }); + // Precompute the key list once per tsconfig load. `_selectPathsDataForContext` + // runs per resolve and otherwise would call `Object.entries(allContexts)` + // each time, allocating a fresh [key, value][] array. + const contextList = Object.keys(allContexts); + return { + main, + mainContext, + refs, + allContexts, + contextList, + fileDependencies, + }; +} + +module.exports = class TsconfigPathsPlugin { + /** + * @param {true | string | TsconfigOptions} configFileOrOptions tsconfig file path or options object + */ + constructor(configFileOrOptions) { + if ( + typeof configFileOrOptions === "object" && + configFileOrOptions !== null + ) { + // Options object format + const { configFile } = configFileOrOptions; + /** @type {boolean} */ + this.isAutoConfigFile = typeof configFile !== "string"; + /** @type {string} */ + this.configFile = this.isAutoConfigFile + ? DEFAULT_CONFIG_FILE + : /** @type {string} */ (configFile); + /** @type {string[] | "auto"} */ + if (Array.isArray(configFileOrOptions.references)) { + /** @type {TsconfigReference[] | "auto"} */ + this.references = configFileOrOptions.references.map((ref) => ({ + path: ref, + })); + } else if (configFileOrOptions.references === "auto") { + this.references = "auto"; + } else { + this.references = []; + } + /** @type {string | undefined} */ + this.baseUrl = configFileOrOptions.baseUrl; + } else { + /** @type {boolean} */ + this.isAutoConfigFile = configFileOrOptions === true; + /** @type {string} */ + this.configFile = this.isAutoConfigFile + ? DEFAULT_CONFIG_FILE + : /** @type {string} */ (configFileOrOptions); + /** @type {TsconfigReference[] | "auto"} */ + this.references = []; + /** @type {string | undefined} */ + this.baseUrl = undefined; + } + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const aliasTarget = resolver.ensureHook("internal-resolve"); + const moduleTarget = resolver.ensureHook("module"); + + resolver + .getHook("raw-resolve") + .tapAsync("TsconfigPathsPlugin", (request, resolveContext, callback) => { + this._getTsconfigPathsMap( + resolver, + request, + resolveContext, + (err, tsconfigPathsMap) => { + if (err) return callback(err); + if (!tsconfigPathsMap) return callback(); + + const selectedData = this._selectPathsDataForContext( + request.path, + tsconfigPathsMap, + ); + + if (!selectedData) return callback(); + + aliasResolveHandler( + resolver, + selectedData.alias, + aliasTarget, + request, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // https://github.com/webpack/webpack/issues/20944 + // Unlike resolve.alias, tsconfig paths should fall through + // when a pattern matches but the mapped path does not exist + // (matching TypeScript's native resolution behavior). + return callback(); + }, + ); + }, + ); + }); + + resolver + .getHook("raw-module") + .tapAsync("TsconfigPathsPlugin", (request, resolveContext, callback) => { + this._getTsconfigPathsMap( + resolver, + request, + resolveContext, + (err, tsconfigPathsMap) => { + if (err) return callback(err); + if (!tsconfigPathsMap) return callback(); + + const selectedData = this._selectPathsDataForContext( + request.path, + tsconfigPathsMap, + ); + + if (!selectedData) return callback(); + + modulesResolveHandler( + resolver, + selectedData.modules, + moduleTarget, + request, + resolveContext, + callback, + ); + }, + ); + }); + } + + /** + * Get TsconfigPathsMap for the request (with caching) + * @param {Resolver} resolver the resolver + * @param {ResolveRequest} request the request + * @param {ResolveContext} resolveContext the resolve context + * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback + * @returns {void} + */ + _getTsconfigPathsMap(resolver, request, resolveContext, callback) { + if (typeof request.tsconfigPathsMap !== "undefined") { + const cached = request.tsconfigPathsMap; + if (!cached) return callback(null, null); + if (resolveContext.fileDependencies) { + for (const fileDependency of cached.fileDependencies) { + resolveContext.fileDependencies.add(fileDependency); + } + } + return callback(null, cached); + } + + if (this.isAutoConfigFile) { + this._findTsconfigUpward( + resolver, + request.path || process.cwd(), + (err, result) => { + if (err) { + request.tsconfigPathsMap = null; + return callback(err); + } + if (!result) { + request.tsconfigPathsMap = null; + return callback(null, null); + } + const map = /** @type {TsconfigPathsMap} */ (result); + request.tsconfigPathsMap = map; + if (resolveContext.fileDependencies) { + for (const fileDependency of map.fileDependencies) { + resolveContext.fileDependencies.add(fileDependency); + } + } + callback(null, map); + }, + ); + return; + } + + const absTsconfigPath = resolver.join( + request.path || process.cwd(), + this.configFile, + ); + this._loadTsconfigPathsMap(resolver, absTsconfigPath, (err, result) => { + if (err) { + request.tsconfigPathsMap = null; + return callback(err); + } + + const map = /** @type {TsconfigPathsMap} */ (result); + request.tsconfigPathsMap = map; + if (resolveContext.fileDependencies) { + for (const fileDependency of map.fileDependencies) { + resolveContext.fileDependencies.add(fileDependency); + } + } + callback(null, map); + }); + } + + /** + * Walk up from startDir to the filesystem root looking for tsconfig.json. + * Like TypeScript's own `findConfigFile` / `forEachAncestorDirectory`. + * @param {Resolver} resolver the resolver + * @param {string} startDir the directory to start searching from + * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback + * @returns {void} + */ + _findTsconfigUpward(resolver, startDir, callback) { + const { fileSystem } = resolver; + const configFileName = this.configFile; + + /** + * @param {string} dir current directory + */ + const check = (dir) => { + const candidate = resolver.join(dir, configFileName); + fileSystem.stat(candidate, (statErr) => { + if (!statErr) { + // Found — load it + this._loadTsconfigPathsMap(resolver, candidate, (loadErr, result) => { + if (loadErr) return callback(loadErr); + callback(null, result); + }); + return; + } + // Not found — move to parent + const parentDir = resolver.dirname(dir); + if (parentDir === dir) { + // Reached filesystem root, no tsconfig.json found + return callback(null, null); + } + check(parentDir); + }); + }; + + check(startDir); + } + + /** + * Load tsconfig.json and build complete TsconfigPathsMap + * Includes main project paths and all referenced projects + * @param {Resolver} resolver the resolver + * @param {string} absTsconfigPath absolute path to tsconfig.json + * @param {(err: Error | null, result?: TsconfigPathsMap) => void} callback the callback + * @returns {void} + */ + _loadTsconfigPathsMap(resolver, absTsconfigPath, callback) { + /** @type {Set} */ + const fileDependencies = new Set(); + + this._loadTsconfig( + resolver, + absTsconfigPath, + fileDependencies, + undefined, + (err, config) => { + if (err) return callback(err); + + const cfg = /** @type {Tsconfig} */ (config); + const compilerOptions = cfg.compilerOptions || {}; + const mainContext = resolver.dirname(absTsconfigPath); + + const baseUrl = + this.baseUrl !== undefined ? this.baseUrl : compilerOptions.baseUrl; + + const main = tsconfigPathsToResolveOptions( + mainContext, + compilerOptions.paths || {}, + resolver, + baseUrl, + ); + /** @type {{ [baseUrl: string]: TsconfigPathsData }} */ + const refs = {}; + + let referencesToUse = null; + if (this.references === "auto") { + referencesToUse = cfg.references; + } else if (Array.isArray(this.references)) { + referencesToUse = this.references; + } + + if (!Array.isArray(referencesToUse)) { + return callback( + null, + buildTsconfigPathsMap(main, mainContext, refs, fileDependencies), + ); + } + + this._loadTsconfigReferences( + resolver, + mainContext, + referencesToUse, + fileDependencies, + refs, + (refErr) => { + if (refErr) return callback(refErr); + callback( + null, + buildTsconfigPathsMap(main, mainContext, refs, fileDependencies), + ); + }, + ); + }, + ); + } + + /** + * Select the correct TsconfigPathsData based on request.path (context-aware) + * Matches the behavior of tsconfig-paths-webpack-plugin + * @param {string | false} requestPath the request path + * @param {TsconfigPathsMap} tsconfigPathsMap the tsconfig paths map + * @returns {TsconfigPathsData | null} the selected paths data + */ + _selectPathsDataForContext(requestPath, tsconfigPathsMap) { + const { main, allContexts, contextList } = tsconfigPathsMap; + if (!requestPath) { + return main; + } + // Single-context tsconfigs (no project references) hit the loop + // below at most once; in that case the cache lookup costs more + // than the loop itself. Only memoize when there are 2+ contexts + // — that's the monorepo / project-references shape where the + // scan actually walks multiple entries per resolve and the + // `(map, requestPath)` answer can be reused. + /** @type {Map | undefined} */ + let perMap; + if (contextList.length >= 2) { + perMap = _contextSelectionCache.get(tsconfigPathsMap); + if (perMap !== undefined) { + const cached = perMap.get(requestPath); + if (cached !== undefined) { + return cached === NULL_CONTEXT + ? null + : /** @type {TsconfigPathsData} */ (cached); + } + } else { + perMap = new Map(); + _contextSelectionCache.set(tsconfigPathsMap, perMap); + } + } + let longestMatchContext = null; + let longestMatchLength = 0; + // Iterate the pre-computed key list (the previous + // `Object.entries(allContexts)` form allocated a fresh + // `[key, value][]` per resolve). Defer the `allContexts[context]` + // lookup to after we know the context actually matches — non-matches + // are the common case and don't need the property access. + for (let i = 0; i < contextList.length; i++) { + const context = contextList[i]; + if (context === requestPath) { + const exact = allContexts[context]; + if (perMap !== undefined) perMap.set(requestPath, exact); + return exact; + } + // Cheap integer-compare gate first: a context can only beat the + // current longest match if its own length is strictly greater. + // Skipping `isSubPath` (a `startsWith` + char-code probe) when the + // length already disqualifies the candidate avoids the per-resolve + // scan over every shorter context. + if ( + context.length > longestMatchLength && + isSubPath(context, requestPath) + ) { + longestMatchContext = context; + longestMatchLength = context.length; + } + } + const result = + longestMatchContext === null ? null : allContexts[longestMatchContext]; + if (perMap !== undefined) { + perMap.set(requestPath, result === null ? NULL_CONTEXT : result); + } + return result; + } + + /** + * Load tsconfig from extends path + * @param {Resolver} resolver the resolver + * @param {string} configFilePath current config file path + * @param {string} extendedConfigValue extends value + * @param {Set} fileDependencies the file dependencies + * @param {Set} visitedConfigPaths config paths being loaded (for circular extends detection) + * @param {(err: Error | null, result?: Tsconfig) => void} callback callback + * @returns {void} + */ + _loadTsconfigFromExtends( + resolver, + configFilePath, + extendedConfigValue, + fileDependencies, + visitedConfigPaths, + callback, + ) { + const { fileSystem } = resolver; + const currentDir = resolver.dirname(configFilePath); + + // Substitute ${configDir} in extends path + extendedConfigValue = substituteConfigDir(extendedConfigValue, currentDir); + + // Remember the original value before potentially appending .json + const originalExtendedConfigValue = extendedConfigValue; + + if ( + typeof extendedConfigValue === "string" && + !extendedConfigValue.includes(".json") + ) { + extendedConfigValue += ".json"; + } + + const initialExtendedConfigPath = resolver.join( + currentDir, + extendedConfigValue, + ); + + fileSystem.stat(initialExtendedConfigPath, (existsErr) => { + let extendedConfigPath = initialExtendedConfigPath; + if (existsErr) { + // Handle scoped package extends like "@scope/name" (no sub-path): + // "@scope/name" should resolve to node_modules/@scope/name/tsconfig.json, + // not node_modules/@scope/name.json + // See: test/fixtures/tsconfig-paths/extends-pkg-entry/ + if ( + typeof originalExtendedConfigValue === "string" && + originalExtendedConfigValue.startsWith("@") && + originalExtendedConfigValue.split("/").length === 2 + ) { + extendedConfigPath = resolver.join( + currentDir, + normalize( + `node_modules/${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`, + ), + ); + } else if (extendedConfigValue.includes("/")) { + // Handle package sub-path extends like "react/tsconfig": + // "react/tsconfig" resolves to node_modules/react/tsconfig.json + // See: test/fixtures/tsconfig-paths/extends-npm/ + extendedConfigPath = resolver.join( + currentDir, + normalize(`node_modules/${extendedConfigValue}`), + ); + } else if ( + !originalExtendedConfigValue.startsWith(".") && + !originalExtendedConfigValue.startsWith("/") + ) { + // Handle unscoped package extends like "my-base-config" (no sub-path): + // "my-base-config" should resolve to node_modules/my-base-config/tsconfig.json + extendedConfigPath = resolver.join( + currentDir, + normalize( + `node_modules/${originalExtendedConfigValue}/${DEFAULT_CONFIG_FILE}`, + ), + ); + } + } + + this._loadTsconfig( + resolver, + extendedConfigPath, + fileDependencies, + visitedConfigPaths, + (err, config) => { + if (err) return callback(err); + + const cfg = /** @type {Tsconfig} */ (config); + const compilerOptions = cfg.compilerOptions || { + baseUrl: undefined, + }; + + if (compilerOptions.baseUrl) { + const extendedConfigDir = resolver.dirname(extendedConfigPath); + compilerOptions.baseUrl = getAbsoluteBaseUrl( + extendedConfigDir, + resolver, + compilerOptions.baseUrl, + ); + } + + delete cfg.references; + + callback(null, cfg); + }, + ); + }); + } + + /** + * Load referenced tsconfig projects and store in referenceMatchMap + * Simple implementation matching tsconfig-paths-webpack-plugin: + * Just load each reference and store independently + * @param {Resolver} resolver the resolver + * @param {string} context the context + * @param {TsconfigReference[]} references array of references + * @param {Set} fileDependencies the file dependencies + * @param {{ [baseUrl: string]: TsconfigPathsData }} referenceMatchMap the map to populate + * @param {(err: Error | null) => void} callback callback + * @param {Set=} visitedRefPaths visited reference config paths (for circular reference detection) + * @returns {void} + */ + _loadTsconfigReferences( + resolver, + context, + references, + fileDependencies, + referenceMatchMap, + callback, + visitedRefPaths, + ) { + if (references.length === 0) return callback(null); + + const visited = visitedRefPaths || new Set(); + let pending = references.length; + const finishOne = () => { + if (--pending === 0) callback(null); + }; + + for (const ref of references) { + const refPath = substituteConfigDir(ref.path, context); + const refConfigPath = resolver.join( + resolver.join(context, refPath), + DEFAULT_CONFIG_FILE, + ); + + if (visited.has(refConfigPath)) { + finishOne(); + continue; + } + visited.add(refConfigPath); + + this._loadTsconfig( + resolver, + refConfigPath, + fileDependencies, + undefined, + (err, refConfig) => { + // Failures are swallowed to match tsconfig-paths-webpack-plugin: + // a broken reference must not abort the main project's resolution. + if (err) return finishOne(); + + const cfg = /** @type {Tsconfig} */ (refConfig); + if (cfg.compilerOptions && cfg.compilerOptions.paths) { + const refContext = resolver.dirname(refConfigPath); + + referenceMatchMap[refContext] = tsconfigPathsToResolveOptions( + refContext, + cfg.compilerOptions.paths || {}, + resolver, + cfg.compilerOptions.baseUrl, + ); + } + + if (this.references === "auto" && Array.isArray(cfg.references)) { + this._loadTsconfigReferences( + resolver, + resolver.dirname(refConfigPath), + cfg.references, + fileDependencies, + referenceMatchMap, + finishOne, + visited, + ); + } else { + finishOne(); + } + }, + ); + } + } + + /** + * Load tsconfig.json with extends support + * @param {Resolver} resolver the resolver + * @param {string} configFilePath absolute path to tsconfig.json + * @param {Set} fileDependencies the file dependencies + * @param {Set | undefined} visitedConfigPaths config paths being loaded (for circular extends detection) + * @param {(err: Error | null, result?: Tsconfig) => void} callback callback + * @returns {void} + */ + _loadTsconfig( + resolver, + configFilePath, + fileDependencies, + visitedConfigPaths, + callback, + ) { + const visited = visitedConfigPaths || new Set(); + + if (visited.has(configFilePath)) { + return callback(null, /** @type {Tsconfig} */ ({})); + } + visited.add(configFilePath); + + readJson( + resolver.fileSystem, + configFilePath, + READ_JSON_OPTIONS, + (err, parsed) => { + if (err) return callback(/** @type {Error} */ (err)); + + const config = /** @type {Tsconfig} */ (parsed); + fileDependencies.add(configFilePath); + + const extendedConfig = config.extends; + if (!extendedConfig) return callback(null, config); + + if (!Array.isArray(extendedConfig)) { + this._loadTsconfigFromExtends( + resolver, + configFilePath, + extendedConfig, + fileDependencies, + visited, + (extErr, extendedTsconfig) => { + if (extErr) return callback(extErr); + callback( + null, + mergeTsconfigs( + /** @type {Tsconfig} */ (extendedTsconfig), + config, + ), + ); + }, + ); + return; + } + + /** @type {Tsconfig} */ + let base = {}; + let i = 0; + const next = () => { + if (i >= extendedConfig.length) { + return callback(null, mergeTsconfigs(base, config)); + } + this._loadTsconfigFromExtends( + resolver, + configFilePath, + extendedConfig[i++], + fileDependencies, + visited, + (extErr, extendedTsconfig) => { + if (extErr) return callback(extErr); + base = mergeTsconfigs( + base, + /** @type {Tsconfig} */ (extendedTsconfig), + ); + next(); + }, + ); + }; + next(); + }, + ); + } +}; + + +/***/ }), + +/***/ 97604: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* @@ -17265,26 +20695,110 @@ module.exports = class TryNextPlugin { +const { isRelativeRequest } = __nccwpck_require__(64030); + /** @typedef {import("./Resolver")} Resolver */ /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ -/** @typedef {{[k: string]: any}} Cache */ +/** @typedef {import("./Resolver").ResolveContextYield} ResolveContextYield */ +/** @typedef {{ [k: string]: undefined | ResolveRequest | ResolveRequest[] }} Cache */ + +/** + * @param {string} relativePath relative path from package root + * @param {string} request relative request + * @param {Resolver} resolver resolver instance + * @returns {string} normalized request with a preserved leading dot + */ +function joinRelativePreservingLeadingDot(relativePath, request, resolver) { + const normalized = resolver.join(relativePath, request); + return isRelativeRequest(normalized) ? normalized : `./${normalized}`; +} + +/** + * @param {ResolveRequest} request request + * @returns {string | false | undefined} normalized path + */ +function getCachePath(request) { + if (request.descriptionFileRoot && !request.module) { + return request.descriptionFileRoot; + } + return request.path; +} + +/** + * @param {ResolveRequest} request request + * @param {Resolver} resolver resolver instance + * @returns {string | undefined} normalized request string + */ +function getCacheRequest(request, resolver) { + const requestString = request.request; + if ( + !requestString || + !request.relativePath || + !isRelativeRequest(requestString) + ) { + return requestString; + } + return joinRelativePreservingLeadingDot( + request.relativePath, + requestString, + resolver, + ); +} + +// Cache-key separator: `\0` is safe because paths, requests, queries and +// fragments produced by `parseIdentifier` never contain a raw NUL (the +// \0-escape in identifier.js is decoded back to the original char), and the +// context, when included, is passed through `JSON.stringify`, which escapes +// any NUL to \u0000. +// const SEP = "\0"; + +/** + * Build the cache id for a request. Called on every `described-resolve` + * invocation when `unsafeCache` is on, so it's a hot path. + * + * Equivalent in meaning to the previous `JSON.stringify({ ... })` form, but + * ~3–5× faster since we avoid the object allocation and JSON serializer for + * the fields that are already plain strings. + * @param {string} type type of cache + * @param {ResolveRequest} request request + * @param {boolean} withContext cache with context? + * @param {Resolver} resolver resolver instance + * @returns {string} cache id + */ +function getCacheId(type, request, withContext, resolver) { + // TODO use it in the next major release, it is faster + // const contextPart = withContext ? JSON.stringify(request.context) : ""; + // const path = getCachePath(request); + // const cacheRequest = getCacheRequest(request, resolver); + // return ( + // type + + // SEP + + // contextPart + + // SEP + + // (path || "") + + // SEP + + // (request.query || "") + + // SEP + + // (request.fragment || "") + + // SEP + + // (cacheRequest || "") + // ); -function getCacheId(type, request, withContext) { return JSON.stringify({ type, context: withContext ? request.context : "", - path: request.path, + path: getCachePath(request), query: request.query, fragment: request.fragment, - request: request.request + request: getCacheRequest(request, resolver), }); } module.exports = class UnsafeCachePlugin { /** * @param {string | ResolveStepHook} source source - * @param {function(ResolveRequest): boolean} filterPredicate filterPredicate + * @param {(request: ResolveRequest) => boolean} filterPredicate filterPredicate * @param {Cache} cache cache * @param {boolean} withContext withContext * @param {string | ResolveStepHook} target target @@ -17306,17 +20820,28 @@ module.exports = class UnsafeCachePlugin { resolver .getHook(this.source) .tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => { - if (!this.filterPredicate(request)) return callback(); + if (!this.filterPredicate(request)) { + return resolver.doResolve( + target, + request, + null, + resolveContext, + callback, + ); + } const isYield = typeof resolveContext.yield === "function"; const cacheId = getCacheId( isYield ? "yield" : "default", request, - this.withContext + this.withContext, + resolver, ); const cacheEntry = this.cache[cacheId]; if (cacheEntry) { if (isYield) { - const yield_ = /** @type {Function} */ (resolveContext.yield); + const yield_ = + /** @type {ResolveContextYield} */ + (resolveContext.yield); if (Array.isArray(cacheEntry)) { for (const result of cacheEntry) yield_(result); } else { @@ -17324,15 +20849,18 @@ module.exports = class UnsafeCachePlugin { } return callback(null, null); } - return callback(null, cacheEntry); + return callback(null, /** @type {ResolveRequest} */ (cacheEntry)); } + /** @type {ResolveContextYield | undefined} */ let yieldFn; + /** @type {ResolveContextYield | undefined} */ let yield_; + /** @type {ResolveRequest[]} */ const yieldResult = []; if (isYield) { yieldFn = resolveContext.yield; - yield_ = result => { + yield_ = (result) => { yieldResult.push(result); }; } @@ -17346,13 +20874,16 @@ module.exports = class UnsafeCachePlugin { if (err) return callback(err); if (isYield) { if (result) yieldResult.push(result); - for (const result of yieldResult) yieldFn(result); + for (const result of yieldResult) { + /** @type {ResolveContextYield} */ + (yieldFn)(result); + } this.cache[cacheId] = yieldResult; return callback(null, null); } if (result) return callback(null, (this.cache[cacheId] = result)); callback(); - } + }, ); }); } @@ -17361,7 +20892,7 @@ module.exports = class UnsafeCachePlugin { /***/ }), -/***/ 2229: +/***/ 92229: /***/ ((module) => { "use strict"; @@ -17373,6 +20904,7 @@ module.exports = class UnsafeCachePlugin { /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ module.exports = class UseFilePlugin { @@ -17396,20 +20928,25 @@ module.exports = class UseFilePlugin { resolver .getHook(this.source) .tapAsync("UseFilePlugin", (request, resolveContext, callback) => { - const filePath = resolver.join(request.path, this.filename); + const filePath = resolver.join( + /** @type {string} */ (request.path), + this.filename, + ); + + /** @type {ResolveRequest} */ const obj = { ...request, path: filePath, relativePath: request.relativePath && - resolver.join(request.relativePath, this.filename) + resolver.join(request.relativePath, this.filename), }; resolver.doResolve( target, obj, - "using path: " + filePath, + `using path: ${filePath}`, resolveContext, - callback + callback, ); }); } @@ -17429,41 +20966,60 @@ module.exports = class UseFilePlugin { -module.exports = function createInnerContext( - options, - message, - messageOptional -) { - let messageReported = false; - let innerLog = undefined; - if (options.log) { +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ + +/** + * Build the `ResolveContext` passed into the next hook in the chain. + * + * The caller — `Resolver.doResolve` — runs on every resolve step, so we + * want to allocate as little as possible here. Previously the caller + * constructed a temporary `{ log, yield, fileDependencies, ... }` literal + * and handed it to this helper, which then copied those same fields into + * a second fresh object. That's two allocations per step for what is + * effectively a struct copy with one mutated field (`stack`) and one + * optionally-wrapped field (`log`). Taking the parent context and the + * two things we actually want to change (stack, message) as separate + * arguments lets us allocate exactly one inner context. + * @param {ResolveContext} parent parent resolve context to inherit dependency sets / yield from + * @param {ResolveContext["stack"]} stack new stack tip for the nested call + * @param {null | string} message log message prefix for this step + * @returns {ResolveContext} inner context + */ +module.exports = function createInnerContext(parent, stack, message) { + const parentLog = parent.log; + let innerLog; + if (parentLog) { if (message) { - innerLog = msg => { + let messageReported = false; + /** + * @param {string} msg message + */ + innerLog = (msg) => { if (!messageReported) { - options.log(message); + parentLog(message); messageReported = true; } - options.log(" " + msg); + parentLog(` ${msg}`); }; } else { - innerLog = options.log; + innerLog = parentLog; } } - const childContext = { + + return { log: innerLog, - yield: options.yield, - fileDependencies: options.fileDependencies, - contextDependencies: options.contextDependencies, - missingDependencies: options.missingDependencies, - stack: options.stack + yield: parent.yield, + fileDependencies: parent.fileDependencies, + contextDependencies: parent.contextDependencies, + missingDependencies: parent.missingDependencies, + stack, }; - return childContext; }; /***/ }), -/***/ 4833: +/***/ 34833: /***/ ((module) => { "use strict"; @@ -17474,19 +21030,44 @@ module.exports = function createInnerContext( +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ + +/** + * @template T + * @template Z + * @callback Iterator + * @param {T} item item + * @param {(err?: null | Error, result?: null | Z) => void} callback callback + * @param {number} i index + * @returns {void} + */ + +/** + * @template T + * @template Z + * @param {T[]} array array + * @param {Iterator} iterator iterator + * @param {(err?: null | Error, result?: null | Z, i?: number) => void} callback callback after all items are iterated + * @returns {void} + */ module.exports = function forEachBail(array, iterator, callback) { if (array.length === 0) return callback(); let i = 0; const next = () => { - let loop = undefined; - iterator(array[i++], (err, result) => { - if (err || result !== undefined || i >= array.length) { - return callback(err, result); - } - if (loop === false) while (next()); - loop = true; - }); + /** @type {boolean | undefined} */ + let loop; + iterator( + array[i++], + (err, result) => { + if (err || result !== undefined || i >= array.length) { + return callback(err, result, i); + } + if (loop === false) while (next()); + loop = true; + }, + i, + ); if (!loop) loop = false; return loop; }; @@ -17496,8 +21077,8 @@ module.exports = function forEachBail(array, iterator, callback) { /***/ }), -/***/ 9954: -/***/ ((module) => { +/***/ 39954: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* @@ -17507,31 +21088,45 @@ module.exports = function forEachBail(array, iterator, callback) { +const { isRelativeRequest } = __nccwpck_require__(64030); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ + +/** + * @param {Resolver} resolver resolver + * @param {ResolveRequest} request string + * @returns {string} inner request + */ module.exports = function getInnerRequest(resolver, request) { if ( typeof request.__innerRequest === "string" && request.__innerRequest_request === request.request && request.__innerRequest_relativePath === request.relativePath - ) + ) { return request.__innerRequest; + } + /** @type {string | undefined} */ let innerRequest; if (request.request) { innerRequest = request.request; - if (/^\.\.?(?:\/|$)/.test(innerRequest) && request.relativePath) { + if (request.relativePath && isRelativeRequest(innerRequest)) { innerRequest = resolver.join(request.relativePath, innerRequest); } } else { innerRequest = request.relativePath; } + // eslint-disable-next-line camelcase request.__innerRequest_request = request.request; + // eslint-disable-next-line camelcase request.__innerRequest_relativePath = request.relativePath; - return (request.__innerRequest = innerRequest); + return (request.__innerRequest = /** @type {string} */ (innerRequest)); }; /***/ }), -/***/ 4880: +/***/ 84880: /***/ ((module) => { "use strict"; @@ -17542,41 +21137,86 @@ module.exports = function getInnerRequest(resolver, request) { -module.exports = function getPaths(path) { +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {{ paths: string[], segments: string[] }} GetPathsResult */ + +/** + * Walk `path` from tip to root, returning every ancestor directory (plus the + * input itself) in `paths`, and each corresponding segment name in `segments`. + * + * The return value may be shared across callers via `getPathsCached` — treat + * it as read-only. Callers that need to mutate (currently only + * `SymlinkPlugin`) should `slice()` the arrays locally before writing. + * @param {string} path path + * @returns {GetPathsResult} paths and segments + */ +function getPaths(path) { if (path === "/") return { paths: ["/"], segments: [""] }; const parts = path.split(/(.*?[\\/]+)/); const paths = [path]; const segments = [parts[parts.length - 1]]; let part = parts[parts.length - 1]; - path = path.substr(0, path.length - part.length - 1); + path = path.slice(0, Math.max(0, path.length - part.length - 1)); for (let i = parts.length - 2; i > 2; i -= 2) { paths.push(path); part = parts[i]; - path = path.substr(0, path.length - part.length) || "/"; - segments.push(part.substr(0, part.length - 1)); + path = path.slice(0, Math.max(0, path.length - part.length)) || "/"; + segments.push(part.slice(0, -1)); } - part = parts[1]; + [, part] = parts; segments.push(part); paths.push(part); return { - paths: paths, - segments: segments + paths, + segments, }; -}; +} -module.exports.basename = function basename(path) { - const i = path.lastIndexOf("/"), - j = path.lastIndexOf("\\"); - const p = i < 0 ? j : j < 0 ? i : i < j ? j : i; - if (p < 0) return null; - const s = path.substr(p + 1); - return s; -}; +/** + * Per-filesystem memoization of `getPaths`. Kept in a standalone WeakMap + * rather than being hung off `resolver.pathCache` so that adding this cache + * does not change the hidden-class shape of `pathCache` — which is accessed + * on the hot path of every resolve as `resolver.pathCache.{join,dirname, + * basename}.fn(...)`. CodSpeed caught that shape change as a ~1–2% + * instruction-count regression on `cache-predicate`, so we keep pathCache + * shape-stable by owning this cache here instead. + * + * The cache lifetime is tied to the filesystem object (same invariant as + * `_pathCacheByFs` in `Resolver.js`): when the user swaps filesystems the + * entries become unreachable and get collected. + * @type {WeakMap>} + */ +const _getPathsCacheByFs = new WeakMap(); + +/** + * Memoized `getPaths`. The returned object is shared across callers — do + * not mutate the `paths` or `segments` arrays in-place; `slice()` first if + * you need a mutable copy. + * @param {FileSystem} fileSystem filesystem used as the cache namespace + * @param {string} path path + * @returns {GetPathsResult} paths and segments + */ +function getPathsCached(fileSystem, path) { + let cache = _getPathsCacheByFs.get(fileSystem); + if (cache === undefined) { + cache = new Map(); + _getPathsCacheByFs.set(fileSystem, cache); + } else { + const cached = cache.get(path); + if (cached !== undefined) return cached; + } + const result = getPaths(path); + cache.set(path, result); + return result; +} + +module.exports = getPaths; +module.exports.getPathsCached = getPathsCached; /***/ }), -/***/ 453: +/***/ 40453: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -17587,93 +21227,259 @@ module.exports.basename = function basename(path) { -const fs = __nccwpck_require__(7758); -const CachedInputFileSystem = __nccwpck_require__(8127); -const ResolverFactory = __nccwpck_require__(5429); +const memoize = __nccwpck_require__(17309); +/** @typedef {import("./CachedInputFileSystem").BaseFileSystem} BaseFileSystem */ /** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ /** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").Context} Context */ /** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").ResolveCallback} ResolveCallback */ /** @typedef {import("./Resolver").ResolveContext} ResolveContext */ /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ /** @typedef {import("./ResolverFactory").Plugin} Plugin */ /** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */ -const nodeFileSystem = new CachedInputFileSystem(fs, 4000); +/** + * @typedef {{ + * (context: Context, parent: string | URL, specifier: string | URL, resolveContext: ResolveContext, callback: ResolveCallback): void, + * (context: Context, parent: string | URL, specifier: string | URL, callback: ResolveCallback): void, + * (parent: string | URL, specifier: string | URL, resolveContext: ResolveContext, callback: ResolveCallback): void, + * (parent: string | URL, specifier: string | URL, callback: ResolveCallback): void, + * }} ResolveFunctionAsync + */ -const nodeContext = { - environments: ["node+es3+es5+process+native"] -}; +/** + * @typedef {{ + * (context: Context, parent: string | URL, specifier: string | URL, resolveContext?: ResolveContext): string | false, + * (parent: string | URL, specifier: string | URL, resolveContext?: ResolveContext): string | false, + * }} ResolveFunction + */ -const asyncResolver = ResolverFactory.createResolver({ - conditionNames: ["node"], - extensions: [".js", ".json", ".node"], - fileSystem: nodeFileSystem -}); -function resolve(context, path, request, resolveContext, callback) { - if (typeof context === "string") { - callback = resolveContext; - resolveContext = request; - request = path; - path = context; - context = nodeContext; - } - if (typeof callback !== "function") { - callback = resolveContext; - } - asyncResolver.resolve(context, path, request, resolveContext, callback); -} +/** + * @typedef {{ + * (context: Context, parent: string | URL, specifier: string | URL, resolveContext?: ResolveContext): Promise, + * (parent: string | URL, specifier: string | URL, resolveContext?: ResolveContext): Promise, + * }} ResolveFunctionPromise + */ + +const getCachedFileSystem = memoize(() => __nccwpck_require__(68127)); -const syncResolver = ResolverFactory.createResolver({ - conditionNames: ["node"], - extensions: [".js", ".json", ".node"], - useSyncFileSystemCalls: true, - fileSystem: nodeFileSystem +const getNodeFileSystem = memoize(() => { + const fs = __nccwpck_require__(77758); + + const CachedInputFileSystem = getCachedFileSystem(); + + return new CachedInputFileSystem(fs, 4000); }); -function resolveSync(context, path, request) { - if (typeof context === "string") { - request = path; - path = context; - context = nodeContext; - } - return syncResolver.resolveSync(context, path, request); -} +const getNodeContext = memoize(() => ({ + environments: ["node+es3+es5+process+native"], +})); -function create(options) { - options = { - fileSystem: nodeFileSystem, - ...options +const getResolverFactory = memoize(() => __nccwpck_require__(25429)); + +const getAsyncResolver = memoize(() => + getResolverFactory().createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + fileSystem: getNodeFileSystem(), + }), +); + +/** + * @type {ResolveFunctionAsync} + */ +const resolve = + /** + * @param {object | string | URL} context context + * @param {string | URL} parent parent path + * @param {string | URL | ResolveContext | ResolveCallback} specifier specifier to resolve + * @param {ResolveContext | ResolveCallback=} resolveContext resolve context + * @param {ResolveCallback=} callback callback + */ + (context, parent, specifier, resolveContext, callback) => { + if (typeof context === "string" || context instanceof URL) { + callback = /** @type {ResolveCallback} */ (resolveContext); + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + if (typeof callback !== "function") { + callback = /** @type {ResolveCallback} */ (resolveContext); + } + getAsyncResolver().resolve( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + /** @type {ResolveCallback} */ (callback), + ); + }; + +const getSyncResolver = memoize(() => + getResolverFactory().createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + useSyncFileSystemCalls: true, + fileSystem: getNodeFileSystem(), + }), +); + +/** + * @type {ResolveFunction} + */ +const resolveSync = + /** + * @param {object | string | URL} context context + * @param {string | URL} parent parent path + * @param {string | URL | ResolveContext | undefined} specifier specifier to resolve + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} resolved path + */ + (context, parent, specifier, resolveContext) => { + if (typeof context === "string" || context instanceof URL) { + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + return getSyncResolver().resolveSync( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + ); + }; + +/** + * @type {ResolveFunctionPromise} + */ +const resolvePromise = + /** + * @param {object | string | URL} context context + * @param {string | URL} parent parent path + * @param {string | URL | ResolveContext | undefined} specifier specifier to resolve + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} resolved path + */ + (context, parent, specifier, resolveContext) => { + if (typeof context === "string" || context instanceof URL) { + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + return getAsyncResolver().resolvePromise( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + ); }; - const resolver = ResolverFactory.createResolver(options); - return function (context, path, request, resolveContext, callback) { - if (typeof context === "string") { - callback = resolveContext; - resolveContext = request; - request = path; - path = context; - context = nodeContext; + +/** @typedef {Omit & Partial>} ResolveOptionsOptionalFS */ + +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunctionAsync} Resolver function + */ +function create(options) { + const resolver = getResolverFactory().createResolver({ + ...options, + fileSystem: options.fileSystem || getNodeFileSystem(), + }); + /** + * @param {object | string | URL} context Custom context + * @param {string | URL} parent Base/parent path + * @param {string | URL | ResolveContext | ResolveCallback} specifier Specifier to resolve + * @param {ResolveContext | ResolveCallback=} resolveContext Resolve context + * @param {ResolveCallback=} callback Result callback + */ + return function create(context, parent, specifier, resolveContext, callback) { + if (typeof context === "string" || context instanceof URL) { + callback = /** @type {ResolveCallback} */ (resolveContext); + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); } if (typeof callback !== "function") { - callback = resolveContext; + callback = /** @type {ResolveCallback} */ (resolveContext); } - resolver.resolve(context, path, request, resolveContext, callback); + resolver.resolve( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + callback, + ); }; } +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunction} Resolver function + */ function createSync(options) { - options = { + const resolver = getResolverFactory().createResolver({ useSyncFileSystemCalls: true, - fileSystem: nodeFileSystem, - ...options + ...options, + fileSystem: options.fileSystem || getNodeFileSystem(), + }); + /** + * @param {object | string | URL} context custom context + * @param {string | URL} parent base/parent path + * @param {string | URL | ResolveContext | undefined} specifier specifier to resolve + * @param {ResolveContext=} resolveContext Resolve context + * @returns {string | false} Resolved path or false + */ + return function createSync(context, parent, specifier, resolveContext) { + if (typeof context === "string" || context instanceof URL) { + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + return resolver.resolveSync( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + ); }; - const resolver = ResolverFactory.createResolver(options); - return function (context, path, request) { - if (typeof context === "string") { - request = path; - path = context; - context = nodeContext; +} + +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunctionPromise} Resolver function + */ +function createPromise(options) { + const resolver = getResolverFactory().createResolver({ + ...options, + fileSystem: options.fileSystem || getNodeFileSystem(), + }); + /** + * @param {object | string | URL} context Custom context + * @param {string | URL} parent Base/parent path + * @param {string | URL | ResolveContext | undefined} specifier Specifier to resolve + * @param {ResolveContext=} resolveContext Resolve context + * @returns {Promise} resolved path + */ + return function createPromise(context, parent, specifier, resolveContext) { + if (typeof context === "string" || context instanceof URL) { + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); } - return resolver.resolveSync(context, path, request); + return resolver.resolvePromise( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + ); }; } @@ -17694,29 +21500,42 @@ module.exports = mergeExports(resolve, { get sync() { return resolveSync; }, + get promise() { + return resolvePromise; + }, create: mergeExports(create, { get sync() { return createSync; - } + }, + get promise() { + return createPromise; + }, }), - ResolverFactory, - CachedInputFileSystem, + get ResolverFactory() { + return getResolverFactory(); + }, + get CachedInputFileSystem() { + return getCachedFileSystem(); + }, get CloneBasenamePlugin() { - return __nccwpck_require__(4086); + return __nccwpck_require__(36041); }, get LogInfoPlugin() { - return __nccwpck_require__(1656); + return __nccwpck_require__(81656); + }, + get TsconfigPathsPlugin() { + return __nccwpck_require__(19012); }, get forEachBail() { - return __nccwpck_require__(4833); - } + return __nccwpck_require__(34833); + }, }); /***/ }), -/***/ 3679: -/***/ ((module) => { +/***/ 63679: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* @@ -17726,26 +21545,20 @@ module.exports = mergeExports(resolve, { -/** @typedef {string|(string|ConditionalMapping)[]} DirectMapping */ -/** @typedef {{[k: string]: MappingValue}} ConditionalMapping */ -/** @typedef {ConditionalMapping|DirectMapping|null} MappingValue */ -/** @typedef {Record|ConditionalMapping|DirectMapping} ExportsField */ -/** @typedef {Record} ImportsField */ +const { parseIdentifier } = __nccwpck_require__(42505); -/** - * @typedef {Object} PathTreeNode - * @property {Map|null} children - * @property {MappingValue} folder - * @property {Map|null} wildcards - * @property {Map} files - */ +/** @typedef {string | (string | ConditionalMapping)[]} DirectMapping */ +/** @typedef {{ [k: string]: MappingValue }} ConditionalMapping */ +/** @typedef {ConditionalMapping | DirectMapping | null} MappingValue */ +/** @typedef {Record | ConditionalMapping | DirectMapping} ExportsField */ +/** @typedef {Record} ImportsField */ /** * Processing exports/imports field * @callback FieldProcessor * @param {string} request request * @param {Set} conditionNames condition names - * @returns {string[]} resolved paths + * @returns {[string[], string | null]} resolved paths with used field */ /* @@ -17804,310 +21617,416 @@ Conditional mapping nested in another conditional mapping is called nested mappi const slashCode = "/".charCodeAt(0); const dotCode = ".".charCodeAt(0); const hashCode = "#".charCodeAt(0); +const patternRegEx = /\*/g; +const DOLLAR_ESCAPE_RE = /\$/g; -/** - * @param {ExportsField} exportsField the exports field - * @returns {FieldProcessor} process callback - */ -module.exports.processExportsField = function processExportsField( - exportsField -) { - return createFieldProcessor( - buildExportsFieldPathTree(exportsField), - assertExportsFieldRequest, - assertExportTarget - ); -}; +/** @typedef {Record} RecordMapping */ /** - * @param {ImportsField} importsField the exports field - * @returns {FieldProcessor} process callback + * Cached `Object.keys()` for objects whose shape does not change after the + * first observation — i.e. parsed `package.json` fields and the nested + * conditional mappings inside them. `Object.keys` allocates a fresh array + * on every call; since `findMatch` / `conditionalMapping` run on every + * bare-specifier resolve, the allocation adds up quickly. + * @type {WeakMap} */ -module.exports.processImportsField = function processImportsField( - importsField -) { - return createFieldProcessor( - buildImportsFieldPathTree(importsField), - assertImportsFieldRequest, - assertImportTarget - ); -}; +const _keysCache = new WeakMap(); /** - * @param {PathTreeNode} treeRoot root - * @param {(s: string) => string} assertRequest assertRequest - * @param {(s: string, f: boolean) => void} assertTarget assertTarget - * @returns {FieldProcessor} field processor + * @param {RecordMapping} obj object to read keys from + * @returns {string[]} cached keys array (DO NOT mutate) */ -function createFieldProcessor(treeRoot, assertRequest, assertTarget) { - return function fieldProcessor(request, conditionNames) { - request = assertRequest(request); - - const match = findMatch(request, treeRoot); - - if (match === null) return []; - - const [mapping, remainRequestIndex] = match; - - /** @type {DirectMapping|null} */ - let direct = null; - - if (isConditionalMapping(mapping)) { - direct = conditionalMapping( - /** @type {ConditionalMapping} */ (mapping), - conditionNames - ); - - // matching not found - if (direct === null) return []; - } else { - direct = /** @type {DirectMapping} */ (mapping); - } - - const remainingRequest = - remainRequestIndex === request.length + 1 - ? undefined - : remainRequestIndex < 0 - ? request.slice(-remainRequestIndex - 1) - : request.slice(remainRequestIndex); - - return directMapping( - remainingRequest, - remainRequestIndex < 0, - direct, - conditionNames, - assertTarget - ); - }; +function cachedKeys(obj) { + let keys = _keysCache.get(obj); + if (keys === undefined) { + keys = Object.keys(obj); + _keysCache.set(obj, keys); + } + return keys; } /** - * @param {string} request request - * @returns {string} updated request + * Per-key precomputed info used by `findMatch`. Equivalent to what the + * previous implementation recomputed inline on every resolve. + * @typedef {object} FieldKeyInfo + * @property {string} key the original key + * @property {number} patternIndex position of the single "*" in the key, or -1 when absent + * @property {string} wildcardPrefix substring before "*" (empty when patternIndex === -1) + * @property {string} wildcardSuffix substring after "*" (empty when patternIndex === -1) + * @property {boolean} isLegacySubpath true when key is a legacy `./foo/`-style folder key with no "*" + * @property {boolean} isPattern true when key contains "*" + * @property {boolean} isSubpathMapping true when key ends with "/" + * @property {boolean} isValidPattern true when key has at most one "*" */ -function assertExportsFieldRequest(request) { - if (request.charCodeAt(0) !== dotCode) { - throw new Error('Request should be relative path and start with "."'); - } - if (request.length === 1) return ""; - if (request.charCodeAt(1) !== slashCode) { - throw new Error('Request should be relative path and start with "./"'); - } - if (request.charCodeAt(request.length - 1) === slashCode) { - throw new Error("Only requesting file allowed"); - } - return request.slice(2); -} +/** + * Cached per-field key metadata, keyed by the exports/imports field + * object. Computed lazily on first `findMatch` call and reused forever. + * Safe because `package.json` fields are immutable JSON values. + * @type {WeakMap} + */ +const _fieldKeyInfoCache = new WeakMap(); /** - * @param {string} request request - * @returns {string} updated request + * @param {ExportsField | ImportsField} field field object + * @returns {FieldKeyInfo[]} precomputed per-key info */ -function assertImportsFieldRequest(request) { - if (request.charCodeAt(0) !== hashCode) { - throw new Error('Request should start with "#"'); - } - if (request.length === 1) { - throw new Error("Request should have at least 2 characters"); - } - if (request.charCodeAt(1) === slashCode) { - throw new Error('Request should not start with "#/"'); - } - if (request.charCodeAt(request.length - 1) === slashCode) { - throw new Error("Only requesting file allowed"); +function getFieldKeyInfos(field) { + const fieldKey = /** @type {RecordMapping} */ (field); + let infos = _fieldKeyInfoCache.get(fieldKey); + if (infos !== undefined) return infos; + const keys = Object.getOwnPropertyNames(field); + infos = Array.from({ length: keys.length }); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const patternIndex = key.indexOf("*"); + // `isValidPattern` is true when the key has at most one `*`. Searching + // from `patternIndex + 1` stops as soon as a second `*` is found, so + // we avoid the full-string scan that `lastIndexOf` would do — and the + // single-star common case finishes in one pass. + const isValidPattern = + patternIndex === -1 || !key.includes("*", patternIndex + 1); + const keyLen = key.length; + const endsWithSlash = + keyLen > 0 && key.charCodeAt(keyLen - 1) === slashCode; + infos[i] = { + key, + patternIndex, + wildcardPrefix: patternIndex === -1 ? "" : key.slice(0, patternIndex), + wildcardSuffix: patternIndex === -1 ? "" : key.slice(patternIndex + 1), + isLegacySubpath: patternIndex === -1 && endsWithSlash, + isPattern: patternIndex !== -1, + isSubpathMapping: endsWithSlash, + isValidPattern, + }; } - - return request.slice(1); + _fieldKeyInfoCache.set(fieldKey, infos); + return infos; } /** - * @param {string} exp export target - * @param {boolean} expectFolder is folder expected + * @param {string} a first string + * @param {string} b second string + * @returns {number} compare result */ -function assertExportTarget(exp, expectFolder) { - if ( - exp.charCodeAt(0) === slashCode || - (exp.charCodeAt(0) === dotCode && exp.charCodeAt(1) !== slashCode) - ) { - throw new Error( - `Export should be relative path and start with "./", got ${JSON.stringify( - exp - )}.` - ); - } +function patternKeyCompare(a, b) { + const aPatternIndex = a.indexOf("*"); + const bPatternIndex = b.indexOf("*"); + const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; - const isFolder = exp.charCodeAt(exp.length - 1) === slashCode; + if (baseLenA > baseLenB) return -1; + if (baseLenB > baseLenA) return 1; + if (aPatternIndex === -1) return 1; + if (bPatternIndex === -1) return -1; + if (a.length > b.length) return -1; + if (b.length > a.length) return 1; - if (isFolder !== expectFolder) { - throw new Error( - expectFolder - ? `Expecting folder to folder mapping. ${JSON.stringify( - exp - )} should end with "/"` - : `Expecting file to file mapping. ${JSON.stringify( - exp - )} should not end with "/"` - ); - } + return 0; } +/** @typedef {[MappingValue, string, boolean, boolean, string] | null} MatchTuple */ + /** - * @param {string} imp import target - * @param {boolean} expectFolder is folder expected + * Per-field memoization of `findMatch(request, field)`. For a given field + * the result depends only on the `request` string (it does NOT depend on + * `conditionNames` — that's applied separately by `conditionalMapping`), + * so we can cache the tuple keyed by request. + * + * Typical build traffic runs the same request through the resolver + * repeatedly (same import re-resolved from different source files, module + * graph traversals that revisit a package, etc.), and every one of those + * hits walks the same key list and allocates the same tuple. Caching the + * tuple turns the second-and-onward call into a single Map lookup. + * + * Keyed on the field object via a module-level `WeakMap`, so the cache + * is freed automatically when the owning description file is GC'd. + * @type {WeakMap>} */ -function assertImportTarget(imp, expectFolder) { - const isFolder = imp.charCodeAt(imp.length - 1) === slashCode; - - if (isFolder !== expectFolder) { - throw new Error( - expectFolder - ? `Expecting folder to folder mapping. ${JSON.stringify( - imp - )} should end with "/"` - : `Expecting file to file mapping. ${JSON.stringify( - imp - )} should not end with "/"` - ); - } -} +const _findMatchCache = new WeakMap(); /** - * Trying to match request to field * @param {string} request request - * @param {PathTreeNode} treeRoot path tree root - * @returns {[MappingValue, number]|null} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings + * @param {ExportsField | ImportsField} field exports or import field + * @returns {MatchTuple} match result (uncached) */ -function findMatch(request, treeRoot) { - if (request.length === 0) { - const value = treeRoot.files.get(""); - - return value ? [value, 1] : null; - } +function computeFindMatch(request, field) { + const requestLen = request.length; + const requestEndsWithSlash = + requestLen > 0 && request.charCodeAt(requestLen - 1) === slashCode; + const requestHasStar = request.includes("*"); if ( - treeRoot.children === null && - treeRoot.folder === null && - treeRoot.wildcards === null + !requestHasStar && + !requestEndsWithSlash && + Object.prototype.hasOwnProperty.call(field, request) ) { - const value = treeRoot.files.get(request); + const target = /** @type {{ [k: string]: MappingValue }} */ (field)[ + request + ]; - return value ? [value, request.length + 1] : null; + return [target, "", false, false, request]; } - let node = treeRoot; - let lastNonSlashIndex = 0; - let slashIndex = request.indexOf("/", 0); + /** @type {string} */ + let bestMatch = ""; + /** @type {FieldKeyInfo | null} */ + let bestMatchInfo = null; + /** @type {string | undefined} */ + let bestMatchSubpath; - /** @type {[MappingValue, number]|null} */ - let lastFolderMatch = null; + const infos = getFieldKeyInfos(field); - const applyFolderMapping = () => { - const folderMapping = node.folder; - if (folderMapping) { - if (lastFolderMatch) { - lastFolderMatch[0] = folderMapping; - lastFolderMatch[1] = -lastNonSlashIndex - 1; - } else { - lastFolderMatch = [folderMapping, -lastNonSlashIndex - 1]; - } - } - }; + for (let i = 0; i < infos.length; i++) { + const info = infos[i]; + const { key, patternIndex } = info; - const applyWildcardMappings = (wildcardMappings, remainingRequest) => { - if (wildcardMappings) { - for (const [key, target] of wildcardMappings) { - if (remainingRequest.startsWith(key)) { - if (!lastFolderMatch) { - lastFolderMatch = [target, lastNonSlashIndex + key.length]; - } else if (lastFolderMatch[1] < lastNonSlashIndex + key.length) { - lastFolderMatch[0] = target; - lastFolderMatch[1] = lastNonSlashIndex + key.length; - } - } + if (patternIndex !== -1) { + if ( + !info.isValidPattern || + !request.startsWith(info.wildcardPrefix) || + requestLen < key.length || + !request.endsWith(info.wildcardSuffix) || + patternKeyCompare(bestMatch, key) !== 1 + ) { + continue; } + bestMatch = key; + bestMatchInfo = info; + bestMatchSubpath = request.slice( + patternIndex, + requestLen - info.wildcardSuffix.length, + ); + } else if ( + info.isLegacySubpath && + request.startsWith(key) && + patternKeyCompare(bestMatch, key) === 1 + ) { + bestMatch = key; + bestMatchInfo = info; + bestMatchSubpath = request.slice(key.length); } - }; + } - while (slashIndex !== -1) { - applyFolderMapping(); + if (bestMatch === "") return null; - const wildcardMappings = node.wildcards; + const target = + /** @type {{ [k: string]: MappingValue }} */ + (field)[bestMatch]; - if (!wildcardMappings && node.children === null) return lastFolderMatch; + return [ + target, + /** @type {string} */ (bestMatchSubpath), + /** @type {FieldKeyInfo} */ (bestMatchInfo).isSubpathMapping, + /** @type {FieldKeyInfo} */ (bestMatchInfo).isPattern, + bestMatch, + ]; +} - const folder = request.slice(lastNonSlashIndex, slashIndex); +/** + * Trying to match request to field + * @param {string} request request + * @param {ExportsField | ImportsField} field exports or import field + * @returns {MatchTuple} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings + */ +function findMatch(request, field) { + const fieldKey = /** @type {RecordMapping} */ (field); + let perRequest = _findMatchCache.get(fieldKey); + if (perRequest === undefined) { + perRequest = new Map(); + _findMatchCache.set(fieldKey, perRequest); + } else { + // `computeFindMatch` only ever returns `MatchTuple | null` — never + // `undefined` — and `Map.set(k, null)` then `Map.get(k)` returns + // `null`, not `undefined`. So `get(...) === undefined` already + // unambiguously means "not cached yet"; one Map lookup is enough, + // no follow-up `has` needed to disambiguate "cached null". + const cached = perRequest.get(request); + if (cached !== undefined) return cached; + } - applyWildcardMappings(wildcardMappings, folder); + const result = computeFindMatch(request, field); + perRequest.set(request, result); + return result; +} - if (node.children === null) return lastFolderMatch; +/** + * Sentinel stored in the conditional-mapping cache for inputs whose walk + * returns `null` ("no condition matched"). Using a non-null marker lets the + * cache-hit path be a single `WeakMap.get()` — we distinguish + * "cached null" from "not cached yet" without a second `has` call. + */ +const NULL_RESULT = Symbol("NULL_RESULT"); - const newNode = node.children.get(folder); +/** + * Memoization of `conditionalMapping(mapping, conditionNames)`. The result + * depends only on the mapping object (immutable — owned by a parsed + * `package.json`) and the `conditionNames` Set (owned by the resolver's + * options and stable for its lifetime), so it is safe to cache per (mapping, + * conditionNames) pair. + * + * A conditional `exports` entry that appears inside a `directMapping` array + * (the common `"browser": [...fallback list...]` shape, plus nested + * conditions) gets walked on every resolve that traverses the parent entry. + * Without this cache each of those walks re-reads `Object.keys` on the + * mapping and re-visits every condition until one matches, even though the + * inputs are identical. + * + * Outer key is the conditional mapping itself; inner key is the condition + * Set. Both are object references, so WeakMap-of-WeakMap lets both levels + * be collected automatically when the description file or resolver go away. + * @type {WeakMap, DirectMapping | typeof NULL_RESULT>>} + */ +const _conditionalMappingCache = new WeakMap(); - if (!newNode) { - return lastFolderMatch; - } +/** + * @param {ConditionalMapping} conditionalMapping_ conditional mapping + * @param {Set} conditionNames condition names + * @returns {DirectMapping | null} direct mapping if found (uncached) + */ +function computeConditionalMapping(conditionalMapping_, conditionNames) { + /** @type {[ConditionalMapping, string[], number][]} */ + const lookup = [[conditionalMapping_, cachedKeys(conditionalMapping_), 0]]; - node = newNode; - lastNonSlashIndex = slashIndex + 1; - slashIndex = request.indexOf("/", lastNonSlashIndex); - } + loop: while (lookup.length > 0) { + const top = lookup[lookup.length - 1]; + const [mapping, conditions, j] = top; - const remainingRequest = - lastNonSlashIndex > 0 ? request.slice(lastNonSlashIndex) : request; + for (let i = j; i < conditions.length; i++) { + const condition = conditions[i]; - const value = node.files.get(remainingRequest); + if (condition === "default" || conditionNames.has(condition)) { + const innerMapping = mapping[condition]; + if ( + innerMapping !== null && + typeof innerMapping === "object" && + !Array.isArray(innerMapping) + ) { + const nested = /** @type {ConditionalMapping} */ (innerMapping); + top[2] = i + 1; + lookup.push([nested, cachedKeys(nested), 0]); + continue loop; + } - if (value) { - return [value, request.length + 1]; - } + return /** @type {DirectMapping} */ (innerMapping); + } + } - applyFolderMapping(); + lookup.pop(); + } - applyWildcardMappings(node.wildcards, remainingRequest); + return null; +} - return lastFolderMatch; +/** + * @param {ConditionalMapping} conditionalMapping_ conditional mapping + * @param {Set} conditionNames condition names + * @returns {DirectMapping | null} direct mapping if found + */ +function conditionalMapping(conditionalMapping_, conditionNames) { + let perSet = _conditionalMappingCache.get(conditionalMapping_); + if (perSet !== undefined) { + const cached = perSet.get(conditionNames); + if (cached !== undefined) { + return cached === NULL_RESULT + ? null + : /** @type {DirectMapping} */ (cached); + } + } else { + perSet = new WeakMap(); + _conditionalMappingCache.set(conditionalMapping_, perSet); + } + const result = computeConditionalMapping(conditionalMapping_, conditionNames); + perSet.set(conditionNames, result === null ? NULL_RESULT : result); + return result; } /** - * @param {ConditionalMapping|DirectMapping|null} mapping mapping - * @returns {boolean} is conditional mapping + * @param {string | undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} isPattern true, if mapping is a pattern (contains "*") + * @param {boolean} isSubpathMapping true, for subpath mappings + * @param {string} mappingTarget direct export + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string} mapping result */ -function isConditionalMapping(mapping) { - return ( - mapping !== null && typeof mapping === "object" && !Array.isArray(mapping) - ); +function targetMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mappingTarget, + assert, +) { + if (remainingRequest === undefined) { + assert(mappingTarget, false); + + return mappingTarget; + } + + if (isSubpathMapping) { + assert(mappingTarget, true); + + return mappingTarget + remainingRequest; + } + + assert(mappingTarget, false); + + let result = mappingTarget; + + if (isPattern) { + const escapedRemainder = remainingRequest.includes("$") + ? remainingRequest.replace(DOLLAR_ESCAPE_RE, "$$") + : remainingRequest; + result = result.replace(patternRegEx, escapedRemainder); + } + + return result; } /** - * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings - * @param {boolean} subpathMapping true, for subpath mappings - * @param {DirectMapping|null} mappingTarget direct export + * @param {string | undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} isPattern true, if mapping is a pattern (contains "*") + * @param {boolean} isSubpathMapping true, for subpath mappings + * @param {DirectMapping | null} mappingTarget direct export * @param {Set} conditionNames condition names * @param {(d: string, f: boolean) => void} assert asserting direct value * @returns {string[]} mapping result */ function directMapping( remainingRequest, - subpathMapping, + isPattern, + isSubpathMapping, mappingTarget, conditionNames, - assert + assert, ) { if (mappingTarget === null) return []; if (typeof mappingTarget === "string") { return [ - targetMapping(remainingRequest, subpathMapping, mappingTarget, assert) + targetMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mappingTarget, + assert, + ), ]; } + /** @type {string[]} */ const targets = []; - for (const exp of mappingTarget) { + for (let i = 0, len = mappingTarget.length; i < len; i++) { + const exp = mappingTarget[i]; if (typeof exp === "string") { targets.push( - targetMapping(remainingRequest, subpathMapping, exp, assert) + targetMapping( + remainingRequest, + isPattern, + isSubpathMapping, + exp, + assert, + ), ); continue; } @@ -18116,185 +22035,101 @@ function directMapping( if (!mapping) continue; const innerExports = directMapping( remainingRequest, - subpathMapping, + isPattern, + isSubpathMapping, mapping, conditionNames, - assert + assert, ); - for (const innerExport of innerExports) { - targets.push(innerExport); + for (let j = 0, innerLen = innerExports.length; j < innerLen; j++) { + targets.push(innerExports[j]); } } return targets; } -/** - * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings - * @param {boolean} subpathMapping true, for subpath mappings - * @param {string} mappingTarget direct export - * @param {(d: string, f: boolean) => void} assert asserting direct value - * @returns {string} mapping result - */ -function targetMapping( - remainingRequest, - subpathMapping, - mappingTarget, - assert -) { - if (remainingRequest === undefined) { - assert(mappingTarget, false); - return mappingTarget; - } - if (subpathMapping) { - assert(mappingTarget, true); - return mappingTarget + remainingRequest; - } - assert(mappingTarget, false); - return mappingTarget.replace(/\*/g, remainingRequest.replace(/\$/g, "$$")); -} +/** @type {[string[], null]} */ +const EMPTY_NO_MATCH = /** @type {[string[], null]} */ ([[], null]); /** - * @param {ConditionalMapping} conditionalMapping_ conditional mapping - * @param {Set} conditionNames condition names - * @returns {DirectMapping|null} direct mapping if found + * @param {ExportsField | ImportsField} field root + * @param {(s: string) => string} normalizeRequest Normalize request, for `imports` field it adds `#`, for `exports` field it adds `.` or `./` + * @param {(s: string) => string} assertRequest assertRequest + * @param {(s: string, f: boolean) => void} assertTarget assertTarget + * @returns {FieldProcessor} field processor */ -function conditionalMapping(conditionalMapping_, conditionNames) { - /** @type {[ConditionalMapping, string[], number][]} */ - let lookup = [[conditionalMapping_, Object.keys(conditionalMapping_), 0]]; - - loop: while (lookup.length > 0) { - const [mapping, conditions, j] = lookup[lookup.length - 1]; - const last = conditions.length - 1; - - for (let i = j; i < conditions.length; i++) { - const condition = conditions[i]; - - // assert default. Could be last only - if (i !== last) { - if (condition === "default") { - throw new Error("Default condition should be last one"); - } - } else if (condition === "default") { - const innerMapping = mapping[condition]; - // is nested - if (isConditionalMapping(innerMapping)) { - const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); - lookup[lookup.length - 1][2] = i + 1; - lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); - continue loop; - } +function createFieldProcessor( + field, + normalizeRequest, + assertRequest, + assertTarget, +) { + return function fieldProcessor(request, conditionNames) { + const match = findMatch(normalizeRequest(assertRequest(request)), field); - return /** @type {DirectMapping} */ (innerMapping); - } + if (match === null) return EMPTY_NO_MATCH; - if (conditionNames.has(condition)) { - const innerMapping = mapping[condition]; - // is nested - if (isConditionalMapping(innerMapping)) { - const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping); - lookup[lookup.length - 1][2] = i + 1; - lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]); - continue loop; - } + const [mapping, remainingRequest, isSubpathMapping, isPattern, usedField] = + match; - return /** @type {DirectMapping} */ (innerMapping); - } + /** @type {DirectMapping | null} */ + let direct; + if ( + mapping !== null && + typeof mapping === "object" && + !Array.isArray(mapping) + ) { + direct = conditionalMapping( + /** @type {ConditionalMapping} */ (mapping), + conditionNames, + ); + if (direct === null) return EMPTY_NO_MATCH; + } else { + direct = /** @type {DirectMapping} */ (mapping); } - lookup.pop(); - } - - return null; -} - -/** - * Internal helper to create path tree node - * to ensure that each node gets the same hidden class - * @returns {PathTreeNode} node - */ -function createNode() { - return { - children: null, - folder: null, - wildcards: null, - files: new Map() + return [ + directMapping( + remainingRequest, + isPattern, + isSubpathMapping, + direct, + conditionNames, + assertTarget, + ), + usedField, + ]; }; } /** - * Internal helper for building path tree - * @param {PathTreeNode} root root - * @param {string} path path - * @param {MappingValue} target target + * @param {string} request request + * @returns {string} updated request */ -function walkPath(root, path, target) { - if (path.length === 0) { - root.folder = target; - return; +function assertExportsFieldRequest(request) { + if (request.charCodeAt(0) !== dotCode) { + throw new Error('Request should be relative path and start with "."'); } - - let node = root; - // Typical path tree can looks like - // root - // - files: ["a.js", "b.js"] - // - children: - // node1: - // - files: ["a.js", "b.js"] - let lastNonSlashIndex = 0; - let slashIndex = path.indexOf("/", 0); - - while (slashIndex !== -1) { - const folder = path.slice(lastNonSlashIndex, slashIndex); - let newNode; - - if (node.children === null) { - newNode = createNode(); - node.children = new Map(); - node.children.set(folder, newNode); - } else { - newNode = node.children.get(folder); - - if (!newNode) { - newNode = createNode(); - node.children.set(folder, newNode); - } - } - - node = newNode; - lastNonSlashIndex = slashIndex + 1; - slashIndex = path.indexOf("/", lastNonSlashIndex); + if (request.length === 1) return ""; + if (request.charCodeAt(1) !== slashCode) { + throw new Error('Request should be relative path and start with "./"'); } - - if (lastNonSlashIndex >= path.length) { - node.folder = target; - } else { - const file = lastNonSlashIndex > 0 ? path.slice(lastNonSlashIndex) : path; - if (file.endsWith("*")) { - if (node.wildcards === null) node.wildcards = new Map(); - node.wildcards.set(file.slice(0, -1), target); - } else { - node.files.set(file, target); - } + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); } + + return request.slice(2); } /** * @param {ExportsField} field exports field - * @returns {PathTreeNode} tree root + * @returns {ExportsField} normalized exports field */ -function buildExportsFieldPathTree(field) { - const root = createNode(); - +function buildExportsField(field) { // handle syntax sugar, if exports field is direct mapping for "." - if (typeof field === "string") { - root.files.set("", field); - - return root; - } else if (Array.isArray(field)) { - root.files.set("", field.slice()); - - return root; + if (typeof field === "string" || Array.isArray(field)) { + return { ".": field }; } const keys = Object.keys(field); @@ -18310,144 +22145,442 @@ function buildExportsFieldPathTree(field) { if (charCode === dotCode || charCode === slashCode) { throw new Error( `Exports field key should be relative path and start with "." (key: ${JSON.stringify( - key - )})` + key, + )})`, ); } i++; } - root.files.set("", field); - return root; + return { ".": field }; } throw new Error( `Exports field key should be relative path and start with "." (key: ${JSON.stringify( - key - )})` + key, + )})`, ); } if (key.length === 1) { - root.files.set("", field[key]); continue; } if (key.charCodeAt(1) !== slashCode) { throw new Error( `Exports field key should be relative path and start with "./" (key: ${JSON.stringify( - key - )})` + key, + )})`, ); } - - walkPath(root, key.slice(2), field[key]); } - return root; + return field; } /** - * @param {ImportsField} field imports field - * @returns {PathTreeNode} root + * @param {string} exp export target + * @param {boolean} expectFolder is folder expected */ -function buildImportsFieldPathTree(field) { - const root = createNode(); +function assertExportTarget(exp, expectFolder) { + const parsedIdentifier = parseIdentifier(exp); - const keys = Object.keys(field); + if (!parsedIdentifier) { + return; + } - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; + const [relativePath] = parsedIdentifier; + const isFolder = + relativePath.charCodeAt(relativePath.length - 1) === slashCode; - if (key.charCodeAt(0) !== hashCode) { - throw new Error( - `Imports field key should start with "#" (key: ${JSON.stringify(key)})` - ); - } + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + exp, + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + exp, + )} should not end with "/"`, + ); + } +} - if (key.length === 1) { - throw new Error( - `Imports field key should have at least 2 characters (key: ${JSON.stringify( - key - )})` - ); - } +/** + * @param {ExportsField} exportsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processExportsField = function processExportsField( + exportsField, +) { + return createFieldProcessor( + buildExportsField(exportsField), + (request) => (request.length === 0 ? "." : `./${request}`), + assertExportsFieldRequest, + assertExportTarget, + ); +}; - if (key.charCodeAt(1) === slashCode) { - throw new Error( - `Imports field key should not start with "#/" (key: ${JSON.stringify( - key - )})` - ); - } +/** + * @param {string} request request + * @returns {string} updated request + */ +function assertImportsFieldRequest(request) { + if (request.charCodeAt(0) !== hashCode) { + throw new Error('Request should start with "#"'); + } + if (request.length === 1) { + throw new Error("Request should have at least 2 characters"); + } + // Note: #/ patterns are now allowed per Node.js PR #60864 + // https://github.com/nodejs/node/pull/60864 + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); + } + + return request.slice(1); +} - walkPath(root, key.slice(1), field[key]); +/** + * @param {string} imp import target + * @param {boolean} expectFolder is folder expected + */ +function assertImportTarget(imp, expectFolder) { + const parsedIdentifier = parseIdentifier(imp); + + if (!parsedIdentifier) { + return; } - return root; + const [relativePath] = parsedIdentifier; + const isFolder = + relativePath.charCodeAt(relativePath.length - 1) === slashCode; + + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + imp, + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + imp, + )} should not end with "/"`, + ); + } } +/** + * @param {ImportsField} importsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processImportsField = function processImportsField( + importsField, +) { + return createFieldProcessor( + importsField, + (request) => `#${request}`, + assertImportsFieldRequest, + assertImportTarget, + ); +}; + /***/ }), -/***/ 2505: -/***/ ((module) => { +/***/ 55524: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Ivan Kopeykin @vankop + Author Natsu @xiaoxiaojx */ -const PATH_QUERY_FRAGMENT_REGEXP = /^(#?(?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; +const memoize = __nccwpck_require__(17309); +const stripJsonComments = __nccwpck_require__(73816); + +/** @typedef {import("../Resolver").FileSystem} FileSystem */ +/** @typedef {import("../Resolver").JsonObject} JsonObject */ /** - * @param {string} identifier identifier - * @returns {[string, string, string]|null} parsed identifier + * @typedef {object} ReadJsonOptions + * @property {boolean=} stripComments Whether to strip JSONC comments */ -function parseIdentifier(identifier) { - const match = PATH_QUERY_FRAGMENT_REGEXP.exec(identifier); - if (!match) return null; +/** @type {WeakMap} */ +const _stripCommentsCache = new WeakMap(); - return [ - match[1].replace(/\0(.)/g, "$1"), - match[2] ? match[2].replace(/\0(.)/g, "$1") : "", - match[3] || "" - ]; +// Only constructed for non-Buffer input: on Node the `Buffer.isBuffer` branch +// in `decodeText` handles decoding, so the global `TextDecoder` (Node 11+, +// always present in browsers/Deno/Bun) is only reached off the Buffer path. +// `ignoreBOM: true` keeps a leading BOM in the output, matching +// `Buffer.toString("utf8")` so both decode paths behave identically. +// eslint-disable-next-line n/no-unsupported-features/node-builtins +const getDecoder = memoize(() => new TextDecoder("utf-8", { ignoreBOM: true })); + +/** + * Decode a file's raw contents to text without assuming a Node runtime. A + * `Buffer` (Node) uses its fast native `toString`; any other binary input + * (`Uint8Array` from a browser/Deno/Bun file system) goes through + * `TextDecoder`, and strings are returned as-is. + * @param {string | Buffer | Uint8Array} data raw file contents + * @returns {string} decoded text + */ +const decodeText = (data) => { + if (typeof data === "string") return data; + if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) { + return data.toString("utf8"); + } + return getDecoder().decode(data); +}; + +/** + * Read and parse JSON file (supports JSONC with comments). + * Callback-based so a synchronous `fileSystem` stays synchronous all the + * way through — Promise wrapping would defer resolution by a Promise tick + * and break `resolveSync` when `tsconfig` is used together with + * `useSyncFileSystemCalls: true`. + * @param {FileSystem} fileSystem the file system + * @param {string} jsonFilePath absolute path to JSON file + * @param {ReadJsonOptions} options Options + * @param {(err: NodeJS.ErrnoException | Error | null, content?: JsonObject) => void} callback callback + * @returns {void} + */ +function readJson(fileSystem, jsonFilePath, options, callback) { + const { stripComments = false } = options; + const { readJson: fsReadJson } = fileSystem; + if (fsReadJson && !stripComments) { + fsReadJson(jsonFilePath, (err, content) => { + if (err) return callback(err); + callback(null, /** @type {JsonObject} */ (content)); + }); + return; + } + + fileSystem.readFile(jsonFilePath, (err, data) => { + if (err) return callback(err); + const buf = /** @type {Buffer | Uint8Array | string} */ (data); + + // The strip-comments cache is keyed by the file-contents object; a file + // system may hand back a plain string, which cannot be a WeakMap key, so + // only cache when the contents are an object. + const cacheable = stripComments && typeof buf === "object"; + + if (cacheable) { + const cached = _stripCommentsCache.get(buf); + if (cached !== undefined) return callback(null, cached); + } + + let result; + try { + const jsonText = decodeText(buf); + const jsonWithoutComments = stripComments + ? stripJsonComments(jsonText, { + trailingCommas: true, + whitespace: true, + }) + : jsonText; + result = JSON.parse(jsonWithoutComments); + } catch (parseErr) { + return callback(/** @type {Error} */ (parseErr)); + } + + if (cacheable) { + _stripCommentsCache.set(buf, result); + } + + callback(null, result); + }); } -module.exports.parseIdentifier = parseIdentifier; +module.exports.decodeText = decodeText; +module.exports.readJson = readJson; /***/ }), -/***/ 4030: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 42505: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Ivan Kopeykin @vankop */ -const path = __nccwpck_require__(1017); +const { fileURLToPath } = __nccwpck_require__(57310); -const CHAR_HASH = "#".charCodeAt(0); -const CHAR_SLASH = "/".charCodeAt(0); -const CHAR_BACKSLASH = "\\".charCodeAt(0); -const CHAR_A = "A".charCodeAt(0); -const CHAR_Z = "Z".charCodeAt(0); -const CHAR_LOWER_A = "a".charCodeAt(0); -const CHAR_LOWER_Z = "z".charCodeAt(0); -const CHAR_DOT = ".".charCodeAt(0); -const CHAR_COLON = ":".charCodeAt(0); +const PATH_QUERY_FRAGMENT_REGEXP = + /^(#?(?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; +const ZERO_ESCAPE_REGEXP = /\0(.)/g; +const FILE_REG_EXP = /file:/i; -const posixNormalize = path.posix.normalize; +/** + * Index past a DOS device path prefix (`\\?\…` or `\\.\…`), or 0. Kept + * out of `parseIdentifier` on purpose: inlining it back bloats the caller + * beyond the size where V8's interpreter and JIT both handle it well + * (the cause of the description-files-multi CodSpeed regression). + * @param {string} identifier identifier known to start with `\` + * @returns {number} 4 if identifier starts with a DOS device prefix, else 0 + */ +function dosPrefixEnd(identifier) { + if ( + identifier.length >= 4 && + identifier.charCodeAt(1) === 92 && + identifier.charCodeAt(3) === 92 + ) { + const c2 = identifier.charCodeAt(2); + if (c2 === 63 || c2 === 46) return 4; + } + return 0; +} + +/** + * @param {string} identifier identifier + * @returns {[string, string, string] | null} parsed identifier + */ +function parseIdentifier(identifier) { + if (!identifier) { + return null; + } + + if (FILE_REG_EXP.test(identifier)) { + identifier = fileURLToPath(identifier); + } + + const firstEscape = identifier.indexOf("\0"); + + // Handle `\0` + if (firstEscape !== -1) { + const match = PATH_QUERY_FRAGMENT_REGEXP.exec(identifier); + + if (!match) return null; + + return [ + match[1].replace(ZERO_ESCAPE_REGEXP, "$1"), + match[2] ? match[2].replace(ZERO_ESCAPE_REGEXP, "$1") : "", + match[3] || "", + ]; + } + + // Fast path for inputs that don't use \0 escaping. DOS device paths + // (`\\?\…`, `\\.\…`) embed a literal `?` / `.` that must not be read + // as a query separator; skip past the prefix when the input actually + // starts with `\`. Gate is a single char-code compare so this function + // stays inside V8's inline budget for its hot callers (resolver parse). + const scanStart = + identifier.charCodeAt(0) === 92 ? dosPrefixEnd(identifier) : 0; + const queryStart = identifier.indexOf("?", scanStart); + // Start at index 1 (or past a DOS prefix) to ignore a possible leading hash. + const fragmentStart = identifier.indexOf("#", scanStart || 1); + + if (fragmentStart < 0) { + if (queryStart < 0) { + // No fragment, no query + return [identifier, "", ""]; + } + + // Query, no fragment + return [identifier.slice(0, queryStart), identifier.slice(queryStart), ""]; + } + + if (queryStart < 0 || fragmentStart < queryStart) { + // Fragment, no query + return [ + identifier.slice(0, fragmentStart), + "", + identifier.slice(fragmentStart), + ]; + } + + // Query and fragment + return [ + identifier.slice(0, queryStart), + identifier.slice(queryStart, fragmentStart), + identifier.slice(fragmentStart), + ]; +} + +module.exports.parseIdentifier = parseIdentifier; + + +/***/ }), + +/***/ 17309: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +/** + * @template T + * @typedef {() => T} FunctionReturning + */ + +/** + * @template T + * @param {FunctionReturning} fn memorized function + * @returns {FunctionReturning} new function + */ +const memoize = (fn) => { + let cache = false; + /** @type {T | undefined} */ + let result; + return () => { + if (cache) { + return /** @type {T} */ (result); + } + + result = fn(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + /** @type {FunctionReturning | undefined} */ + (fn) = undefined; + return /** @type {T} */ (result); + }; +}; + +module.exports = memoize; + + +/***/ }), + +/***/ 64030: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + + +const path = __nccwpck_require__(71017); +const { fileURLToPath } = __nccwpck_require__(57310); + +const CHAR_HASH = "#".charCodeAt(0); +const CHAR_SLASH = "/".charCodeAt(0); +const CHAR_BACKSLASH = "\\".charCodeAt(0); +const CHAR_A = "A".charCodeAt(0); +const CHAR_Z = "Z".charCodeAt(0); +const CHAR_LOWER_A = "a".charCodeAt(0); +const CHAR_LOWER_Z = "z".charCodeAt(0); +const CHAR_DOT = ".".charCodeAt(0); +const CHAR_COLON = ":".charCodeAt(0); +const CHAR_QUESTION = "?".charCodeAt(0); + +const posixNormalize = path.posix.normalize; const winNormalize = path.win32.normalize; /** @@ -18459,20 +22592,39 @@ const PathType = Object.freeze({ Relative: 2, AbsoluteWin: 3, AbsolutePosix: 4, - Internal: 5 + Internal: 5, }); -exports.PathType = PathType; + +const deprecatedInvalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i; + +const invalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i; /** - * @param {string} p a path + * @param {string} maybePath a path known to start with `\\` + * @returns {PathType} AbsoluteWin for `\\?\…` / `\\.\…`, otherwise Normal + */ +const getDosDeviceType = (maybePath) => { + if (maybePath.length >= 4 && maybePath.charCodeAt(3) === CHAR_BACKSLASH) { + const c2 = maybePath.charCodeAt(2); + if (c2 === CHAR_QUESTION || c2 === CHAR_DOT) { + return PathType.AbsoluteWin; + } + } + return PathType.Normal; +}; + +/** + * @param {string} maybePath a path * @returns {PathType} type of path */ -const getType = p => { - switch (p.length) { +const getType = (maybePath) => { + switch (maybePath.length) { case 0: return PathType.Empty; case 1: { - const c0 = p.charCodeAt(0); + const c0 = maybePath.charCodeAt(0); switch (c0) { case CHAR_DOT: return PathType.Relative; @@ -18484,10 +22636,10 @@ const getType = p => { return PathType.Normal; } case 2: { - const c0 = p.charCodeAt(0); + const c0 = maybePath.charCodeAt(0); switch (c0) { case CHAR_DOT: { - const c1 = p.charCodeAt(1); + const c1 = maybePath.charCodeAt(1); switch (c1) { case CHAR_DOT: case CHAR_SLASH: @@ -18500,27 +22652,26 @@ const getType = p => { case CHAR_HASH: return PathType.Internal; } - const c1 = p.charCodeAt(1); - if (c1 === CHAR_COLON) { - if ( - (c0 >= CHAR_A && c0 <= CHAR_Z) || - (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z) - ) { - return PathType.AbsoluteWin; - } + const c1 = maybePath.charCodeAt(1); + if ( + c1 === CHAR_COLON && + ((c0 >= CHAR_A && c0 <= CHAR_Z) || + (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z)) + ) { + return PathType.AbsoluteWin; } return PathType.Normal; } } - const c0 = p.charCodeAt(0); + const c0 = maybePath.charCodeAt(0); switch (c0) { case CHAR_DOT: { - const c1 = p.charCodeAt(1); + const c1 = maybePath.charCodeAt(1); switch (c1) { case CHAR_SLASH: return PathType.Relative; case CHAR_DOT: { - const c2 = p.charCodeAt(2); + const c2 = maybePath.charCodeAt(2); if (c2 === CHAR_SLASH) return PathType.Relative; return PathType.Normal; } @@ -18532,9 +22683,9 @@ const getType = p => { case CHAR_HASH: return PathType.Internal; } - const c1 = p.charCodeAt(1); + const c1 = maybePath.charCodeAt(1); if (c1 === CHAR_COLON) { - const c2 = p.charCodeAt(2); + const c2 = maybePath.charCodeAt(2); if ( (c2 === CHAR_BACKSLASH || c2 === CHAR_SLASH) && ((c0 >= CHAR_A && c0 <= CHAR_Z) || @@ -18543,28 +22694,33 @@ const getType = p => { return PathType.AbsoluteWin; } } + // DOS device paths (`\\?\…`, `\\.\…`) are handled in a cold helper so + // this function stays small — inlining the full check here regressed + // `description-files-multi` under `--no-opt` interpretation. Here we + // only pay the two-byte gate for non-DOS inputs. + if (c0 === CHAR_BACKSLASH && c1 === CHAR_BACKSLASH) { + return getDosDeviceType(maybePath); + } return PathType.Normal; }; -exports.getType = getType; /** - * @param {string} p a path + * @param {string} maybePath a path * @returns {string} the normalized path */ -const normalize = p => { - switch (getType(p)) { +const normalize = (maybePath) => { + switch (getType(maybePath)) { case PathType.Empty: - return p; + return maybePath; case PathType.AbsoluteWin: - return winNormalize(p); + return winNormalize(maybePath); case PathType.Relative: { - const r = posixNormalize(p); + const r = posixNormalize(maybePath); return getType(r) === PathType.Relative ? r : `./${r}`; } } - return posixNormalize(p); + return posixNormalize(maybePath); }; -exports.normalize = normalize; /** * @param {string} rootPath the root path @@ -18598,59 +22754,378 @@ const join = (rootPath, request) => { } return posixNormalize(rootPath); }; -exports.join = join; -const joinCache = new Map(); +/** + * @param {string} maybePath a path + * @returns {string} the directory name + */ +const dirname = (maybePath) => { + switch (getType(maybePath)) { + case PathType.AbsoluteWin: + return path.win32.dirname(maybePath); + } + return path.posix.dirname(maybePath); +}; + +/** @typedef {{ fn: (rootPath: string, request: string) => string, cache: Map> }} CachedJoin */ /** - * @param {string} rootPath the root path - * @param {string | undefined} request the request path - * @returns {string} the joined path + * @returns {CachedJoin} cached join */ -const cachedJoin = (rootPath, request) => { - let cacheEntry; - let cache = joinCache.get(rootPath); - if (cache === undefined) { - joinCache.set(rootPath, (cache = new Map())); - } else { - cacheEntry = cache.get(request); +const createCachedJoin = () => { + /** @type {CachedJoin["cache"]} */ + const cache = new Map(); + /** @type {CachedJoin["fn"]} */ + const fn = (rootPath, request) => { + /** @type {string | undefined} */ + let cacheEntry; + let inner = cache.get(rootPath); + if (inner === undefined) { + cache.set(rootPath, (inner = new Map())); + } else { + cacheEntry = inner.get(request); + if (cacheEntry !== undefined) return cacheEntry; + } + cacheEntry = join(rootPath, request); + inner.set(request, cacheEntry); + return cacheEntry; + }; + return { fn, cache }; +}; + +/** @typedef {{ fn: (maybePath: string) => string, cache: Map }} CachedDirname */ + +/** + * @returns {CachedDirname} cached dirname + */ +const createCachedDirname = () => { + /** @type {CachedDirname["cache"]} */ + const cache = new Map(); + /** @type {CachedDirname["fn"]} */ + const fn = (maybePath) => { + const cacheEntry = cache.get(maybePath); if (cacheEntry !== undefined) return cacheEntry; + const result = dirname(maybePath); + cache.set(maybePath, result); + return result; + }; + return { fn, cache }; +}; + +/** @typedef {{ fn: (maybePath: string, suffix?: string) => string, cache: Map> }} CachedBasename */ + +/** + * @returns {CachedBasename} cached basename + */ +const createCachedBasename = () => { + /** @type {CachedBasename["cache"]} */ + const cache = new Map(); + /** @type {CachedBasename["fn"]} */ + const fn = (maybePath, suffix) => { + /** @type {string | undefined} */ + let cacheEntry; + let inner = cache.get(maybePath); + if (inner === undefined) { + cache.set(maybePath, (inner = new Map())); + } else { + cacheEntry = inner.get(suffix); + if (cacheEntry !== undefined) return cacheEntry; + } + cacheEntry = path.basename(maybePath, suffix); + inner.set(suffix, cacheEntry); + return cacheEntry; + }; + return { fn, cache }; +}; + +/** + * Whether `request` is a relative request — i.e. matches `^\.\.?(?:\/|$)`. + * + * This is called on every `doResolve` via `UnsafeCachePlugin` and + * `getInnerRequest`, so the char-code form is meaningfully faster than the + * equivalent regex test: no regex state machine, no string object churn. + * @param {string} request request string + * @returns {boolean} true if request is relative + */ +const isRelativeRequest = (request) => { + const len = request.length; + if (len === 0 || request.charCodeAt(0) !== CHAR_DOT) return false; + if (len === 1) return true; // "." + const c1 = request.charCodeAt(1); + if (c1 === CHAR_SLASH) return true; // "./..." + if (c1 !== CHAR_DOT) return false; // ".x..." + if (len === 2) return true; // ".." + return request.charCodeAt(2) === CHAR_SLASH; // "../..." +}; + +/** + * Check if childPath is a subdirectory of parentPath. + * + * Called from `TsconfigPathsPlugin._selectPathsDataForContext` inside a loop + * over every tsconfig-paths context on every resolve, so it's worth keeping + * cheap. Compared to the previous `startsWith(normalize(parent + "/"))` + * version, this: checks the last char with `charCodeAt` instead of two + * `endsWith` calls; and skips `normalize()` entirely in the common case + * (parent has no trailing separator), since all we really need is the same + * anchoring effect — a cheap `startsWith` plus a separator char check on the + * byte immediately after `parentPath.length`. + * @param {string} parentPath parent directory path + * @param {string} childPath child path to check + * @returns {boolean} true if childPath is under parentPath + */ +const isSubPath = (parentPath, childPath) => { + const parentLen = parentPath.length; + if (parentLen === 0) { + // Match the old `normalize("" + "/") === "/"` fallback: an empty + // parent only "contains" a child that starts with a forward slash. + return childPath.length > 0 && childPath.charCodeAt(0) === CHAR_SLASH; + } + const lastChar = parentPath.charCodeAt(parentLen - 1); + if (lastChar === CHAR_SLASH || lastChar === CHAR_BACKSLASH) { + // Parent already ends with a separator — a plain prefix test is enough. + return childPath.startsWith(parentPath); + } + if (childPath.length <= parentLen) return false; + if (!childPath.startsWith(parentPath)) return false; + // Must be followed by a separator so "/app" doesn't match "/app-other". + const nextChar = childPath.charCodeAt(parentLen); + return nextChar === CHAR_SLASH || nextChar === CHAR_BACKSLASH; +}; + +/** + * Convert a `file:` `URL` instance to a filesystem path; any other input + * (including plain strings) is returned unchanged. Mirrors Node's `fs`, which + * treats strings as literal paths and only `URL` objects as URLs (see + * nodejs/node#17658) — so a directory literally named `file:` is never + * mistaken for a URL. + * @param {string | URL} maybeURL a path string or a `file:` `URL` instance + * @returns {string} a filesystem path + */ +const toPath = (maybeURL) => + maybeURL instanceof URL ? fileURLToPath(maybeURL) : maybeURL; + +module.exports.PathType = PathType; +module.exports.createCachedBasename = createCachedBasename; +module.exports.createCachedDirname = createCachedDirname; +module.exports.createCachedJoin = createCachedJoin; +module.exports.deprecatedInvalidSegmentRegEx = deprecatedInvalidSegmentRegEx; +module.exports.dirname = dirname; +module.exports.getType = getType; +module.exports.invalidSegmentRegEx = invalidSegmentRegEx; +module.exports.isRelativeRequest = isRelativeRequest; +module.exports.isSubPath = isSubPath; +module.exports.join = join; +module.exports.normalize = normalize; +module.exports.toPath = toPath; + + +/***/ }), + +/***/ 73816: +/***/ ((module) => { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx + + This file contains code ported from strip-json-comments: + https://github.com/sindresorhus/strip-json-comments + Original license: MIT + Original author: Sindre Sorhus +*/ + + + +/** + * @typedef {object} StripJsonCommentsOptions + * @property {boolean=} whitespace Replace comments with whitespace + * @property {boolean=} trailingCommas Strip trailing commas + */ + +const singleComment = Symbol("singleComment"); +const multiComment = Symbol("multiComment"); + +/** + * Strip without whitespace (returns empty string) + * @param {string} _string Unused + * @param {number} _start Unused + * @param {number} _end Unused + * @returns {string} Empty string for all input + */ +const stripWithoutWhitespace = (_string, _start, _end) => ""; + +/** + * Replace all characters except ASCII spaces, tabs and line endings with regular spaces to ensure valid JSON output. + * @param {string} string String to process + * @param {number} start Start index + * @param {number} end End index + * @returns {string} Processed string with comments replaced by whitespace + */ +const stripWithWhitespace = (string, start, end) => + string.slice(start, end).replace(/[^ \t\r\n]/g, " "); + +/** + * Check if a quote is escaped + * @param {string} jsonString JSON string + * @param {number} quotePosition Position of the quote + * @returns {boolean} True if the quote at the given position is escaped + */ +const isEscaped = (jsonString, quotePosition) => { + let index = quotePosition - 1; + let backslashCount = 0; + + while (jsonString[index] === "\\") { + index -= 1; + backslashCount += 1; } - cacheEntry = join(rootPath, request); - cache.set(request, cacheEntry); - return cacheEntry; + + return Boolean(backslashCount % 2); }; -exports.cachedJoin = cachedJoin; - -const checkImportsExportsFieldTarget = relativePath => { - let lastNonSlashIndex = 0; - let slashIndex = relativePath.indexOf("/", 1); - let cd = 0; - - while (slashIndex !== -1) { - const folder = relativePath.slice(lastNonSlashIndex, slashIndex); - - switch (folder) { - case "..": { - cd--; - if (cd < 0) - return new Error( - `Trying to access out of package scope. Requesting ${relativePath}` - ); - break; + +/** + * Strip comments from JSON string + * @param {string} jsonString JSON string with potential comments + * @param {StripJsonCommentsOptions} options Options + * @returns {string} JSON string without comments + */ +function stripJsonComments( + jsonString, + { whitespace = true, trailingCommas = false } = {}, +) { + if (typeof jsonString !== "string") { + throw new TypeError( + `Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``, + ); + } + + const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace; + + let isInsideString = false; + /** @type {false | typeof singleComment | typeof multiComment} */ + let isInsideComment = false; + let offset = 0; + let buffer = ""; + let result = ""; + let commaIndex = -1; + + for (let index = 0; index < jsonString.length; index++) { + const currentCharacter = jsonString[index]; + const nextCharacter = jsonString[index + 1]; + + if (!isInsideComment && currentCharacter === '"') { + // Enter or exit string + const escaped = isEscaped(jsonString, index); + if (!escaped) { + isInsideString = !isInsideString; } - case ".": - break; - default: - cd++; - break; } - lastNonSlashIndex = slashIndex + 1; - slashIndex = relativePath.indexOf("/", lastNonSlashIndex); + if (isInsideString) { + continue; + } + + if (!isInsideComment && currentCharacter + nextCharacter === "//") { + // Enter single-line comment + buffer += jsonString.slice(offset, index); + offset = index; + isInsideComment = singleComment; + index++; + } else if ( + isInsideComment === singleComment && + currentCharacter + nextCharacter === "\r\n" + ) { + // Exit single-line comment via \r\n + index++; + isInsideComment = false; + buffer += strip(jsonString, offset, index); + offset = index; + continue; + } else if (isInsideComment === singleComment && currentCharacter === "\n") { + // Exit single-line comment via \n + isInsideComment = false; + buffer += strip(jsonString, offset, index); + offset = index; + } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") { + // Enter multiline comment + buffer += jsonString.slice(offset, index); + offset = index; + isInsideComment = multiComment; + index++; + continue; + } else if ( + isInsideComment === multiComment && + currentCharacter + nextCharacter === "*/" + ) { + // Exit multiline comment + index++; + isInsideComment = false; + buffer += strip(jsonString, offset, index + 1); + offset = index + 1; + continue; + } else if (trailingCommas && !isInsideComment) { + if (commaIndex !== -1) { + if (currentCharacter === "}" || currentCharacter === "]") { + // Strip trailing comma + buffer += jsonString.slice(offset, index); + result += strip(buffer, 0, 1) + buffer.slice(1); + buffer = ""; + offset = index; + commaIndex = -1; + } else if ( + currentCharacter !== " " && + currentCharacter !== "\t" && + currentCharacter !== "\r" && + currentCharacter !== "\n" + ) { + // Hit non-whitespace following a comma; comma is not trailing + buffer += jsonString.slice(offset, index); + offset = index; + commaIndex = -1; + } + } else if (currentCharacter === ",") { + // Flush buffer prior to this point, and save new comma index + result += buffer + jsonString.slice(offset, index); + buffer = ""; + offset = index; + commaIndex = index; + } + } } -}; -exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; + + const remaining = + isInsideComment === singleComment + ? strip(jsonString, offset, jsonString.length) + : jsonString.slice(offset); + + return result + buffer + remaining; +} + +module.exports = stripJsonComments; + + +/***/ }), + +/***/ 28015: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = Error; + + +/***/ }), + +/***/ 6361: +/***/ ((module) => { + +"use strict"; + + +/** @type {import('./type')} */ +module.exports = TypeError; /***/ }), @@ -18671,6 +23146,7 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; Copyright (C) 2012 Joost-Wim Boekesteijn Copyright (C) 2012 Kris Kowal Copyright (C) 2012 Arpad Borsos + Copyright (C) 2020 Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -18724,8 +23200,8 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; FORMAT_MINIFY, FORMAT_DEFAULTS; - estraverse = __nccwpck_require__(3479); - esutils = __nccwpck_require__(4038); + estraverse = __nccwpck_require__(23479); + esutils = __nccwpck_require__(94038); Syntax = estraverse.Syntax; @@ -18745,29 +23221,31 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; Assignment: 1, Conditional: 2, ArrowFunction: 2, - LogicalOR: 3, - LogicalAND: 4, - BitwiseOR: 5, - BitwiseXOR: 6, - BitwiseAND: 7, - Equality: 8, - Relational: 9, - BitwiseSHIFT: 10, - Additive: 11, - Multiplicative: 12, - Exponentiation: 13, - Await: 14, - Unary: 14, - Postfix: 15, - OptionalChaining: 16, - Call: 17, - New: 18, - TaggedTemplate: 19, - Member: 20, - Primary: 21 + Coalesce: 3, + LogicalOR: 4, + LogicalAND: 5, + BitwiseOR: 6, + BitwiseXOR: 7, + BitwiseAND: 8, + Equality: 9, + Relational: 10, + BitwiseSHIFT: 11, + Additive: 12, + Multiplicative: 13, + Exponentiation: 14, + Await: 15, + Unary: 15, + Postfix: 16, + OptionalChaining: 17, + Call: 18, + New: 19, + TaggedTemplate: 20, + Member: 21, + Primary: 22 }; BinaryPrecedence = { + '??': Precedence.Coalesce, '||': Precedence.LogicalOR, '&&': Precedence.LogicalAND, '|': Precedence.BitwiseOR, @@ -18802,7 +23280,8 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; F_ALLOW_UNPARATH_NEW = 1 << 2, F_FUNC_BODY = 1 << 3, F_DIRECTIVE_CTX = 1 << 4, - F_SEMICOLON_OPT = 1 << 5; + F_SEMICOLON_OPT = 1 << 5, + F_FOUND_COALESCE = 1 << 6; //Expression flag sets //NOTE: Flag order: @@ -20478,7 +24957,7 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; } return parenthesize( [ - this.generateExpression(expr.test, Precedence.LogicalOR, flags), + this.generateExpression(expr.test, Precedence.Coalesce, flags), space + '?' + space, this.generateExpression(expr.consequent, Precedence.Assignment, flags), space + ':' + space, @@ -20490,6 +24969,9 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; }, LogicalExpression: function (expr, precedence, flags) { + if (expr.operator === '??') { + flags |= F_FOUND_COALESCE; + } return this.BinaryExpression(expr, precedence, flags); }, @@ -20527,6 +25009,9 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) { return ['(', result, ')']; } + if ((expr.operator === '||' || expr.operator === '&&') && (flags & F_FOUND_COALESCE)) { + return ['(', result, ')']; + } return parenthesize(result, currentPrecedence, precedence); }, @@ -21008,6 +25493,16 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; return '/' + expr.regex.pattern + '/' + expr.regex.flags; } + if (typeof expr.value === 'bigint') { + return expr.value.toString() + 'n'; + } + + // `expr.value` can be null if `expr.bigint` exists. We need to check + // `expr.bigint` first. + if (expr.bigint) { + return expr.bigint + 'n'; + } + if (expr.value === null) { return 'null'; } @@ -21249,7 +25744,7 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; if (!exports.browser) { // We assume environment is node.js // And prevent from including source-map by browserify - SourceNode = (__nccwpck_require__(6594).SourceNode); + SourceNode = (__nccwpck_require__(56594).SourceNode); } else { SourceNode = global.sourceMap.SourceNode; } @@ -21296,7 +25791,7 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; FORMAT_DEFAULTS = getDefaultOptions().format; - exports.version = __nccwpck_require__(8531).version; + exports.version = __nccwpck_require__(78531).version; exports.generate = generate; exports.attachComments = estraverse.attachComments; exports.Precedence = updateDeeply({}, Precedence); @@ -21309,7 +25804,7 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; /***/ }), -/***/ 7185: +/***/ 37185: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -21319,7 +25814,7 @@ exports.checkImportsExportsFieldTarget = checkImportsExportsFieldTarget; */ -const KEYS = __nccwpck_require__(3432); +const KEYS = __nccwpck_require__(63432); // Types. const NODE_TYPES = Object.freeze(Object.keys(KEYS)); @@ -21398,7 +25893,7 @@ module.exports = Object.freeze({ /***/ }), -/***/ 8823: +/***/ 78823: /***/ (function(module) { (function webpackUniversalModuleDefinition(root, factory) { @@ -28107,7 +32602,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }), -/***/ 3479: +/***/ 23479: /***/ ((__unused_webpack_module, exports) => { /* @@ -28919,7 +33414,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }), -/***/ 471: +/***/ 70471: /***/ ((module) => { /* @@ -29070,7 +33565,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }), -/***/ 5501: +/***/ 15501: /***/ ((module) => { /* @@ -29212,7 +33707,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }), -/***/ 7635: +/***/ 67635: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /* @@ -29242,7 +33737,7 @@ return /******/ (function(modules) { // webpackBootstrap (function () { 'use strict'; - var code = __nccwpck_require__(5501); + var code = __nccwpck_require__(15501); function isStrictModeReservedWordES6(id) { switch (id) { @@ -29384,7 +33879,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }), -/***/ 4038: +/***/ 94038: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { /* @@ -29415,27 +33910,26 @@ return /******/ (function(modules) { // webpackBootstrap (function () { 'use strict'; - exports.ast = __nccwpck_require__(471); - exports.code = __nccwpck_require__(5501); - exports.keyword = __nccwpck_require__(7635); + exports.ast = __nccwpck_require__(70471); + exports.code = __nccwpck_require__(15501); + exports.keyword = __nccwpck_require__(67635); }()); /* vim: set sw=4 ts=4 et tw=80 : */ /***/ }), -/***/ 3664: +/***/ 43664: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const taskManager = __nccwpck_require__(2708); -const patternManager = __nccwpck_require__(8306); -const async_1 = __nccwpck_require__(5679); -const stream_1 = __nccwpck_require__(4630); -const sync_1 = __nccwpck_require__(2405); -const settings_1 = __nccwpck_require__(952); -const utils = __nccwpck_require__(5444); +const taskManager = __nccwpck_require__(42708); +const async_1 = __nccwpck_require__(95679); +const stream_1 = __nccwpck_require__(94630); +const sync_1 = __nccwpck_require__(42405); +const settings_1 = __nccwpck_require__(10952); +const utils = __nccwpck_require__(45444); async function FastGlob(source, options) { assertPatternsInput(source); const works = getWorks(source, async_1.default, options); @@ -29445,6 +33939,10 @@ async function FastGlob(source, options) { // https://github.com/typescript-eslint/typescript-eslint/issues/60 // eslint-disable-next-line no-redeclare (function (FastGlob) { + FastGlob.glob = FastGlob; + FastGlob.globSync = sync; + FastGlob.globStream = stream; + FastGlob.async = FastGlob; function sync(source, options) { assertPatternsInput(source); const works = getWorks(source, sync_1.default, options); @@ -29464,7 +33962,7 @@ async function FastGlob(source, options) { FastGlob.stream = stream; function generateTasks(source, options) { assertPatternsInput(source); - const patterns = patternManager.transform([].concat(source)); + const patterns = [].concat(source); const settings = new settings_1.default(options); return taskManager.generate(patterns, settings); } @@ -29480,9 +33978,40 @@ async function FastGlob(source, options) { return utils.path.escape(source); } FastGlob.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPathToPattern(source); + } + FastGlob.convertPathToPattern = convertPathToPattern; + let posix; + (function (posix) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapePosixPath(source); + } + posix.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertPosixPathToPattern(source); + } + posix.convertPathToPattern = convertPathToPattern; + })(posix = FastGlob.posix || (FastGlob.posix = {})); + let win32; + (function (win32) { + function escapePath(source) { + assertPatternsInput(source); + return utils.path.escapeWindowsPath(source); + } + win32.escapePath = escapePath; + function convertPathToPattern(source) { + assertPatternsInput(source); + return utils.path.convertWindowsPathToPattern(source); + } + win32.convertPathToPattern = convertPathToPattern; + })(win32 = FastGlob.win32 || (FastGlob.win32 = {})); })(FastGlob || (FastGlob = {})); function getWorks(source, _Provider, options) { - const patterns = patternManager.transform([].concat(source)); + const patterns = [].concat(source); const settings = new settings_1.default(options); const tasks = taskManager.generate(patterns, settings); const provider = new _Provider(settings); @@ -29500,46 +34029,19 @@ module.exports = FastGlob; /***/ }), -/***/ 8306: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.removeDuplicateSlashes = exports.transform = void 0; -/** - * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. - * The latter is due to the presence of the device path at the beginning of the UNC path. - * @todo rewrite to negative lookbehind with the next major release. - */ -const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; -function transform(patterns) { - return patterns.map((pattern) => removeDuplicateSlashes(pattern)); -} -exports.transform = transform; -/** - * This package only works with forward slashes as a path separator. - * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. - */ -function removeDuplicateSlashes(pattern) { - return pattern.replace(DOUBLE_SLASH_RE, '/'); -} -exports.removeDuplicateSlashes = removeDuplicateSlashes; - - -/***/ }), - -/***/ 2708: +/***/ 42708: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; -const utils = __nccwpck_require__(5444); -function generate(patterns, settings) { +const utils = __nccwpck_require__(45444); +function generate(input, settings) { + const patterns = processPatterns(input, settings); + const ignore = processPatterns(settings.ignore, settings); const positivePatterns = getPositivePatterns(patterns); - const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); + const negativePatterns = getNegativePatternsAsPositive(patterns, ignore); const staticPatterns = positivePatterns.filter((pattern) => utils.pattern.isStaticPattern(pattern, settings)); const dynamicPatterns = positivePatterns.filter((pattern) => utils.pattern.isDynamicPattern(pattern, settings)); const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, /* dynamic */ false); @@ -29547,6 +34049,34 @@ function generate(patterns, settings) { return staticTasks.concat(dynamicTasks); } exports.generate = generate; +function processPatterns(input, settings) { + let patterns = input; + /** + * The original pattern like `{,*,**,a/*}` can lead to problems checking the depth when matching entry + * and some problems with the micromatch package (see fast-glob issues: #365, #394). + * + * To solve this problem, we expand all patterns containing brace expansion. This can lead to a slight slowdown + * in matching in the case of a large set of patterns after expansion. + */ + if (settings.braceExpansion) { + patterns = utils.pattern.expandPatternsWithBraceExpansion(patterns); + } + /** + * If the `baseNameMatch` option is enabled, we must add globstar to patterns, so that they can be used + * at any nesting level. + * + * We do this here, because otherwise we have to complicate the filtering logic. For example, we need to change + * the pattern in the filter before creating a regular expression. There is no need to change the patterns + * in the application. Only on the input. + */ + if (settings.baseNameMatch) { + patterns = patterns.map((pattern) => pattern.includes('/') ? pattern : `**/${pattern}`); + } + /** + * This method also removes duplicate slashes that may have been in the pattern or formed as a result of expansion. + */ + return patterns.map((pattern) => utils.pattern.removeDuplicateSlashes(pattern)); +} /** * Returns tasks grouped by basic pattern directories. * @@ -29617,29 +34147,24 @@ exports.convertPatternGroupToTask = convertPatternGroupToTask; /***/ }), -/***/ 5679: +/***/ 95679: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const stream_1 = __nccwpck_require__(2083); -const provider_1 = __nccwpck_require__(257); +const async_1 = __nccwpck_require__(97747); +const provider_1 = __nccwpck_require__(60257); class ProviderAsync extends provider_1.default { constructor() { super(...arguments); - this._reader = new stream_1.default(this._settings); + this._reader = new async_1.default(this._settings); } - read(task) { + async read(task) { const root = this._getRootDirectory(task); const options = this._getReaderOptions(task); - const entries = []; - return new Promise((resolve, reject) => { - const stream = this.api(root, task, options); - stream.once('error', reject); - stream.on('data', (entry) => entries.push(options.transform(entry))); - stream.once('end', () => resolve(entries)); - }); + const entries = await this.api(root, task, options); + return entries.map((entry) => options.transform(entry)); } api(root, task, options) { if (task.dynamic) { @@ -29653,14 +34178,14 @@ exports["default"] = ProviderAsync; /***/ }), -/***/ 6983: +/***/ 36983: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(5444); -const partial_1 = __nccwpck_require__(5295); +const utils = __nccwpck_require__(45444); +const partial_1 = __nccwpck_require__(35295); class DeepFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; @@ -29723,13 +34248,13 @@ exports["default"] = DeepFilter; /***/ }), -/***/ 1343: +/***/ 71343: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(5444); +const utils = __nccwpck_require__(45444); class EntryFilter { constructor(_settings, _micromatchOptions) { this._settings = _settings; @@ -29737,32 +34262,37 @@ class EntryFilter { this.index = new Map(); } getFilter(positive, negative) { - const positiveRe = utils.pattern.convertPatternsToRe(positive, this._micromatchOptions); - const negativeRe = utils.pattern.convertPatternsToRe(negative, this._micromatchOptions); - return (entry) => this._filter(entry, positiveRe, negativeRe); + const [absoluteNegative, relativeNegative] = utils.pattern.partitionAbsoluteAndRelative(negative); + const patterns = { + positive: { + all: utils.pattern.convertPatternsToRe(positive, this._micromatchOptions) + }, + negative: { + absolute: utils.pattern.convertPatternsToRe(absoluteNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })), + relative: utils.pattern.convertPatternsToRe(relativeNegative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true })) + } + }; + return (entry) => this._filter(entry, patterns); } - _filter(entry, positiveRe, negativeRe) { - if (this._settings.unique && this._isDuplicateEntry(entry)) { + _filter(entry, patterns) { + const filepath = utils.path.removeLeadingDotSegment(entry.path); + if (this._settings.unique && this._isDuplicateEntry(filepath)) { return false; } if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { return false; } - if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { - return false; - } - const filepath = this._settings.baseNameMatch ? entry.name : entry.path; - const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); + const isMatched = this._isMatchToPatternsSet(filepath, patterns, entry.dirent.isDirectory()); if (this._settings.unique && isMatched) { - this._createIndexRecord(entry); + this._createIndexRecord(filepath); } return isMatched; } - _isDuplicateEntry(entry) { - return this.index.has(entry.path); + _isDuplicateEntry(filepath) { + return this.index.has(filepath); } - _createIndexRecord(entry) { - this.index.set(entry.path, undefined); + _createIndexRecord(filepath) { + this.index.set(filepath, undefined); } _onlyFileFilter(entry) { return this._settings.onlyFiles && !entry.dirent.isFile(); @@ -29770,20 +34300,40 @@ class EntryFilter { _onlyDirectoryFilter(entry) { return this._settings.onlyDirectories && !entry.dirent.isDirectory(); } - _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { - if (!this._settings.absolute) { + _isMatchToPatternsSet(filepath, patterns, isDirectory) { + const isMatched = this._isMatchToPatterns(filepath, patterns.positive.all, isDirectory); + if (!isMatched) { return false; } - const fullpath = utils.path.makeAbsolute(this._settings.cwd, entryPath); - return utils.pattern.matchAny(fullpath, patternsRe); + const isMatchedByRelativeNegative = this._isMatchToPatterns(filepath, patterns.negative.relative, isDirectory); + if (isMatchedByRelativeNegative) { + return false; + } + const isMatchedByAbsoluteNegative = this._isMatchToAbsoluteNegative(filepath, patterns.negative.absolute, isDirectory); + if (isMatchedByAbsoluteNegative) { + return false; + } + return true; } - /** - * First, just trying to apply patterns to the path. - * Second, trying to apply patterns to the path with final slash. - */ - _isMatchToPatterns(entryPath, patternsRe) { - const filepath = utils.path.removeLeadingDotSegment(entryPath); - return utils.pattern.matchAny(filepath, patternsRe) || utils.pattern.matchAny(filepath + '/', patternsRe); + _isMatchToAbsoluteNegative(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } + const fullpath = utils.path.makeAbsolute(this._settings.cwd, filepath); + return this._isMatchToPatterns(fullpath, patternsRe, isDirectory); + } + _isMatchToPatterns(filepath, patternsRe, isDirectory) { + if (patternsRe.length === 0) { + return false; + } + // Trying to match files and directories by patterns. + const isMatched = utils.pattern.matchAny(filepath, patternsRe); + // A pattern with a trailling slash can be used for directory matching. + // To apply such pattern, we need to add a tralling slash to the path. + if (!isMatched && isDirectory) { + return utils.pattern.matchAny(filepath + '/', patternsRe); + } + return isMatched; } } exports["default"] = EntryFilter; @@ -29791,13 +34341,13 @@ exports["default"] = EntryFilter; /***/ }), -/***/ 6654: +/***/ 36654: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(5444); +const utils = __nccwpck_require__(45444); class ErrorFilter { constructor(_settings) { this._settings = _settings; @@ -29814,13 +34364,13 @@ exports["default"] = ErrorFilter; /***/ }), -/***/ 2576: +/***/ 32576: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(5444); +const utils = __nccwpck_require__(45444); class Matcher { constructor(_patterns, _settings, _micromatchOptions) { this._patterns = _patterns; @@ -29830,12 +34380,7 @@ class Matcher { this._fillStorage(); } _fillStorage() { - /** - * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). - * So, before expand patterns with brace expansion into separated patterns. - */ - const patterns = utils.pattern.expandPatternsWithBraceExpansion(this._patterns); - for (const pattern of patterns) { + for (const pattern of this._patterns) { const segments = this._getPatternSegments(pattern); const sections = this._splitSegmentsIntoSections(segments); this._storage.push({ @@ -29872,13 +34417,13 @@ exports["default"] = Matcher; /***/ }), -/***/ 5295: +/***/ 35295: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const matcher_1 = __nccwpck_require__(2576); +const matcher_1 = __nccwpck_require__(32576); class PartialMatcher extends matcher_1.default { match(filepath) { const parts = filepath.split('/'); @@ -29918,17 +34463,17 @@ exports["default"] = PartialMatcher; /***/ }), -/***/ 257: +/***/ 60257: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const path = __nccwpck_require__(1017); -const deep_1 = __nccwpck_require__(6983); -const entry_1 = __nccwpck_require__(1343); -const error_1 = __nccwpck_require__(6654); -const entry_2 = __nccwpck_require__(4029); +const path = __nccwpck_require__(71017); +const deep_1 = __nccwpck_require__(36983); +const entry_1 = __nccwpck_require__(71343); +const error_1 = __nccwpck_require__(36654); +const entry_2 = __nccwpck_require__(94029); class Provider { constructor(_settings) { this._settings = _settings; @@ -29974,15 +34519,15 @@ exports["default"] = Provider; /***/ }), -/***/ 4630: +/***/ 94630: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const stream_1 = __nccwpck_require__(2781); -const stream_2 = __nccwpck_require__(2083); -const provider_1 = __nccwpck_require__(257); +const stream_1 = __nccwpck_require__(12781); +const stream_2 = __nccwpck_require__(12083); +const provider_1 = __nccwpck_require__(60257); class ProviderStream extends provider_1.default { constructor() { super(...arguments); @@ -30013,14 +34558,14 @@ exports["default"] = ProviderStream; /***/ }), -/***/ 2405: +/***/ 42405: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const sync_1 = __nccwpck_require__(6234); -const provider_1 = __nccwpck_require__(257); +const sync_1 = __nccwpck_require__(76234); +const provider_1 = __nccwpck_require__(60257); class ProviderSync extends provider_1.default { constructor() { super(...arguments); @@ -30044,13 +34589,13 @@ exports["default"] = ProviderSync; /***/ }), -/***/ 4029: +/***/ 94029: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils = __nccwpck_require__(5444); +const utils = __nccwpck_require__(45444); class EntryTransformer { constructor(_settings) { this._settings = _settings; @@ -30078,15 +34623,58 @@ exports["default"] = EntryTransformer; /***/ }), -/***/ 5582: +/***/ 97747: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const fsWalk = __nccwpck_require__(26026); +const reader_1 = __nccwpck_require__(65582); +const stream_1 = __nccwpck_require__(12083); +class ReaderAsync extends reader_1.default { + constructor() { + super(...arguments); + this._walkAsync = fsWalk.walk; + this._readerStream = new stream_1.default(this._settings); + } + dynamic(root, options) { + return new Promise((resolve, reject) => { + this._walkAsync(root, options, (error, entries) => { + if (error === null) { + resolve(entries); + } + else { + reject(error); + } + }); + }); + } + async static(patterns, options) { + const entries = []; + const stream = this._readerStream.static(patterns, options); + // After #235, replace it with an asynchronous iterator. + return new Promise((resolve, reject) => { + stream.once('error', reject); + stream.on('data', (entry) => entries.push(entry)); + stream.once('end', () => resolve(entries)); + }); + } +} +exports["default"] = ReaderAsync; + + +/***/ }), + +/***/ 65582: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const path = __nccwpck_require__(1017); -const fsStat = __nccwpck_require__(109); -const utils = __nccwpck_require__(5444); +const path = __nccwpck_require__(71017); +const fsStat = __nccwpck_require__(70109); +const utils = __nccwpck_require__(45444); class Reader { constructor(_settings) { this._settings = _settings; @@ -30119,16 +34707,16 @@ exports["default"] = Reader; /***/ }), -/***/ 2083: +/***/ 12083: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const stream_1 = __nccwpck_require__(2781); -const fsStat = __nccwpck_require__(109); -const fsWalk = __nccwpck_require__(6026); -const reader_1 = __nccwpck_require__(5582); +const stream_1 = __nccwpck_require__(12781); +const fsStat = __nccwpck_require__(70109); +const fsWalk = __nccwpck_require__(26026); +const reader_1 = __nccwpck_require__(65582); class ReaderStream extends reader_1.default { constructor() { super(...arguments); @@ -30182,15 +34770,15 @@ exports["default"] = ReaderStream; /***/ }), -/***/ 6234: +/***/ 76234: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const fsStat = __nccwpck_require__(109); -const fsWalk = __nccwpck_require__(6026); -const reader_1 = __nccwpck_require__(5582); +const fsStat = __nccwpck_require__(70109); +const fsWalk = __nccwpck_require__(26026); +const reader_1 = __nccwpck_require__(65582); class ReaderSync extends reader_1.default { constructor() { super(...arguments); @@ -30233,15 +34821,15 @@ exports["default"] = ReaderSync; /***/ }), -/***/ 952: +/***/ 10952: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; -const fs = __nccwpck_require__(7147); -const os = __nccwpck_require__(2037); +const fs = __nccwpck_require__(57147); +const os = __nccwpck_require__(22037); /** * The `os.cpus` method can return zero. We expect the number of cores to be greater than zero. * https://github.com/nodejs/node/blob/7faeddf23a98c53896f8b574a6e66589e8fb1eb8/lib/os.js#L106-L107 @@ -30285,6 +34873,8 @@ class Settings { if (this.stats) { this.objectMode = true; } + // Remove the cast to the array in the next major (#404). + this.ignore = [].concat(this.ignore); } _getValue(option, value) { return option === undefined ? value : option; @@ -30298,7 +34888,7 @@ exports["default"] = Settings; /***/ }), -/***/ 5325: +/***/ 85325: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -30328,7 +34918,7 @@ exports.splitWhen = splitWhen; /***/ }), -/***/ 1230: +/***/ 41230: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -30343,7 +34933,7 @@ exports.isEnoentCodeError = isEnoentCodeError; /***/ }), -/***/ 7543: +/***/ 17543: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -30370,41 +34960,60 @@ exports.createDirentFromStats = createDirentFromStats; /***/ }), -/***/ 5444: +/***/ 45444: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; -const array = __nccwpck_require__(5325); +const array = __nccwpck_require__(85325); exports.array = array; -const errno = __nccwpck_require__(1230); +const errno = __nccwpck_require__(41230); exports.errno = errno; -const fs = __nccwpck_require__(7543); +const fs = __nccwpck_require__(17543); exports.fs = fs; -const path = __nccwpck_require__(3873); +const path = __nccwpck_require__(63873); exports.path = path; -const pattern = __nccwpck_require__(1221); +const pattern = __nccwpck_require__(81221); exports.pattern = pattern; -const stream = __nccwpck_require__(8382); +const stream = __nccwpck_require__(18382); exports.stream = stream; -const string = __nccwpck_require__(2203); +const string = __nccwpck_require__(52203); exports.string = string; /***/ }), -/***/ 3873: +/***/ 63873: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0; -const path = __nccwpck_require__(1017); +exports.convertPosixPathToPattern = exports.convertWindowsPathToPattern = exports.convertPathToPattern = exports.escapePosixPath = exports.escapeWindowsPath = exports.escape = exports.removeLeadingDotSegment = exports.makeAbsolute = exports.unixify = void 0; +const os = __nccwpck_require__(22037); +const path = __nccwpck_require__(71017); +const IS_WINDOWS_PLATFORM = os.platform() === 'win32'; const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ -const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; +/** + * All non-escaped special characters. + * Posix: ()*?[]{|}, !+@ before (, ! at the beginning, \\ before non-special characters. + * Windows: (){}[], !+@ before (, ! at the beginning. + */ +const POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g; +const WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g; +/** + * The device path (\\.\ or \\?\). + * https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats#dos-device-paths + */ +const DOS_DEVICE_PATH_RE = /^\\\\([.?])/; +/** + * All backslashes except those escaping special characters. + * Windows: !()+@{} + * https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions + */ +const WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g; /** * Designed to work only with simple paths: `dir\\file`. */ @@ -30416,10 +35025,6 @@ function makeAbsolute(cwd, filepath) { return path.resolve(cwd, filepath); } exports.makeAbsolute = makeAbsolute; -function escape(pattern) { - return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); -} -exports.escape = escape; function removeLeadingDotSegment(entry) { // We do not use `startsWith` because this is 10x slower than current implementation for some cases. // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with @@ -30432,20 +35037,40 @@ function removeLeadingDotSegment(entry) { return entry; } exports.removeLeadingDotSegment = removeLeadingDotSegment; +exports.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath; +function escapeWindowsPath(pattern) { + return pattern.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escapeWindowsPath = escapeWindowsPath; +function escapePosixPath(pattern) { + return pattern.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); +} +exports.escapePosixPath = escapePosixPath; +exports.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern; +function convertWindowsPathToPattern(filepath) { + return escapeWindowsPath(filepath) + .replace(DOS_DEVICE_PATH_RE, '//$1') + .replace(WINDOWS_BACKSLASHES_RE, '/'); +} +exports.convertWindowsPathToPattern = convertWindowsPathToPattern; +function convertPosixPathToPattern(filepath) { + return escapePosixPath(filepath); +} +exports.convertPosixPathToPattern = convertPosixPathToPattern; /***/ }), -/***/ 1221: +/***/ 81221: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; -const path = __nccwpck_require__(1017); -const globParent = __nccwpck_require__(4655); -const micromatch = __nccwpck_require__(6228); +exports.isAbsolute = exports.partitionAbsoluteAndRelative = exports.removeDuplicateSlashes = exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.isPatternRelatedToParentDirectory = exports.getPatternsOutsideCurrentDirectory = exports.getPatternsInsideCurrentDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; +const path = __nccwpck_require__(71017); +const globParent = __nccwpck_require__(54655); +const micromatch = __nccwpck_require__(76228); const GLOBSTAR = '**'; const ESCAPE_SYMBOL = '\\'; const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; @@ -30453,6 +35078,11 @@ const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/; const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/; const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/; const BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./; +/** + * Matches a sequence of two or more consecutive slashes, excluding the first two slashes at the beginning of the string. + * The latter is due to the presence of the device path at the beginning of the UNC path. + */ +const DOUBLE_SLASH_RE = /(?!^)\/{2,}/g; function isStaticPattern(pattern, options = {}) { return !isDynamicPattern(pattern, options); } @@ -30571,10 +35201,16 @@ function expandPatternsWithBraceExpansion(patterns) { } exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; function expandBraceExpansion(pattern) { - return micromatch.braces(pattern, { - expand: true, - nodupes: true - }); + const patterns = micromatch.braces(pattern, { expand: true, nodupes: true, keepEscaping: true }); + /** + * Sort the patterns by length so that the same depth patterns are processed side by side. + * `a/{b,}/{c,}/*` – `['a///*', 'a/b//*', 'a//c/*', 'a/b/c/*']` + */ + patterns.sort((a, b) => a.length - b.length); + /** + * Micromatch can return an empty string in the case of patterns like `{a,}`. + */ + return patterns.filter((pattern) => pattern !== ''); } exports.expandBraceExpansion = expandBraceExpansion; function getPatternParts(pattern, options) { @@ -30609,18 +35245,44 @@ function matchAny(entry, patternsRe) { return patternsRe.some((patternRe) => patternRe.test(entry)); } exports.matchAny = matchAny; +/** + * This package only works with forward slashes as a path separator. + * Because of this, we cannot use the standard `path.normalize` method, because on Windows platform it will use of backslashes. + */ +function removeDuplicateSlashes(pattern) { + return pattern.replace(DOUBLE_SLASH_RE, '/'); +} +exports.removeDuplicateSlashes = removeDuplicateSlashes; +function partitionAbsoluteAndRelative(patterns) { + const absolute = []; + const relative = []; + for (const pattern of patterns) { + if (isAbsolute(pattern)) { + absolute.push(pattern); + } + else { + relative.push(pattern); + } + } + return [absolute, relative]; +} +exports.partitionAbsoluteAndRelative = partitionAbsoluteAndRelative; +function isAbsolute(pattern) { + return path.isAbsolute(pattern); +} +exports.isAbsolute = isAbsolute; /***/ }), -/***/ 8382: +/***/ 18382: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.merge = void 0; -const merge2 = __nccwpck_require__(2578); +const merge2 = __nccwpck_require__(82578); function merge(streams) { const mergedStream = merge2(streams); streams.forEach((stream) => { @@ -30638,7 +35300,7 @@ function propagateCloseEventToSources(streams) { /***/ }), -/***/ 2203: +/***/ 52203: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -30657,307 +35319,16 @@ exports.isEmpty = isEmpty; /***/ }), -/***/ 7340: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/* eslint-disable no-var */ - -var reusify = __nccwpck_require__(2113) - -function fastqueue (context, worker, concurrency) { - if (typeof context === 'function') { - concurrency = worker - worker = context - context = null - } - - if (concurrency < 1) { - throw new Error('fastqueue concurrency must be greater than 1') - } - - var cache = reusify(Task) - var queueHead = null - var queueTail = null - var _running = 0 - var errorHandler = null - - var self = { - push: push, - drain: noop, - saturated: noop, - pause: pause, - paused: false, - concurrency: concurrency, - running: running, - resume: resume, - idle: idle, - length: length, - getQueue: getQueue, - unshift: unshift, - empty: noop, - kill: kill, - killAndDrain: killAndDrain, - error: error - } - - return self - - function running () { - return _running - } - - function pause () { - self.paused = true - } - - function length () { - var current = queueHead - var counter = 0 - - while (current) { - current = current.next - counter++ - } - - return counter - } - - function getQueue () { - var current = queueHead - var tasks = [] - - while (current) { - tasks.push(current.value) - current = current.next - } - - return tasks - } - - function resume () { - if (!self.paused) return - self.paused = false - for (var i = 0; i < self.concurrency; i++) { - _running++ - release() - } - } - - function idle () { - return _running === 0 && self.length() === 0 - } - - function push (value, done) { - var current = cache.get() - - current.context = context - current.release = release - current.value = value - current.callback = done || noop - current.errorHandler = errorHandler - - if (_running === self.concurrency || self.paused) { - if (queueTail) { - queueTail.next = current - queueTail = current - } else { - queueHead = current - queueTail = current - self.saturated() - } - } else { - _running++ - worker.call(context, current.value, current.worked) - } - } - - function unshift (value, done) { - var current = cache.get() - - current.context = context - current.release = release - current.value = value - current.callback = done || noop - - if (_running === self.concurrency || self.paused) { - if (queueHead) { - current.next = queueHead - queueHead = current - } else { - queueHead = current - queueTail = current - self.saturated() - } - } else { - _running++ - worker.call(context, current.value, current.worked) - } - } - - function release (holder) { - if (holder) { - cache.release(holder) - } - var next = queueHead - if (next) { - if (!self.paused) { - if (queueTail === queueHead) { - queueTail = null - } - queueHead = next.next - next.next = null - worker.call(context, next.value, next.worked) - if (queueTail === null) { - self.empty() - } - } else { - _running-- - } - } else if (--_running === 0) { - self.drain() - } - } - - function kill () { - queueHead = null - queueTail = null - self.drain = noop - } - - function killAndDrain () { - queueHead = null - queueTail = null - self.drain() - self.drain = noop - } - - function error (handler) { - errorHandler = handler - } -} - -function noop () {} - -function Task () { - this.value = null - this.callback = noop - this.next = null - this.release = noop - this.context = null - this.errorHandler = null - - var self = this - - this.worked = function worked (err, result) { - var callback = self.callback - var errorHandler = self.errorHandler - var val = self.value - self.value = null - self.callback = noop - if (self.errorHandler) { - errorHandler(err, val) - } - callback.call(self.context, err, result) - self.release(self) - } -} - -function queueAsPromised (context, worker, concurrency) { - if (typeof context === 'function') { - concurrency = worker - worker = context - context = null - } - - function asyncWrapper (arg, cb) { - worker.call(this, arg) - .then(function (res) { - cb(null, res) - }, cb) - } - - var queue = fastqueue(context, asyncWrapper, concurrency) - - var pushCb = queue.push - var unshiftCb = queue.unshift - - queue.push = push - queue.unshift = unshift - queue.drained = drained - - return queue - - function push (value) { - var p = new Promise(function (resolve, reject) { - pushCb(value, function (err, result) { - if (err) { - reject(err) - return - } - resolve(result) - }) - }) - - // Let's fork the promise chain to - // make the error bubble up to the user but - // not lead to a unhandledRejection - p.catch(noop) - - return p - } - - function unshift (value) { - var p = new Promise(function (resolve, reject) { - unshiftCb(value, function (err, result) { - if (err) { - reject(err) - return - } - resolve(result) - }) - }) - - // Let's fork the promise chain to - // make the error bubble up to the user but - // not lead to a unhandledRejection - p.catch(noop) - - return p - } - - function drained () { - var previousDrain = queue.drain - - var p = new Promise(function (resolve) { - queue.drain = function () { - previousDrain() - resolve() - } - }) - - return p - } -} - -module.exports = fastqueue -module.exports.promise = queueAsPromised - - -/***/ }), - -/***/ 1695: +/***/ 41695: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(1017); -const debug = __nccwpck_require__(8237)('cabinet'); -const {createMatchPath} = __nccwpck_require__(6143); -const fs = __nccwpck_require__(7147); +const path = __nccwpck_require__(71017); +const debug = __nccwpck_require__(38237)('cabinet'); +const {createMatchPath} = __nccwpck_require__(56143); +const fs = __nccwpck_require__(57147); /* * most js resolver are lazy-loaded (only required when needed) * e.g. dont load requirejs when we only have commonjs modules to resolve @@ -30968,14 +35339,14 @@ let getModuleType; let resolve; let amdLookup; -const stylusLookup = __nccwpck_require__(4765); -const sassLookup = __nccwpck_require__(6881); +const stylusLookup = __nccwpck_require__(44765); +const sassLookup = __nccwpck_require__(66881); let ts; let resolveDependencyPath; -const appModulePath = __nccwpck_require__(5360); +const appModulePath = __nccwpck_require__(55360); let webpackResolve; -const isRelative = __nccwpck_require__(2837); +const isRelative = __nccwpck_require__(82837); const defaultLookups = { '.js': jsLookup, @@ -31019,7 +35390,7 @@ module.exports = function cabinet(options) { if (!resolver) { debug('using generic resolver'); if (!resolveDependencyPath) { - resolveDependencyPath = __nccwpck_require__(5886); + resolveDependencyPath = __nccwpck_require__(65886); } resolver = resolveDependencyPath; @@ -31072,7 +35443,7 @@ module.exports.unregister = function(extension) { */ module.exports._getJSType = function(options = {}) { if (!getModuleType) { - getModuleType = __nccwpck_require__(1877); + getModuleType = __nccwpck_require__(81877); } if (options.config) { @@ -31094,7 +35465,7 @@ module.exports._getJSType = function(options = {}) { function getCompilerOptionsFromTsConfig(tsConfig) { if (!ts) { - ts = __nccwpck_require__(7414); + ts = __nccwpck_require__(37414); } let compilerOptions = {}; @@ -31150,7 +35521,7 @@ function jsLookup(options) { case 'amd': debug('using amd resolver'); if (!amdLookup) { - amdLookup = __nccwpck_require__(6203); + amdLookup = __nccwpck_require__(86203); } return amdLookup({ @@ -31206,7 +35577,8 @@ function tsLookup({dependency, filename, directory, webpackConfig, tsConfig, tsC if (namedModule.resolvedModule) { result = namedModule.resolvedModule.resolvedFileName; if (namedModule.resolvedModule.extension === '.d.ts' && noTypeDefinitions) { - result = ts.resolveJSModule(dependency, path.dirname(filename), host) || result; + const resolvedFileNameWithoutExtension = result.replace(namedModule.resolvedModule.extension, ''); + result = ts.resolveJSModule(resolvedFileNameWithoutExtension, path.dirname(filename), host) || result; } } else { const suffix = '.d.ts'; @@ -31269,7 +35641,7 @@ function commonJSLookup(options) { let {dependency} = options; if (!resolve) { - resolve = __nccwpck_require__(9283); + resolve = __nccwpck_require__(39283); } if (!dependency) { @@ -31331,7 +35703,7 @@ function commonJSLookup(options) { function resolveWebpackPath({dependency, filename, directory, webpackConfig}) { if (!webpackResolve) { - webpackResolve = __nccwpck_require__(453); + webpackResolve = __nccwpck_require__(40453); } webpackConfig = path.resolve(webpackConfig); let loadedConfig; @@ -31408,7 +35780,7 @@ function stripLoader(dependency) { -const util = __nccwpck_require__(3837); +const util = __nccwpck_require__(73837); const toRegexRange = __nccwpck_require__(1861); const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); @@ -31461,7 +35833,7 @@ const toMaxLen = (input, maxLength) => { return negative ? ('-' + input) : input; }; -const toSequence = (parts, options) => { +const toSequence = (parts, options, maxLen) => { parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); @@ -31471,11 +35843,11 @@ const toSequence = (parts, options) => { let result; if (parts.positives.length) { - positives = parts.positives.join('|'); + positives = parts.positives.map(v => toMaxLen(String(v), maxLen)).join('|'); } if (parts.negatives.length) { - negatives = `-(${prefix}${parts.negatives.join('|')})`; + negatives = `-(${prefix}${parts.negatives.map(v => toMaxLen(String(v), maxLen)).join('|')})`; } if (positives && negatives) { @@ -31573,7 +35945,7 @@ const fillNumbers = (start, end, step = 1, options = {}) => { if (options.toRegex === true) { return step > 1 - ? toSequence(parts, options) + ? toSequence(parts, options, maxLen) : toRegex(range, null, { wrap: false, ...options }); } @@ -31585,7 +35957,6 @@ const fillLetters = (start, end, step = 1, options = {}) => { return invalidRange(start, end, options); } - let format = options.transform || (val => String.fromCharCode(val)); let a = `${start}`.charCodeAt(0); let b = `${end}`.charCodeAt(0); @@ -31652,7 +36023,7 @@ module.exports = fill; /***/ }), -/***/ 7630: +/***/ 67630: /***/ ((module) => { module.exports = function flatten(list, depth) { @@ -31682,7 +36053,7 @@ module.exports = function flatten(list, depth) { /***/ }), -/***/ 6863: +/***/ 46863: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = realpath @@ -31692,13 +36063,13 @@ realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch -var fs = __nccwpck_require__(7147) +var fs = __nccwpck_require__(57147) var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) -var old = __nccwpck_require__(1734) +var old = __nccwpck_require__(71734) function newError (er) { return er && er.syscall === 'realpath' && ( @@ -31755,7 +36126,7 @@ function unmonkeypatch () { /***/ }), -/***/ 1734: +/***/ 71734: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { // Copyright Joyent, Inc. and other Node contributors. @@ -31779,9 +36150,9 @@ function unmonkeypatch () { // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -var pathModule = __nccwpck_require__(1017); +var pathModule = __nccwpck_require__(71017); var isWindows = process.platform === 'win32'; -var fs = __nccwpck_require__(7147); +var fs = __nccwpck_require__(57147); // JavaScript implementation of realpath, ported from node pre-v6 @@ -32065,7 +36436,7 @@ exports.realpath = function realpath(p, cache, cb) { /***/ }), -/***/ 9320: +/***/ 19320: /***/ ((module) => { "use strict"; @@ -32074,43 +36445,75 @@ exports.realpath = function realpath(p, cache, cb) { /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; var toStr = Object.prototype.toString; +var max = Math.max; var funcType = '[object Function]'; +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + module.exports = function bind(that) { var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } - var args = slice.call(arguments, 1); + var args = slicy(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, - args.concat(slice.call(arguments)) + concatty(args, arguments) ); if (Object(result) === result) { return result; } return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); } + return target.apply( + that, + concatty(args, arguments) + ); + }; - var boundLength = Math.max(0, target.length - args.length); + var boundLength = max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); + boundArgs[i] = '$' + i; } - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; @@ -32125,28 +36528,28 @@ module.exports = function bind(that) { /***/ }), -/***/ 8334: +/***/ 88334: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var implementation = __nccwpck_require__(9320); +var implementation = __nccwpck_require__(19320); module.exports = Function.prototype.bind || implementation; /***/ }), -/***/ 8173: +/***/ 18173: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const fs = __nccwpck_require__(7147); -const Walker = __nccwpck_require__(6695); -const types = __nccwpck_require__(6848); +const fs = __nccwpck_require__(57147); +const Walker = __nccwpck_require__(46695); +const types = __nccwpck_require__(76848); /** * Asynchronously identifies the AMD module type of the given file @@ -32242,7 +36645,7 @@ module.exports.sync = sync; /***/ }), -/***/ 2897: +/***/ 92897: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -32256,15 +36659,15 @@ exports.Z = (object) => Object /***/ }), -/***/ 4655: +/***/ 54655: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var isGlob = __nccwpck_require__(4466); -var pathPosixDirname = (__nccwpck_require__(1017).posix.dirname); -var isWin32 = (__nccwpck_require__(2037).platform)() === 'win32'; +var isGlob = __nccwpck_require__(34466); +var pathPosixDirname = (__nccwpck_require__(71017).posix.dirname); +var isWin32 = (__nccwpck_require__(22037).platform)() === 'win32'; var slash = '/'; var backslash = /\\/g; @@ -32306,7 +36709,7 @@ module.exports = function globParent(str, opts) { /***/ }), -/***/ 7625: +/***/ 47625: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { exports.setopts = setopts @@ -32321,10 +36724,10 @@ function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } -var fs = __nccwpck_require__(7147) -var path = __nccwpck_require__(1017) -var minimatch = __nccwpck_require__(3973) -var isAbsolute = __nccwpck_require__(8714) +var fs = __nccwpck_require__(57147) +var path = __nccwpck_require__(71017) +var minimatch = __nccwpck_require__(83973) +var isAbsolute = __nccwpck_require__(38714) var Minimatch = minimatch.Minimatch function alphasort (a, b) { @@ -32551,7 +36954,7 @@ function childrenIgnored (self, path) { /***/ }), -/***/ 1957: +/***/ 91957: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { // Approach: @@ -32596,20 +36999,20 @@ function childrenIgnored (self, path) { module.exports = glob -var rp = __nccwpck_require__(6863) -var minimatch = __nccwpck_require__(3973) +var rp = __nccwpck_require__(46863) +var minimatch = __nccwpck_require__(83973) var Minimatch = minimatch.Minimatch -var inherits = __nccwpck_require__(4124) -var EE = (__nccwpck_require__(2361).EventEmitter) -var path = __nccwpck_require__(1017) -var assert = __nccwpck_require__(9491) -var isAbsolute = __nccwpck_require__(8714) -var globSync = __nccwpck_require__(9010) -var common = __nccwpck_require__(7625) +var inherits = __nccwpck_require__(44124) +var EE = (__nccwpck_require__(82361).EventEmitter) +var path = __nccwpck_require__(71017) +var assert = __nccwpck_require__(39491) +var isAbsolute = __nccwpck_require__(38714) +var globSync = __nccwpck_require__(29010) +var common = __nccwpck_require__(47625) var setopts = common.setopts var ownProp = common.ownProp -var inflight = __nccwpck_require__(2492) -var util = __nccwpck_require__(3837) +var inflight = __nccwpck_require__(52492) +var util = __nccwpck_require__(73837) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored @@ -33348,21 +37751,21 @@ Glob.prototype._stat2 = function (f, abs, er, stat, cb) { /***/ }), -/***/ 9010: +/***/ 29010: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = globSync globSync.GlobSync = GlobSync -var rp = __nccwpck_require__(6863) -var minimatch = __nccwpck_require__(3973) +var rp = __nccwpck_require__(46863) +var minimatch = __nccwpck_require__(83973) var Minimatch = minimatch.Minimatch -var Glob = (__nccwpck_require__(1957).Glob) -var util = __nccwpck_require__(3837) -var path = __nccwpck_require__(1017) -var assert = __nccwpck_require__(9491) -var isAbsolute = __nccwpck_require__(8714) -var common = __nccwpck_require__(7625) +var Glob = (__nccwpck_require__(91957).Glob) +var util = __nccwpck_require__(73837) +var path = __nccwpck_require__(71017) +var assert = __nccwpck_require__(39491) +var isAbsolute = __nccwpck_require__(38714) +var common = __nccwpck_require__(47625) var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored @@ -33841,17 +38244,17 @@ GlobSync.prototype._makeAbs = function (f) { /***/ }), -/***/ 9038: +/***/ 89038: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const {promisify} = __nccwpck_require__(3837); -const fs = __nccwpck_require__(7147); -const path = __nccwpck_require__(1017); -const fastGlob = __nccwpck_require__(3664); -const gitIgnore = __nccwpck_require__(4777); -const slash = __nccwpck_require__(4111); +const {promisify} = __nccwpck_require__(73837); +const fs = __nccwpck_require__(57147); +const path = __nccwpck_require__(71017); +const fastGlob = __nccwpck_require__(43664); +const gitIgnore = __nccwpck_require__(91230); +const slash = __nccwpck_require__(97543); const DEFAULT_IGNORE = [ '**/node_modules/**', @@ -33969,18 +38372,18 @@ module.exports.sync = options => { /***/ }), -/***/ 3398: +/***/ 43398: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const fs = __nccwpck_require__(7147); -const arrayUnion = __nccwpck_require__(9600); -const merge2 = __nccwpck_require__(2578); -const fastGlob = __nccwpck_require__(3664); -const dirGlob = __nccwpck_require__(2738); -const gitignore = __nccwpck_require__(9038); -const {FilterStream, UniqueStream} = __nccwpck_require__(2408); +const fs = __nccwpck_require__(57147); +const arrayUnion = __nccwpck_require__(99600); +const merge2 = __nccwpck_require__(82578); +const fastGlob = __nccwpck_require__(43664); +const dirGlob = __nccwpck_require__(12738); +const gitignore = __nccwpck_require__(89038); +const {FilterStream, UniqueStream} = __nccwpck_require__(32408); const DEFAULT_FILTER = () => false; @@ -34158,12 +38561,12 @@ module.exports.gitignore = gitignore; /***/ }), -/***/ 2408: +/***/ 32408: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const {Transform} = __nccwpck_require__(2781); +const {Transform} = __nccwpck_require__(12781); class ObjectTransform extends Transform { constructor() { @@ -34212,7 +38615,7 @@ module.exports = { /***/ }), -/***/ 9391: +/***/ 69391: /***/ (function(module) { (function webpackUniversalModuleDefinition(root, factory) { @@ -56648,7 +61051,7 @@ return /******/ (function(modules) { // webpackBootstrap /***/ }), -/***/ 7356: +/***/ 67356: /***/ ((module) => { "use strict"; @@ -56679,15 +61082,15 @@ function clone (obj) { /***/ }), -/***/ 7758: +/***/ 77758: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var fs = __nccwpck_require__(7147) -var polyfills = __nccwpck_require__(263) -var legacy = __nccwpck_require__(3086) -var clone = __nccwpck_require__(7356) +var fs = __nccwpck_require__(57147) +var polyfills = __nccwpck_require__(20263) +var legacy = __nccwpck_require__(73086) +var clone = __nccwpck_require__(67356) -var util = __nccwpck_require__(3837) +var util = __nccwpck_require__(73837) /* istanbul ignore next - node 0.x polyfill */ var gracefulQueue @@ -56768,7 +61171,7 @@ if (!fs[gracefulQueue]) { if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { process.on('exit', function() { debug(fs[gracefulQueue]) - __nccwpck_require__(9491).equal(fs[gracefulQueue].length, 0) + __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) }) } } @@ -57134,10 +61537,10 @@ function retry () { /***/ }), -/***/ 3086: +/***/ 73086: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Stream = (__nccwpck_require__(2781).Stream) +var Stream = (__nccwpck_require__(12781).Stream) module.exports = legacy @@ -57259,10 +61662,10 @@ function legacy (fs) { /***/ }), -/***/ 263: +/***/ 20263: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var constants = __nccwpck_require__(2057) +var constants = __nccwpck_require__(22057) var origCwd = process.cwd var cwd = null @@ -57365,7 +61768,7 @@ function patch (fs) { var backoff = 0; fs$rename(from, to, function CB (er) { if (er - && (er.code === "EACCES" || er.code === "EPERM") + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 60000) { setTimeout(function() { fs.stat(to, function (stater, st) { @@ -57621,20 +62024,23 @@ function patch (fs) { /***/ }), -/***/ 6339: +/***/ 62157: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var bind = __nccwpck_require__(8334); +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = __nccwpck_require__(88334); -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); /***/ }), -/***/ 4777: +/***/ 91230: /***/ ((module) => { // A simple implementation of make-array @@ -57648,6 +62054,7 @@ const EMPTY = '' const SPACE = ' ' const ESCAPE = '\\' const REGEX_TEST_BLANK_LINE = /^\s+$/ +const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/ const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ const REGEX_SPLITALL_CRLF = /\r?\n/g @@ -57659,10 +62066,14 @@ const REGEX_SPLITALL_CRLF = /\r?\n/g const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ const SLASH = '/' -const KEY_IGNORE = typeof Symbol !== 'undefined' - ? Symbol.for('node-ignore') - /* istanbul ignore next */ - : 'node-ignore' + +// Do not use ternary expression here, since "istanbul ignore next" is buggy +let TMP_KEY_IGNORE = 'node-ignore' +/* istanbul ignore else */ +if (typeof Symbol !== 'undefined') { + TMP_KEY_IGNORE = Symbol.for('node-ignore') +} +const KEY_IGNORE = TMP_KEY_IGNORE const define = (object, key, value) => Object.defineProperty(object, key, {value}) @@ -57701,21 +62112,38 @@ const cleanRangeBackSlash = slashes => { // '`foo/`' should not continue with the '`..`' const REPLACERS = [ + [ + // remove BOM + // TODO: + // Other similar zero-width characters? + /^\uFEFF/, + () => EMPTY + ], + // > Trailing spaces are ignored unless they are quoted with backslash ("\") [ // (a\ ) -> (a ) // (a ) -> (a) + // (a ) -> (a) // (a \ ) -> (a ) - /\\?\s+$/, - match => match.indexOf('\\') === 0 - ? SPACE - : EMPTY + /((?:\\\\)*?)(\\?\s+)$/, + (_, m1, m2) => m1 + ( + m2.indexOf('\\') === 0 + ? SPACE + : EMPTY + ) ], // replace (\ ) with ' ' + // (\ ) -> ' ' + // (\\ ) -> '\\ ' + // (\\\ ) -> '\\ ' [ - /\\\s/g, - () => SPACE + /(\\+?)\s/g, + (_, m1) => { + const {length} = m1 + return m1.slice(0, length - length % 2) + SPACE + } ], // Escape metacharacters @@ -57829,18 +62257,27 @@ const REPLACERS = [ : '\\/.+' ], - // intermediate wildcards + // normal intermediate wildcards [ // Never replace escaped '*' // ignore rule '\*' will match the path '*' // 'abc.*/' -> go - // 'abc.*' -> skip this rule - /(^|[^\\]+)\\\*(?=.+)/g, + // 'abc.*' -> skip this rule, + // coz trailing single wildcard will be handed by [trailing wildcard] + /(^|[^\\]+)(\\\*)+(?=.+)/g, // '*.js' matches '.js' // '*.js' doesn't match 'abc' - (_, p1) => `${p1}[^\\/]*` + (_, p1, p2) => { + // 1. + // > An asterisk "*" matches anything except a slash. + // 2. + // > Other consecutive asterisks are considered regular asterisks + // > and will match according to the previous rules. + const unescaped = p2.replace(/\\\*/g, '[^\\/]*') + return p1 + unescaped + } ], [ @@ -57934,7 +62371,8 @@ const makeRegex = (pattern, ignoreCase) => { if (!source) { source = REPLACERS.reduce( - (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + (prev, [matcher, replacer]) => + prev.replace(matcher, replacer.bind(pattern)), pattern ) regexCache[pattern] = source @@ -57951,6 +62389,7 @@ const isString = subject => typeof subject === 'string' const checkPattern = pattern => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) + && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) // > A line starting with # serves as a comment. && pattern.indexOf('#') !== 0 @@ -58216,7 +62655,7 @@ module.exports = factory // Windows // -------------------------------------------------------------- -/* istanbul ignore if */ +/* istanbul ignore if */ if ( // Detect `process` so that it can run in browsers. typeof process !== 'undefined' @@ -58244,7 +62683,7 @@ if ( /***/ }), -/***/ 5977: +/***/ 65977: /***/ ((module) => { module.exports = function (ary, item) { @@ -58257,10 +62696,10 @@ module.exports = function (ary, item) { /***/ }), -/***/ 2492: +/***/ 52492: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var wrappy = __nccwpck_require__(2940) +var wrappy = __nccwpck_require__(62940) var reqs = Object.create(null) var once = __nccwpck_require__(1223) @@ -58318,11 +62757,11 @@ function slice (args) { /***/ }), -/***/ 4124: +/***/ 44124: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { try { - var util = __nccwpck_require__(3837); + var util = __nccwpck_require__(73837); /* istanbul ignore next */ if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; @@ -58368,13 +62807,13 @@ if (typeof Object.create === 'function') { /***/ }), -/***/ 6873: +/***/ 56873: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var has = __nccwpck_require__(6339); +var hasOwn = __nccwpck_require__(62157); function specifierIncluded(current, specifier) { var nodeParts = current.split('.'); @@ -58436,16 +62875,16 @@ function versionIncluded(nodeVersion, specifierValue) { return matchesRange(current, specifierValue); } -var data = __nccwpck_require__(6151); +var data = __nccwpck_require__(66151); module.exports = function isCore(x, nodeVersion) { - return has(data, x) && versionIncluded(nodeVersion, data[x]); + return hasOwn(data, x) && versionIncluded(nodeVersion, data[x]); }; /***/ }), -/***/ 6435: +/***/ 76435: /***/ ((module) => { /*! @@ -58472,7 +62911,7 @@ module.exports = function isExtglob(str) { /***/ }), -/***/ 4466: +/***/ 34466: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /*! @@ -58482,7 +62921,7 @@ module.exports = function isExtglob(str) { * Released under the MIT License. */ -var isExtglob = __nccwpck_require__(6435); +var isExtglob = __nccwpck_require__(76435); var chars = { '{': '}', '(': ')', '[': ']'}; var strictCheck = function(str) { if (str[0] === '!') { @@ -58629,7 +63068,7 @@ module.exports = function isGlob(str, options) { /***/ }), -/***/ 5680: +/***/ 75680: /***/ ((module) => { "use strict"; @@ -58655,7 +63094,7 @@ module.exports = function(num) { /***/ }), -/***/ 1389: +/***/ 51389: /***/ ((module) => { "use strict"; @@ -58680,10 +63119,10 @@ module.exports = function (re) { /***/ }), -/***/ 2837: +/***/ 82837: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var util = __nccwpck_require__(3837); +var util = __nccwpck_require__(73837); /** * @param {String} filename @@ -58700,7 +63139,7 @@ module.exports = function (filename) { /***/ }), -/***/ 239: +/***/ 70239: /***/ ((module) => { @@ -58754,31 +63193,31 @@ function isUrl(string){ /***/ }), -/***/ 6904: +/***/ 86904: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));var _parse=__nccwpck_require__(7583);var _parse2=_interopRequireDefault(_parse);var _stringify=__nccwpck_require__(749);var _stringify2=_interopRequireDefault(_stringify);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports["default"]={parse:_parse2.default,stringify:_stringify2.default};module.exports=exports['default']; +Object.defineProperty(exports, "__esModule", ({value:true}));var _parse=__nccwpck_require__(47583);var _parse2=_interopRequireDefault(_parse);var _stringify=__nccwpck_require__(10749);var _stringify2=_interopRequireDefault(_stringify);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports["default"]={parse:_parse2.default,stringify:_stringify2.default};module.exports=exports['default']; /***/ }), -/***/ 7583: +/***/ 47583: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));var _typeof=typeof Symbol==='function'&&typeof Symbol.iterator==='symbol'?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==='function'&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};exports["default"]=parse;var _util=__nccwpck_require__(7393);var util=_interopRequireWildcard(_util);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}var source=void 0;var parseState=void 0;var stack=void 0;var pos=void 0;var line=void 0;var column=void 0;var token=void 0;var key=void 0;var root=void 0;function parse(text,reviver){source=String(text);parseState='start';stack=[];pos=0;line=1;column=0;token=undefined;key=undefined;root=undefined;do{token=lex();parseStates[parseState]()}while(token.type!=='eof');if(typeof reviver==='function'){return internalize({'':root},'',reviver)}return root}function internalize(holder,name,reviver){var value=holder[name];if(value!=null&&(typeof value==='undefined'?'undefined':_typeof(value))==='object'){for(var _key in value){var replacement=internalize(value,_key,reviver);if(replacement===undefined){delete value[_key]}else{value[_key]=replacement}}}return reviver.call(holder,name,value)}var lexState=void 0;var buffer=void 0;var doubleQuote=void 0;var _sign=void 0;var c=void 0;function lex(){lexState='default';buffer='';doubleQuote=false;_sign=1;for(;;){c=peek();var _token=lexStates[lexState]();if(_token){return _token}}}function peek(){if(source[pos]){return String.fromCodePoint(source.codePointAt(pos))}}function read(){var c=peek();if(c==='\n'){line++;column=0}else if(c){column+=c.length}else{column++}if(c){pos+=c.length}return c}var lexStates={default:function _default(){switch(c){case'\t':case'\x0B':case'\f':case' ':case'\xA0':case'\uFEFF':case'\n':case'\r':case'\u2028':case'\u2029':read();return;case'/':read();lexState='comment';return;case undefined:read();return newToken('eof');}if(util.isSpaceSeparator(c)){read();return}return lexStates[parseState]()},comment:function comment(){switch(c){case'*':read();lexState='multiLineComment';return;case'/':read();lexState='singleLineComment';return;}throw invalidChar(read())},multiLineComment:function multiLineComment(){switch(c){case'*':read();lexState='multiLineCommentAsterisk';return;case undefined:throw invalidChar(read());}read()},multiLineCommentAsterisk:function multiLineCommentAsterisk(){switch(c){case'*':read();return;case'/':read();lexState='default';return;case undefined:throw invalidChar(read());}read();lexState='multiLineComment'},singleLineComment:function singleLineComment(){switch(c){case'\n':case'\r':case'\u2028':case'\u2029':read();lexState='default';return;case undefined:read();return newToken('eof');}read()},value:function value(){switch(c){case'{':case'[':return newToken('punctuator',read());case'n':read();literal('ull');return newToken('null',null);case't':read();literal('rue');return newToken('boolean',true);case'f':read();literal('alse');return newToken('boolean',false);case'-':case'+':if(read()==='-'){_sign=-1}lexState='sign';return;case'.':buffer=read();lexState='decimalPointLeading';return;case'0':buffer=read();lexState='zero';return;case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':buffer=read();lexState='decimalInteger';return;case'I':read();literal('nfinity');return newToken('numeric',Infinity);case'N':read();literal('aN');return newToken('numeric',NaN);case'"':case'\'':doubleQuote=read()==='"';buffer='';lexState='string';return;}throw invalidChar(read())},identifierNameStartEscape:function identifierNameStartEscape(){if(c!=='u'){throw invalidChar(read())}read();var u=unicodeEscape();switch(u){case'$':case'_':break;default:if(!util.isIdStartChar(u)){throw invalidIdentifier()}break;}buffer+=u;lexState='identifierName'},identifierName:function identifierName(){switch(c){case'$':case'_':case'\u200C':case'\u200D':buffer+=read();return;case'\\':read();lexState='identifierNameEscape';return;}if(util.isIdContinueChar(c)){buffer+=read();return}return newToken('identifier',buffer)},identifierNameEscape:function identifierNameEscape(){if(c!=='u'){throw invalidChar(read())}read();var u=unicodeEscape();switch(u){case'$':case'_':case'\u200C':case'\u200D':break;default:if(!util.isIdContinueChar(u)){throw invalidIdentifier()}break;}buffer+=u;lexState='identifierName'},sign:function sign(){switch(c){case'.':buffer=read();lexState='decimalPointLeading';return;case'0':buffer=read();lexState='zero';return;case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':buffer=read();lexState='decimalInteger';return;case'I':read();literal('nfinity');return newToken('numeric',_sign*Infinity);case'N':read();literal('aN');return newToken('numeric',NaN);}throw invalidChar(read())},zero:function zero(){switch(c){case'.':buffer+=read();lexState='decimalPoint';return;case'e':case'E':buffer+=read();lexState='decimalExponent';return;case'x':case'X':buffer+=read();lexState='hexadecimal';return;}return newToken('numeric',_sign*0)},decimalInteger:function decimalInteger(){switch(c){case'.':buffer+=read();lexState='decimalPoint';return;case'e':case'E':buffer+=read();lexState='decimalExponent';return;}if(util.isDigit(c)){buffer+=read();return}return newToken('numeric',_sign*Number(buffer))},decimalPointLeading:function decimalPointLeading(){if(util.isDigit(c)){buffer+=read();lexState='decimalFraction';return}throw invalidChar(read())},decimalPoint:function decimalPoint(){switch(c){case'e':case'E':buffer+=read();lexState='decimalExponent';return;}if(util.isDigit(c)){buffer+=read();lexState='decimalFraction';return}return newToken('numeric',_sign*Number(buffer))},decimalFraction:function decimalFraction(){switch(c){case'e':case'E':buffer+=read();lexState='decimalExponent';return;}if(util.isDigit(c)){buffer+=read();return}return newToken('numeric',_sign*Number(buffer))},decimalExponent:function decimalExponent(){switch(c){case'+':case'-':buffer+=read();lexState='decimalExponentSign';return;}if(util.isDigit(c)){buffer+=read();lexState='decimalExponentInteger';return}throw invalidChar(read())},decimalExponentSign:function decimalExponentSign(){if(util.isDigit(c)){buffer+=read();lexState='decimalExponentInteger';return}throw invalidChar(read())},decimalExponentInteger:function decimalExponentInteger(){if(util.isDigit(c)){buffer+=read();return}return newToken('numeric',_sign*Number(buffer))},hexadecimal:function hexadecimal(){if(util.isHexDigit(c)){buffer+=read();lexState='hexadecimalInteger';return}throw invalidChar(read())},hexadecimalInteger:function hexadecimalInteger(){if(util.isHexDigit(c)){buffer+=read();return}return newToken('numeric',_sign*Number(buffer))},string:function string(){switch(c){case'\\':read();buffer+=escape();return;case'"':if(doubleQuote){read();return newToken('string',buffer)}buffer+=read();return;case'\'':if(!doubleQuote){read();return newToken('string',buffer)}buffer+=read();return;case'\n':case'\r':throw invalidChar(read());case'\u2028':case'\u2029':separatorChar(c);break;case undefined:throw invalidChar(read());}buffer+=read()},start:function start(){switch(c){case'{':case'[':return newToken('punctuator',read());}lexState='value'},beforePropertyName:function beforePropertyName(){switch(c){case'$':case'_':buffer=read();lexState='identifierName';return;case'\\':read();lexState='identifierNameStartEscape';return;case'}':return newToken('punctuator',read());case'"':case'\'':doubleQuote=read()==='"';lexState='string';return;}if(util.isIdStartChar(c)){buffer+=read();lexState='identifierName';return}throw invalidChar(read())},afterPropertyName:function afterPropertyName(){if(c===':'){return newToken('punctuator',read())}throw invalidChar(read())},beforePropertyValue:function beforePropertyValue(){lexState='value'},afterPropertyValue:function afterPropertyValue(){switch(c){case',':case'}':return newToken('punctuator',read());}throw invalidChar(read())},beforeArrayValue:function beforeArrayValue(){if(c===']'){return newToken('punctuator',read())}lexState='value'},afterArrayValue:function afterArrayValue(){switch(c){case',':case']':return newToken('punctuator',read());}throw invalidChar(read())},end:function end(){throw invalidChar(read())}};function newToken(type,value){return{type:type,value:value,line:line,column:column}}function literal(s){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=s[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var _c=_step.value;var p=peek();if(p!==_c){throw invalidChar(read())}read()}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}function escape(){var c=peek();switch(c){case'b':read();return'\b';case'f':read();return'\f';case'n':read();return'\n';case'r':read();return'\r';case't':read();return'\t';case'v':read();return'\x0B';case'0':read();if(util.isDigit(peek())){throw invalidChar(read())}return'\0';case'x':read();return hexEscape();case'u':read();return unicodeEscape();case'\n':case'\u2028':case'\u2029':read();return'';case'\r':read();if(peek()==='\n'){read()}return'';case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':throw invalidChar(read());case undefined:throw invalidChar(read());}return read()}function hexEscape(){var buffer='';var c=peek();if(!util.isHexDigit(c)){throw invalidChar(read())}buffer+=read();c=peek();if(!util.isHexDigit(c)){throw invalidChar(read())}buffer+=read();return String.fromCodePoint(parseInt(buffer,16))}function unicodeEscape(){var buffer='';var count=4;while(count-->0){var _c2=peek();if(!util.isHexDigit(_c2)){throw invalidChar(read())}buffer+=read()}return String.fromCodePoint(parseInt(buffer,16))}var parseStates={start:function start(){if(token.type==='eof'){throw invalidEOF()}push()},beforePropertyName:function beforePropertyName(){switch(token.type){case'identifier':case'string':key=token.value;parseState='afterPropertyName';return;case'punctuator':pop();return;case'eof':throw invalidEOF();}},afterPropertyName:function afterPropertyName(){if(token.type==='eof'){throw invalidEOF()}parseState='beforePropertyValue'},beforePropertyValue:function beforePropertyValue(){if(token.type==='eof'){throw invalidEOF()}push()},beforeArrayValue:function beforeArrayValue(){if(token.type==='eof'){throw invalidEOF()}if(token.type==='punctuator'&&token.value===']'){pop();return}push()},afterPropertyValue:function afterPropertyValue(){if(token.type==='eof'){throw invalidEOF()}switch(token.value){case',':parseState='beforePropertyName';return;case'}':pop();}},afterArrayValue:function afterArrayValue(){if(token.type==='eof'){throw invalidEOF()}switch(token.value){case',':parseState='beforeArrayValue';return;case']':pop();}},end:function end(){}};function push(){var value=void 0;switch(token.type){case'punctuator':switch(token.value){case'{':value={};break;case'[':value=[];break;}break;case'null':case'boolean':case'numeric':case'string':value=token.value;break;}if(root===undefined){root=value}else{var parent=stack[stack.length-1];if(Array.isArray(parent)){parent.push(value)}else{parent[key]=value}}if(value!==null&&(typeof value==='undefined'?'undefined':_typeof(value))==='object'){stack.push(value);if(Array.isArray(value)){parseState='beforeArrayValue'}else{parseState='beforePropertyName'}}else{var current=stack[stack.length-1];if(current==null){parseState='end'}else if(Array.isArray(current)){parseState='afterArrayValue'}else{parseState='afterPropertyValue'}}}function pop(){stack.pop();var current=stack[stack.length-1];if(current==null){parseState='end'}else if(Array.isArray(current)){parseState='afterArrayValue'}else{parseState='afterPropertyValue'}}function invalidChar(c){if(c===undefined){return syntaxError('JSON5: invalid end of input at '+line+':'+column)}return syntaxError('JSON5: invalid character \''+formatChar(c)+'\' at '+line+':'+column)}function invalidEOF(){return syntaxError('JSON5: invalid end of input at '+line+':'+column)}function invalidIdentifier(){column-=5;return syntaxError('JSON5: invalid identifier character at '+line+':'+column)}function separatorChar(c){console.warn('JSON5: \''+c+'\' is not valid ECMAScript; consider escaping')}function formatChar(c){var replacements={'\'':'\\\'','"':'\\"','\\':'\\\\','\b':'\\b','\f':'\\f','\n':'\\n','\r':'\\r','\t':'\\t','\x0B':'\\v','\0':'\\0','\u2028':'\\u2028','\u2029':'\\u2029'};if(replacements[c]){return replacements[c]}if(c<' '){var hexString=c.charCodeAt(0).toString(16);return'\\x'+('00'+hexString).substring(hexString.length)}return c}function syntaxError(message){var err=new SyntaxError(message);err.lineNumber=line;err.columnNumber=column;return err}module.exports=exports['default']; +Object.defineProperty(exports, "__esModule", ({value:true}));var _typeof=typeof Symbol==='function'&&typeof Symbol.iterator==='symbol'?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==='function'&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};exports["default"]=parse;var _util=__nccwpck_require__(67393);var util=_interopRequireWildcard(_util);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}var source=void 0;var parseState=void 0;var stack=void 0;var pos=void 0;var line=void 0;var column=void 0;var token=void 0;var key=void 0;var root=void 0;function parse(text,reviver){source=String(text);parseState='start';stack=[];pos=0;line=1;column=0;token=undefined;key=undefined;root=undefined;do{token=lex();parseStates[parseState]()}while(token.type!=='eof');if(typeof reviver==='function'){return internalize({'':root},'',reviver)}return root}function internalize(holder,name,reviver){var value=holder[name];if(value!=null&&(typeof value==='undefined'?'undefined':_typeof(value))==='object'){if(Array.isArray(value)){for(var i=0;i0){var _c2=peek();if(!util.isHexDigit(_c2)){throw invalidChar(read())}buffer+=read()}return String.fromCodePoint(parseInt(buffer,16))}var parseStates={start:function start(){if(token.type==='eof'){throw invalidEOF()}push()},beforePropertyName:function beforePropertyName(){switch(token.type){case'identifier':case'string':key=token.value;parseState='afterPropertyName';return;case'punctuator':pop();return;case'eof':throw invalidEOF();}},afterPropertyName:function afterPropertyName(){if(token.type==='eof'){throw invalidEOF()}parseState='beforePropertyValue'},beforePropertyValue:function beforePropertyValue(){if(token.type==='eof'){throw invalidEOF()}push()},beforeArrayValue:function beforeArrayValue(){if(token.type==='eof'){throw invalidEOF()}if(token.type==='punctuator'&&token.value===']'){pop();return}push()},afterPropertyValue:function afterPropertyValue(){if(token.type==='eof'){throw invalidEOF()}switch(token.value){case',':parseState='beforePropertyName';return;case'}':pop();}},afterArrayValue:function afterArrayValue(){if(token.type==='eof'){throw invalidEOF()}switch(token.value){case',':parseState='beforeArrayValue';return;case']':pop();}},end:function end(){}};function push(){var value=void 0;switch(token.type){case'punctuator':switch(token.value){case'{':value={};break;case'[':value=[];break;}break;case'null':case'boolean':case'numeric':case'string':value=token.value;break;}if(root===undefined){root=value}else{var parent=stack[stack.length-1];if(Array.isArray(parent)){parent.push(value)}else{Object.defineProperty(parent,key,{value:value,writable:true,enumerable:true,configurable:true})}}if(value!==null&&(typeof value==='undefined'?'undefined':_typeof(value))==='object'){stack.push(value);if(Array.isArray(value)){parseState='beforeArrayValue'}else{parseState='beforePropertyName'}}else{var current=stack[stack.length-1];if(current==null){parseState='end'}else if(Array.isArray(current)){parseState='afterArrayValue'}else{parseState='afterPropertyValue'}}}function pop(){stack.pop();var current=stack[stack.length-1];if(current==null){parseState='end'}else if(Array.isArray(current)){parseState='afterArrayValue'}else{parseState='afterPropertyValue'}}function invalidChar(c){if(c===undefined){return syntaxError('JSON5: invalid end of input at '+line+':'+column)}return syntaxError('JSON5: invalid character \''+formatChar(c)+'\' at '+line+':'+column)}function invalidEOF(){return syntaxError('JSON5: invalid end of input at '+line+':'+column)}function invalidIdentifier(){column-=5;return syntaxError('JSON5: invalid identifier character at '+line+':'+column)}function separatorChar(c){console.warn('JSON5: \''+c+'\' is not valid ECMAScript; consider escaping')}function formatChar(c){var replacements={'\'':'\\\'','"':'\\"','\\':'\\\\','\b':'\\b','\f':'\\f','\n':'\\n','\r':'\\r','\t':'\\t','\x0B':'\\v','\0':'\\0','\u2028':'\\u2028','\u2029':'\\u2029'};if(replacements[c]){return replacements[c]}if(c<' '){var hexString=c.charCodeAt(0).toString(16);return'\\x'+('00'+hexString).substring(hexString.length)}return c}function syntaxError(message){var err=new SyntaxError(message);err.lineNumber=line;err.columnNumber=column;return err}module.exports=exports['default']; /***/ }), -/***/ 749: +/***/ 10749: /***/ ((module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));var _typeof=typeof Symbol==='function'&&typeof Symbol.iterator==='symbol'?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==='function'&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};exports["default"]=stringify;var _util=__nccwpck_require__(7393);var util=_interopRequireWildcard(_util);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function stringify(value,replacer,space){var stack=[];var indent='';var propertyList=void 0;var replacerFunc=void 0;var gap='';var quote=void 0;if(replacer!=null&&(typeof replacer==='undefined'?'undefined':_typeof(replacer))==='object'&&!Array.isArray(replacer)){space=replacer.space;quote=replacer.quote;replacer=replacer.replacer}if(typeof replacer==='function'){replacerFunc=replacer}else if(Array.isArray(replacer)){propertyList=[];var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=replacer[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var v=_step.value;var item=void 0;if(typeof v==='string'){item=v}else if(typeof v==='number'||v instanceof String||v instanceof Number){item=String(v)}if(item!==undefined&&propertyList.indexOf(item)<0){propertyList.push(item)}}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}if(space instanceof Number){space=Number(space)}else if(space instanceof String){space=String(space)}if(typeof space==='number'){if(space>0){space=Math.min(10,Math.floor(space));gap=' '.substr(0,space)}}else if(typeof space==='string'){gap=space.substr(0,10)}return serializeProperty('',{'':value});function serializeProperty(key,holder){var value=holder[key];if(value!=null){if(typeof value.toJSON5==='function'){value=value.toJSON5(key)}else if(typeof value.toJSON==='function'){value=value.toJSON(key)}}if(replacerFunc){value=replacerFunc.call(holder,key,value)}if(value instanceof Number){value=Number(value)}else if(value instanceof String){value=String(value)}else if(value instanceof Boolean){value=value.valueOf()}switch(value){case null:return'null';case true:return'true';case false:return'false';}if(typeof value==='string'){return quoteString(value,false)}if(typeof value==='number'){return String(value)}if((typeof value==='undefined'?'undefined':_typeof(value))==='object'){return Array.isArray(value)?serializeArray(value):serializeObject(value)}return undefined}function quoteString(value){var quotes={'\'':0.1,'"':0.2};var replacements={'\'':'\\\'','"':'\\"','\\':'\\\\','\b':'\\b','\f':'\\f','\n':'\\n','\r':'\\r','\t':'\\t','\x0B':'\\v','\0':'\\0','\u2028':'\\u2028','\u2029':'\\u2029'};var product='';var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=value[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var c=_step2.value;switch(c){case'\'':case'"':quotes[c]++;product+=c;continue;}if(replacements[c]){product+=replacements[c];continue}if(c<' '){var hexString=c.charCodeAt(0).toString(16);product+='\\x'+('00'+hexString).substring(hexString.length);continue}product+=c}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}var quoteChar=quote||Object.keys(quotes).reduce(function(a,b){return quotes[a]=0){throw TypeError('Converting circular structure to JSON5')}stack.push(value);var stepback=indent;indent=indent+gap;var keys=propertyList||Object.keys(value);var partial=[];var _iteratorNormalCompletion3=true;var _didIteratorError3=false;var _iteratorError3=undefined;try{for(var _iterator3=keys[Symbol.iterator](),_step3;!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=true){var key=_step3.value;var propertyString=serializeProperty(key,value);if(propertyString!==undefined){var member=serializeKey(key)+':';if(gap!==''){member+=' '}member+=propertyString;partial.push(member)}}}catch(err){_didIteratorError3=true;_iteratorError3=err}finally{try{if(!_iteratorNormalCompletion3&&_iterator3.return){_iterator3.return()}}finally{if(_didIteratorError3){throw _iteratorError3}}}var final=void 0;if(partial.length===0){final='{}'}else{var properties=void 0;if(gap===''){properties=partial.join(',');final='{'+properties+'}'}else{var separator=',\n'+indent;properties=partial.join(separator);final='{\n'+indent+properties+',\n'+stepback+'}'}}stack.pop();indent=stepback;return final}function serializeKey(key){if(key.length===0){return quoteString(key,true)}var firstChar=String.fromCodePoint(key.codePointAt(0));if(!util.isIdStartChar(firstChar)){return quoteString(key,true)}for(var i=firstChar.length;i=0){throw TypeError('Converting circular structure to JSON5')}stack.push(value);var stepback=indent;indent=indent+gap;var partial=[];for(var i=0;i0){space=Math.min(10,Math.floor(space));gap=' '.substr(0,space)}}else if(typeof space==='string'){gap=space.substr(0,10)}return serializeProperty('',{'':value});function serializeProperty(key,holder){var value=holder[key];if(value!=null){if(typeof value.toJSON5==='function'){value=value.toJSON5(key)}else if(typeof value.toJSON==='function'){value=value.toJSON(key)}}if(replacerFunc){value=replacerFunc.call(holder,key,value)}if(value instanceof Number){value=Number(value)}else if(value instanceof String){value=String(value)}else if(value instanceof Boolean){value=value.valueOf()}switch(value){case null:return'null';case true:return'true';case false:return'false';}if(typeof value==='string'){return quoteString(value,false)}if(typeof value==='number'){return String(value)}if((typeof value==='undefined'?'undefined':_typeof(value))==='object'){return Array.isArray(value)?serializeArray(value):serializeObject(value)}return undefined}function quoteString(value){var quotes={'\'':0.1,'"':0.2};var replacements={'\'':'\\\'','"':'\\"','\\':'\\\\','\b':'\\b','\f':'\\f','\n':'\\n','\r':'\\r','\t':'\\t','\x0B':'\\v','\0':'\\0','\u2028':'\\u2028','\u2029':'\\u2029'};var product='';var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=value[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var c=_step2.value;switch(c){case'\'':case'"':quotes[c]++;product+=c;continue;}if(replacements[c]){product+=replacements[c];continue}if(c<' '){var hexString=c.charCodeAt(0).toString(16);product+='\\x'+('00'+hexString).substring(hexString.length);continue}product+=c}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}var quoteChar=quote||Object.keys(quotes).reduce(function(a,b){return quotes[a]=0){throw TypeError('Converting circular structure to JSON5')}stack.push(value);var stepback=indent;indent=indent+gap;var keys=propertyList||Object.keys(value);var partial=[];var _iteratorNormalCompletion3=true;var _didIteratorError3=false;var _iteratorError3=undefined;try{for(var _iterator3=keys[Symbol.iterator](),_step3;!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=true){var key=_step3.value;var propertyString=serializeProperty(key,value);if(propertyString!==undefined){var member=serializeKey(key)+':';if(gap!==''){member+=' '}member+=propertyString;partial.push(member)}}}catch(err){_didIteratorError3=true;_iteratorError3=err}finally{try{if(!_iteratorNormalCompletion3&&_iterator3.return){_iterator3.return()}}finally{if(_didIteratorError3){throw _iteratorError3}}}var final=void 0;if(partial.length===0){final='{}'}else{var properties=void 0;if(gap===''){properties=partial.join(',');final='{'+properties+'}'}else{var separator=',\n'+indent;properties=partial.join(separator);final='{\n'+indent+properties+',\n'+stepback+'}'}}stack.pop();indent=stepback;return final}function serializeKey(key){if(key.length===0){return quoteString(key,true)}var firstChar=String.fromCodePoint(key.codePointAt(0));if(!util.isIdStartChar(firstChar)){return quoteString(key,true)}for(var i=firstChar.length;i=0){throw TypeError('Converting circular structure to JSON5')}stack.push(value);var stepback=indent;indent=indent+gap;var partial=[];for(var i=0;i { "use strict"; @@ -58786,15 +63225,15 @@ Object.defineProperty(exports, "__esModule", ({value:true}));var Space_Separator /***/ }), -/***/ 7393: +/***/ 67393: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({value:true}));exports.isSpaceSeparator=isSpaceSeparator;exports.isIdStartChar=isIdStartChar;exports.isIdContinueChar=isIdContinueChar;exports.isDigit=isDigit;exports.isHexDigit=isHexDigit;var _unicode=__nccwpck_require__(1927);var unicode=_interopRequireWildcard(_unicode);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function isSpaceSeparator(c){return unicode.Space_Separator.test(c)}function isIdStartChar(c){return c>='a'&&c<='z'||c>='A'&&c<='Z'||c==='$'||c==='_'||unicode.ID_Start.test(c)}function isIdContinueChar(c){return c>='a'&&c<='z'||c>='A'&&c<='Z'||c>='0'&&c<='9'||c==='$'||c==='_'||c==='\u200C'||c==='\u200D'||unicode.ID_Continue.test(c)}function isDigit(c){return /[0-9]/.test(c)}function isHexDigit(c){return /[0-9A-Fa-f]/.test(c)} +Object.defineProperty(exports, "__esModule", ({value:true}));exports.isSpaceSeparator=isSpaceSeparator;exports.isIdStartChar=isIdStartChar;exports.isIdContinueChar=isIdContinueChar;exports.isDigit=isDigit;exports.isHexDigit=isHexDigit;var _unicode=__nccwpck_require__(81927);var unicode=_interopRequireWildcard(_unicode);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function isSpaceSeparator(c){return unicode.Space_Separator.test(c)}function isIdStartChar(c){return c>='a'&&c<='z'||c>='A'&&c<='Z'||c==='$'||c==='_'||unicode.ID_Start.test(c)}function isIdContinueChar(c){return c>='a'&&c<='z'||c>='A'&&c<='Z'||c>='0'&&c<='9'||c==='$'||c==='_'||c==='\u200C'||c==='\u200D'||unicode.ID_Continue.test(c)}function isDigit(c){return /[0-9]/.test(c)}function isHexDigit(c){return /[0-9A-Fa-f]/.test(c)} /***/ }), -/***/ 9764: +/***/ 89764: /***/ ((module) => { /** @@ -59971,7 +64410,7 @@ module.exports = difference; /***/ }), -/***/ 3566: +/***/ 63566: /***/ ((module) => { /** @@ -60876,349 +65315,7 @@ module.exports = uniqWith; /***/ }), -/***/ 7129: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -// A linked list to keep track of recently-used-ness -const Yallist = __nccwpck_require__(665) - -const MAX = Symbol('max') -const LENGTH = Symbol('length') -const LENGTH_CALCULATOR = Symbol('lengthCalculator') -const ALLOW_STALE = Symbol('allowStale') -const MAX_AGE = Symbol('maxAge') -const DISPOSE = Symbol('dispose') -const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') -const LRU_LIST = Symbol('lruList') -const CACHE = Symbol('cache') -const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') - -const naiveLength = () => 1 - -// lruList is a yallist where the head is the youngest -// item, and the tail is the oldest. the list contains the Hit -// objects as the entries. -// Each Hit object has a reference to its Yallist.Node. This -// never changes. -// -// cache is a Map (or PseudoMap) that matches the keys to -// the Yallist.Node object. -class LRUCache { - constructor (options) { - if (typeof options === 'number') - options = { max: options } - - if (!options) - options = {} - - if (options.max && (typeof options.max !== 'number' || options.max < 0)) - throw new TypeError('max must be a non-negative number') - // Kind of weird to have a default max of Infinity, but oh well. - const max = this[MAX] = options.max || Infinity - - const lc = options.length || naiveLength - this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc - this[ALLOW_STALE] = options.stale || false - if (options.maxAge && typeof options.maxAge !== 'number') - throw new TypeError('maxAge must be a number') - this[MAX_AGE] = options.maxAge || 0 - this[DISPOSE] = options.dispose - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false - this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false - this.reset() - } - - // resize the cache when the max changes. - set max (mL) { - if (typeof mL !== 'number' || mL < 0) - throw new TypeError('max must be a non-negative number') - - this[MAX] = mL || Infinity - trim(this) - } - get max () { - return this[MAX] - } - - set allowStale (allowStale) { - this[ALLOW_STALE] = !!allowStale - } - get allowStale () { - return this[ALLOW_STALE] - } - - set maxAge (mA) { - if (typeof mA !== 'number') - throw new TypeError('maxAge must be a non-negative number') - - this[MAX_AGE] = mA - trim(this) - } - get maxAge () { - return this[MAX_AGE] - } - - // resize the cache when the lengthCalculator changes. - set lengthCalculator (lC) { - if (typeof lC !== 'function') - lC = naiveLength - - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC - this[LENGTH] = 0 - this[LRU_LIST].forEach(hit => { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) - this[LENGTH] += hit.length - }) - } - trim(this) - } - get lengthCalculator () { return this[LENGTH_CALCULATOR] } - - get length () { return this[LENGTH] } - get itemCount () { return this[LRU_LIST].length } - - rforEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].tail; walker !== null;) { - const prev = walker.prev - forEachStep(this, fn, walker, thisp) - walker = prev - } - } - - forEach (fn, thisp) { - thisp = thisp || this - for (let walker = this[LRU_LIST].head; walker !== null;) { - const next = walker.next - forEachStep(this, fn, walker, thisp) - walker = next - } - } - - keys () { - return this[LRU_LIST].toArray().map(k => k.key) - } - - values () { - return this[LRU_LIST].toArray().map(k => k.value) - } - - reset () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) - } - - this[CACHE] = new Map() // hash of items by key - this[LRU_LIST] = new Yallist() // list of items in order of use recency - this[LENGTH] = 0 // length of items in the list - } - - dump () { - return this[LRU_LIST].map(hit => - isStale(this, hit) ? false : { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - }).toArray().filter(h => h) - } - - dumpLru () { - return this[LRU_LIST] - } - - set (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE] - - if (maxAge && typeof maxAge !== 'number') - throw new TypeError('maxAge must be a number') - - const now = maxAge ? Date.now() : 0 - const len = this[LENGTH_CALCULATOR](value, key) - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)) - return false - } - - const node = this[CACHE].get(key) - const item = node.value - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) - this[DISPOSE](key, item.value) - } - - item.now = now - item.maxAge = maxAge - item.value = value - this[LENGTH] += len - item.length - item.length = len - this.get(key) - trim(this) - return true - } - - const hit = new Entry(key, value, len, now, maxAge) - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) - this[DISPOSE](key, value) - - return false - } - - this[LENGTH] += hit.length - this[LRU_LIST].unshift(hit) - this[CACHE].set(key, this[LRU_LIST].head) - trim(this) - return true - } - - has (key) { - if (!this[CACHE].has(key)) return false - const hit = this[CACHE].get(key).value - return !isStale(this, hit) - } - - get (key) { - return get(this, key, true) - } - - peek (key) { - return get(this, key, false) - } - - pop () { - const node = this[LRU_LIST].tail - if (!node) - return null - - del(this, node) - return node.value - } - - del (key) { - del(this, this[CACHE].get(key)) - } - - load (arr) { - // reset the cache - this.reset() - - const now = Date.now() - // A previous serialized cache has the most recent items first - for (let l = arr.length - 1; l >= 0; l--) { - const hit = arr[l] - const expiresAt = hit.e || 0 - if (expiresAt === 0) - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v) - else { - const maxAge = expiresAt - now - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge) - } - } - } - } - - prune () { - this[CACHE].forEach((value, key) => get(this, key, false)) - } -} - -const get = (self, key, doUse) => { - const node = self[CACHE].get(key) - if (node) { - const hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - return undefined - } else { - if (doUse) { - if (self[UPDATE_AGE_ON_GET]) - node.value.now = Date.now() - self[LRU_LIST].unshiftNode(node) - } - } - return hit.value - } -} - -const isStale = (self, hit) => { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) - return false - - const diff = Date.now() - hit.now - return hit.maxAge ? diff > hit.maxAge - : self[MAX_AGE] && (diff > self[MAX_AGE]) -} - -const trim = self => { - if (self[LENGTH] > self[MAX]) { - for (let walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - const prev = walker.prev - del(self, walker) - walker = prev - } - } -} - -const del = (self, node) => { - if (node) { - const hit = node.value - if (self[DISPOSE]) - self[DISPOSE](hit.key, hit.value) - - self[LENGTH] -= hit.length - self[CACHE].delete(hit.key) - self[LRU_LIST].removeNode(node) - } -} - -class Entry { - constructor (key, value, length, now, maxAge) { - this.key = key - this.value = value - this.length = length - this.now = now - this.maxAge = maxAge || 0 - } -} - -const forEachStep = (self, fn, node, thisp) => { - let hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) - hit = undefined - } - if (hit) - fn.call(thisp, hit.value, hit.key, self) -} - -module.exports = LRUCache - - -/***/ }), - -/***/ 2578: +/***/ 82578: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -61230,7 +65327,7 @@ module.exports = LRUCache * Copyright (c) 2014-2020 Teambition * Licensed under the MIT license. */ -const Stream = __nccwpck_require__(2781) +const Stream = __nccwpck_require__(12781) const PassThrough = Stream.PassThrough const slice = Array.prototype.slice @@ -61370,17 +65467,22 @@ function pauseStreams (streams, options) { /***/ }), -/***/ 6228: +/***/ 76228: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const util = __nccwpck_require__(3837); -const braces = __nccwpck_require__(610); -const picomatch = __nccwpck_require__(8569); -const utils = __nccwpck_require__(479); -const isEmptyString = val => val === '' || val === './'; +const util = __nccwpck_require__(73837); +const braces = __nccwpck_require__(50610); +const picomatch = __nccwpck_require__(78569); +const utils = __nccwpck_require__(30479); + +const isEmptyString = v => v === '' || v === './'; +const hasBraces = v => { + const index = v.indexOf('{'); + return index > -1 && v.indexOf('}', index) > -1; +}; /** * Returns an array of strings that match one or more glob patterns. @@ -61821,7 +65923,7 @@ micromatch.parse = (patterns, options) => { micromatch.braces = (pattern, options) => { if (typeof pattern !== 'string') throw new TypeError('Expected a string'); - if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) { + if ((options && options.nobrace === true) || !hasBraces(pattern)) { return [pattern]; } return braces(pattern, options); @@ -61840,24 +65942,26 @@ micromatch.braceExpand = (pattern, options) => { * Expose micromatch */ +// exposed for tests +micromatch.hasBraces = hasBraces; module.exports = micromatch; /***/ }), -/***/ 3973: +/***/ 83973: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { module.exports = minimatch minimatch.Minimatch = Minimatch -var path = (function () { try { return __nccwpck_require__(1017) } catch (e) {}}()) || { +var path = (function () { try { return __nccwpck_require__(71017) } catch (e) {}}()) || { sep: '/' } minimatch.sep = path.sep var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __nccwpck_require__(3717) +var expand = __nccwpck_require__(33717) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, @@ -61992,6 +66096,8 @@ function Minimatch (pattern, options) { } this.options = options + this.maxGlobstarRecursion = options.maxGlobstarRecursion !== undefined + ? options.maxGlobstarRecursion : 200 this.set = [] this.pattern = pattern this.regexp = null @@ -62240,6 +66346,9 @@ function parse (pattern, isSub) { continue } + // coalesce consecutive non-globstar * characters + if (c === '*' && stateChar === '*') continue + // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. @@ -62634,109 +66743,173 @@ Minimatch.prototype.match = function match (f, partial) { // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options + if (pattern.indexOf(GLOBSTAR) !== -1) { + return this._matchGlobstar(file, pattern, partial, 0, 0) + } + return this._matchOne(file, pattern, partial, 0, 0) +} - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) +Minimatch.prototype._matchGlobstar = function (file, pattern, partial, fileIndex, patternIndex) { + var i - this.debug('matchOne', file.length, pattern.length) + // find first globstar from patternIndex + var firstgs = -1 + for (i = patternIndex; i < pattern.length; i++) { + if (pattern[i] === GLOBSTAR) { firstgs = i; break } + } - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] + // find last globstar + var lastgs = -1 + for (i = pattern.length - 1; i >= 0; i--) { + if (pattern[i] === GLOBSTAR) { lastgs = i; break } + } - this.debug(pattern, p, f) + var head = pattern.slice(patternIndex, firstgs) + var body = partial ? pattern.slice(firstgs + 1) : pattern.slice(firstgs + 1, lastgs) + var tail = partial ? [] : pattern.slice(lastgs + 1) - // should be impossible. - // some invalid regexp stuff in the set. - /* istanbul ignore if */ - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true + // check the head + if (head.length) { + var fileHead = file.slice(fileIndex, fileIndex + head.length) + if (!this._matchOne(fileHead, head, partial, 0, 0)) { + return false + } + fileIndex += head.length + } + + // check the tail + var fileTailMatch = 0 + if (tail.length) { + if (tail.length + fileIndex > file.length) return false + + var tailStart = file.length - tail.length + if (this._matchOne(file, tail, partial, tailStart, 0)) { + fileTailMatch = tail.length + } else { + // affordance for stuff like a/**/* matching a/b/ + if (file[file.length - 1] !== '' || + fileIndex + tail.length === file.length) { + return false } + tailStart-- + if (!this._matchOne(file, tail, partial, tailStart, 0)) { + return false + } + fileTailMatch = tail.length + 1 + } + } - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] + // if body is empty (single ** between head and tail) + if (!body.length) { + var sawSome = !!fileTailMatch + for (i = fileIndex; i < file.length - fileTailMatch; i++) { + var f = String(file[i]) + sawSome = true + if (f === '.' || f === '..' || + (!this.options.dot && f.charAt(0) === '.')) { + return false + } + } + return partial || sawSome + } - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + // split body into segments at each GLOBSTAR + var bodySegments = [[[], 0]] + var currentBody = bodySegments[0] + var nonGsParts = 0 + var nonGsPartsSums = [0] + for (var bi = 0; bi < body.length; bi++) { + var b = body[bi] + if (b === GLOBSTAR) { + nonGsPartsSums.push(nonGsParts) + currentBody = [[], 0] + bodySegments.push(currentBody) + } else { + currentBody[0].push(b) + nonGsParts++ + } + } - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } + var idx = bodySegments.length - 1 + var fileLength = file.length - fileTailMatch + for (var si = 0; si < bodySegments.length; si++) { + bodySegments[si][1] = fileLength - + (nonGsPartsSums[idx--] + bodySegments[si][0].length) + } - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } + return !!this._matchGlobStarBodySections( + file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch + ) +} + +// return false for "nope, not matching" +// return null for "not matching, cannot keep trying" +Minimatch.prototype._matchGlobStarBodySections = function ( + file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail +) { + var bs = bodySegments[bodyIndex] + if (!bs) { + // just make sure there are no bad dots + for (var i = fileIndex; i < file.length; i++) { + sawTail = true + var f = file[i] + if (f === '.' || f === '..' || + (!this.options.dot && f.charAt(0) === '.')) { + return false } + } + return sawTail + } - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - /* istanbul ignore if */ - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true + var body = bs[0] + var after = bs[1] + while (fileIndex <= after) { + var m = this._matchOne( + file.slice(0, fileIndex + body.length), + body, + partial, + fileIndex, + 0 + ) + // if limit exceeded, no match. intentional false negative, + // acceptable break in correctness for security. + if (m && globStarDepth < this.maxGlobstarRecursion) { + var sub = this._matchGlobStarBodySections( + file, bodySegments, + fileIndex + body.length, bodyIndex + 1, + partial, globStarDepth + 1, sawTail + ) + if (sub !== false) { + return sub } + } + var f = file[fileIndex] + if (f === '.' || f === '..' || + (!this.options.dot && f.charAt(0) === '.')) { return false } + fileIndex++ + } + return partial || null +} + +Minimatch.prototype._matchOne = function (file, pattern, partial, fileIndex, patternIndex) { + var fi, pi, fl, pl + for ( + fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++ + ) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false || p === GLOBSTAR) return false // something other than ** // non-magic patterns just have to match exactly @@ -62753,17 +66926,6 @@ Minimatch.prototype.matchOne = function (file, pattern, partial) { if (!hit) return false } - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. @@ -62799,271 +66961,286 @@ function regExpEscape (s) { /***/ }), -/***/ 5871: +/***/ 35871: /***/ ((module) => { +"use strict"; + + +function hasKey(obj, keys) { + var o = obj; + keys.slice(0, -1).forEach(function (key) { + o = o[key] || {}; + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber(x) { + if (typeof x === 'number') { return true; } + if ((/^0x[0-9a-f]+$/i).test(x)) { return true; } + return (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/).test(x); +} + +function isConstructorOrProto(obj, key) { + return (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__'; +} + module.exports = function (args, opts) { - if (!opts) opts = {}; - - var flags = { bools : {}, strings : {}, unknownFn: null }; + if (!opts) { opts = {}; } - if (typeof opts['unknown'] === 'function') { - flags.unknownFn = opts['unknown']; - } + var flags = { + bools: {}, + strings: {}, + unknownFn: null, + }; - if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { - flags.allBools = true; - } else { - [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - }); - } - - var aliases = {}; - Object.keys(opts.alias || {}).forEach(function (key) { - aliases[key] = [].concat(opts.alias[key]); - aliases[key].forEach(function (x) { - aliases[x] = [key].concat(aliases[key].filter(function (y) { - return x !== y; - })); - }); - }); + if (typeof opts.unknown === 'function') { + flags.unknownFn = opts.unknown; + } - [].concat(opts.string).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - if (aliases[key]) { - flags.strings[aliases[key]] = true; - } - }); + if (typeof opts.boolean === 'boolean' && opts.boolean) { + flags.allBools = true; + } else { + [].concat(opts.boolean).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } - var defaults = opts['default'] || {}; - - var argv = { _ : [] }; - Object.keys(flags.bools).forEach(function (key) { - setArg(key, defaults[key] === undefined ? false : defaults[key]); - }); - - var notFlags = []; + var aliases = {}; - if (args.indexOf('--') !== -1) { - notFlags = args.slice(args.indexOf('--')+1); - args = args.slice(0, args.indexOf('--')); - } + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } - function argDefined(key, arg) { - return (flags.allBools && /^--[^=]+$/.test(arg)) || - flags.strings[key] || flags.bools[key] || aliases[key]; - } + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); - function setArg (key, val, arg) { - if (arg && flags.unknownFn && !argDefined(key, arg)) { - if (flags.unknownFn(arg) === false) return; - } + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + [].concat(aliases[key]).forEach(function (k) { + flags.strings[k] = true; + }); + } + }); - var value = !flags.strings[key] && isNumber(val) - ? Number(val) : val - ; - setKey(argv, key.split('.'), value); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), value); - }); - } + var defaults = opts.default || {}; + + var argv = { _: [] }; + + function argDefined(key, arg) { + return (flags.allBools && (/^--[^=]+$/).test(arg)) + || flags.strings[key] + || flags.bools[key] + || aliases[key]; + } + + function setKey(obj, keys, value) { + var o = obj; + for (var i = 0; i < keys.length - 1; i++) { + var key = keys[i]; + if (isConstructorOrProto(o, key)) { return; } + if (o[key] === undefined) { o[key] = {}; } + if ( + o[key] === Object.prototype + || o[key] === Number.prototype + || o[key] === String.prototype + ) { + o[key] = {}; + } + if (o[key] === Array.prototype) { o[key] = []; } + o = o[key]; + } - function setKey (obj, keys, value) { - var o = obj; - for (var i = 0; i < keys.length-1; i++) { - var key = keys[i]; - if (isConstructorOrProto(o, key)) return; - if (o[key] === undefined) o[key] = {}; - if (o[key] === Object.prototype || o[key] === Number.prototype - || o[key] === String.prototype) o[key] = {}; - if (o[key] === Array.prototype) o[key] = []; - o = o[key]; - } + var lastKey = keys[keys.length - 1]; + if (isConstructorOrProto(o, lastKey)) { return; } + if ( + o === Object.prototype + || o === Number.prototype + || o === String.prototype + ) { + o = {}; + } + if (o === Array.prototype) { o = []; } + if (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') { + o[lastKey] = value; + } else if (Array.isArray(o[lastKey])) { + o[lastKey].push(value); + } else { + o[lastKey] = [o[lastKey], value]; + } + } - var key = keys[keys.length - 1]; - if (isConstructorOrProto(o, key)) return; - if (o === Object.prototype || o === Number.prototype - || o === String.prototype) o = {}; - if (o === Array.prototype) o = []; - if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { - o[key] = value; - } - else if (Array.isArray(o[key])) { - o[key].push(value); - } - else { - o[key] = [ o[key], value ]; - } - } - - function aliasIsBoolean(key) { - return aliases[key].some(function (x) { - return flags.bools[x]; - }); - } + function setArg(key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) { return; } + } - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - - if (/^--.+=/.test(arg)) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - var m = arg.match(/^--([^=]+)=([\s\S]*)$/); - var key = m[1]; - var value = m[2]; - if (flags.bools[key]) { - value = value !== 'false'; - } - setArg(key, value, arg); - } - else if (/^--no-.+/.test(arg)) { - var key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false, arg); - } - else if (/^--.+/.test(arg)) { - var key = arg.match(/^--(.+)/)[1]; - var next = args[i + 1]; - if (next !== undefined && !/^-/.test(next) - && !flags.bools[key] - && !flags.allBools - && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, next, arg); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next === 'true', arg); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true, arg); - } - } - else if (/^-[^-]+/.test(arg)) { - var letters = arg.slice(1,-1).split(''); - - var broken = false; - for (var j = 0; j < letters.length; j++) { - var next = arg.slice(j+2); - - if (next === '-') { - setArg(letters[j], next, arg) - continue; - } - - if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { - setArg(letters[j], next.split('=')[1], arg); - broken = true; - break; - } - - if (/[A-Za-z]/.test(letters[j]) - && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next, arg); - broken = true; - break; - } - - if (letters[j+1] && letters[j+1].match(/\W/)) { - setArg(letters[j], arg.slice(j+2), arg); - broken = true; - break; - } - else { - setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); - } - } - - var key = arg.slice(-1)[0]; - if (!broken && key !== '-') { - if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) - && !flags.bools[key] - && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, args[i+1], arg); - i++; - } - else if (args[i+1] && /^(true|false)$/.test(args[i+1])) { - setArg(key, args[i+1] === 'true', arg); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true, arg); - } - } - } - else { - if (!flags.unknownFn || flags.unknownFn(arg) !== false) { - argv._.push( - flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) - ); - } - if (opts.stopEarly) { - argv._.push.apply(argv._, args.slice(i + 1)); - break; - } - } - } - - Object.keys(defaults).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) { - setKey(argv, key.split('.'), defaults[key]); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), defaults[key]); - }); - } - }); - - if (opts['--']) { - argv['--'] = new Array(); - notFlags.forEach(function(key) { - argv['--'].push(key); - }); - } - else { - notFlags.forEach(function(key) { - argv._.push(key); - }); - } + var value = !flags.strings[key] && isNumber(val) + ? Number(val) + : val; + setKey(argv, key.split('.'), value); - return argv; -}; + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } -function hasKey (obj, keys) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - o = (o[key] || {}); - }); + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); - var key = keys[keys.length - 1]; - return key in o; -} + var notFlags = []; -function isNumber (x) { - if (typeof x === 'number') return true; - if (/^0x[0-9a-f]+$/i.test(x)) return true; - return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); -} + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--') + 1); + args = args.slice(0, args.indexOf('--')); + } + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + var key; + var next; -function isConstructorOrProto (obj, key) { - return key === 'constructor' && typeof obj[key] === 'function' || key === '__proto__'; -} + if ((/^--.+=/).test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } else if ((/^--no-.+/).test(arg)) { + key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } else if ((/^--.+/).test(arg)) { + key = arg.match(/^--(.+)/)[1]; + next = args[i + 1]; + if ( + next !== undefined + && !(/^(-|--)[^-]/).test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, next, arg); + i += 1; + } else if ((/^(true|false)$/).test(next)) { + setArg(key, next === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } else if ((/^-[^-]+/).test(arg)) { + var letters = arg.slice(1, -1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + + if (next === '-') { + setArg(letters[j], next, arg); + continue; + } + + if ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') { + setArg(letters[j], next.slice(1), arg); + broken = true; + break; + } + + if ( + (/[A-Za-z]/).test(letters[j]) + && (/-?\d+(\.\d*)?(e-?\d+)?$/).test(next) + ) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], arg.slice(j + 2), arg); + broken = true; + break; + } else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if ( + args[i + 1] + && !(/^(-|--)[^-]/).test(args[i + 1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true) + ) { + setArg(key, args[i + 1], arg); + i += 1; + } else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) { + setArg(key, args[i + 1] === 'true', arg); + i += 1; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg)); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (k) { + if (!hasKey(argv, k.split('.'))) { + setKey(argv, k.split('.'), defaults[k]); + + (aliases[k] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[k]); + }); + } + }); + + if (opts['--']) { + argv['--'] = notFlags.slice(); + } else { + notFlags.forEach(function (k) { + argv._.push(k); + }); + } + + return argv; +}; /***/ }), -/***/ 1877: +/***/ 81877: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const fs = __nccwpck_require__(7147); -const Walker = __nccwpck_require__(6695); -const types = __nccwpck_require__(6848); +const fs = __nccwpck_require__(57147); +const Walker = __nccwpck_require__(46695); +const types = __nccwpck_require__(76848); /** * Determines the type of the module from the supplied source code or AST @@ -63164,18 +67341,18 @@ module.exports.fromSource = fromSource; /***/ }), -/***/ 6203: +/***/ 86203: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const {ConfigFile} = __nccwpck_require__(7762); -const fs = __nccwpck_require__(7147); -const path = __nccwpck_require__(1017); -const debug = __nccwpck_require__(8237)('lookup'); -const requirejs = __nccwpck_require__(6627); -const glob = __nccwpck_require__(1957); +const {ConfigFile} = __nccwpck_require__(27762); +const fs = __nccwpck_require__(57147); +const path = __nccwpck_require__(71017); +const debug = __nccwpck_require__(38237)('lookup'); +const requirejs = __nccwpck_require__(16627); +const glob = __nccwpck_require__(91957); /** * Determines the real path of a potentially aliased dependency path @@ -63342,7 +67519,7 @@ module.exports._readConfig = function(configPath, fileSystem) { /***/ }), -/***/ 900: +/***/ 80900: /***/ ((module) => { /** @@ -63370,7 +67547,7 @@ var y = d * 365.25; * @api public */ -module.exports = function(val, options) { +module.exports = function (val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { @@ -63511,10 +67688,10 @@ function plural(ms, msAbs, n, name) { /***/ }), -/***/ 6695: +/***/ 46695: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const parser = __nccwpck_require__(5026); +const parser = __nccwpck_require__(85026); /** * @param {Object} options - Options to configure parser @@ -63654,7 +67831,7 @@ module.exports.prototype.stopWalking = function() { /***/ 1223: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var wrappy = __nccwpck_require__(2940) +var wrappy = __nccwpck_require__(62940) module.exports = wrappy(once) module.exports.strict = wrappy(onceStrict) @@ -63700,7 +67877,7 @@ function onceStrict (fn) { /***/ }), -/***/ 8714: +/***/ 38714: /***/ ((module) => { "use strict"; @@ -63811,13 +67988,13 @@ module.exports.win32 = win32.parse; /***/ }), -/***/ 3433: +/***/ 63433: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const {promisify} = __nccwpck_require__(3837); -const fs = __nccwpck_require__(7147); +const {promisify} = __nccwpck_require__(73837); +const fs = __nccwpck_require__(57147); async function isType(fsStatType, statsMethodName, filePath) { if (typeof filePath !== 'string') { @@ -63862,64 +68039,81 @@ exports.isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink'); /***/ }), -/***/ 7023: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -let tty = __nccwpck_require__(6224) +/***/ 37023: +/***/ ((module) => { +let p = process || {}, argv = p.argv || [], env = p.env || {} let isColorSupported = - !("NO_COLOR" in process.env || process.argv.includes("--no-color")) && - ("FORCE_COLOR" in process.env || - process.argv.includes("--color") || - process.platform === "win32" || - (tty.isatty(1) && process.env.TERM !== "dumb") || - "CI" in process.env) - -let formatter = - (open, close, replace = open) => + !(!!env.NO_COLOR || argv.includes("--no-color")) && + (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI) + +let formatter = (open, close, replace = open) => input => { - let string = "" + input - let index = string.indexOf(close, open.length) - return ~index - ? open + replaceClose(string, close, replace, index) + close - : open + string + close + let string = "" + input, index = string.indexOf(close, open.length) + return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close } let replaceClose = (string, close, replace, index) => { - let start = string.substring(0, index) + replace - let end = string.substring(index + close.length) - let nextIndex = end.indexOf(close) - return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end -} - -let createColors = (enabled = isColorSupported) => ({ - isColorSupported: enabled, - reset: enabled ? s => `\x1b[0m${s}\x1b[0m` : String, - bold: enabled ? formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m") : String, - dim: enabled ? formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m") : String, - italic: enabled ? formatter("\x1b[3m", "\x1b[23m") : String, - underline: enabled ? formatter("\x1b[4m", "\x1b[24m") : String, - inverse: enabled ? formatter("\x1b[7m", "\x1b[27m") : String, - hidden: enabled ? formatter("\x1b[8m", "\x1b[28m") : String, - strikethrough: enabled ? formatter("\x1b[9m", "\x1b[29m") : String, - black: enabled ? formatter("\x1b[30m", "\x1b[39m") : String, - red: enabled ? formatter("\x1b[31m", "\x1b[39m") : String, - green: enabled ? formatter("\x1b[32m", "\x1b[39m") : String, - yellow: enabled ? formatter("\x1b[33m", "\x1b[39m") : String, - blue: enabled ? formatter("\x1b[34m", "\x1b[39m") : String, - magenta: enabled ? formatter("\x1b[35m", "\x1b[39m") : String, - cyan: enabled ? formatter("\x1b[36m", "\x1b[39m") : String, - white: enabled ? formatter("\x1b[37m", "\x1b[39m") : String, - gray: enabled ? formatter("\x1b[90m", "\x1b[39m") : String, - bgBlack: enabled ? formatter("\x1b[40m", "\x1b[49m") : String, - bgRed: enabled ? formatter("\x1b[41m", "\x1b[49m") : String, - bgGreen: enabled ? formatter("\x1b[42m", "\x1b[49m") : String, - bgYellow: enabled ? formatter("\x1b[43m", "\x1b[49m") : String, - bgBlue: enabled ? formatter("\x1b[44m", "\x1b[49m") : String, - bgMagenta: enabled ? formatter("\x1b[45m", "\x1b[49m") : String, - bgCyan: enabled ? formatter("\x1b[46m", "\x1b[49m") : String, - bgWhite: enabled ? formatter("\x1b[47m", "\x1b[49m") : String, -}) + let result = "", cursor = 0 + do { + result += string.substring(cursor, index) + replace + cursor = index + close.length + index = string.indexOf(close, cursor) + } while (~index) + return result + string.substring(cursor) +} + +let createColors = (enabled = isColorSupported) => { + let f = enabled ? formatter : () => String + return { + isColorSupported: enabled, + reset: f("\x1b[0m", "\x1b[0m"), + bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), + dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), + italic: f("\x1b[3m", "\x1b[23m"), + underline: f("\x1b[4m", "\x1b[24m"), + inverse: f("\x1b[7m", "\x1b[27m"), + hidden: f("\x1b[8m", "\x1b[28m"), + strikethrough: f("\x1b[9m", "\x1b[29m"), + + black: f("\x1b[30m", "\x1b[39m"), + red: f("\x1b[31m", "\x1b[39m"), + green: f("\x1b[32m", "\x1b[39m"), + yellow: f("\x1b[33m", "\x1b[39m"), + blue: f("\x1b[34m", "\x1b[39m"), + magenta: f("\x1b[35m", "\x1b[39m"), + cyan: f("\x1b[36m", "\x1b[39m"), + white: f("\x1b[37m", "\x1b[39m"), + gray: f("\x1b[90m", "\x1b[39m"), + + bgBlack: f("\x1b[40m", "\x1b[49m"), + bgRed: f("\x1b[41m", "\x1b[49m"), + bgGreen: f("\x1b[42m", "\x1b[49m"), + bgYellow: f("\x1b[43m", "\x1b[49m"), + bgBlue: f("\x1b[44m", "\x1b[49m"), + bgMagenta: f("\x1b[45m", "\x1b[49m"), + bgCyan: f("\x1b[46m", "\x1b[49m"), + bgWhite: f("\x1b[47m", "\x1b[49m"), + + blackBright: f("\x1b[90m", "\x1b[39m"), + redBright: f("\x1b[91m", "\x1b[39m"), + greenBright: f("\x1b[92m", "\x1b[39m"), + yellowBright: f("\x1b[93m", "\x1b[39m"), + blueBright: f("\x1b[94m", "\x1b[39m"), + magentaBright: f("\x1b[95m", "\x1b[39m"), + cyanBright: f("\x1b[96m", "\x1b[39m"), + whiteBright: f("\x1b[97m", "\x1b[39m"), + + bgBlackBright: f("\x1b[100m", "\x1b[49m"), + bgRedBright: f("\x1b[101m", "\x1b[49m"), + bgGreenBright: f("\x1b[102m", "\x1b[49m"), + bgYellowBright: f("\x1b[103m", "\x1b[49m"), + bgBlueBright: f("\x1b[104m", "\x1b[49m"), + bgMagentaBright: f("\x1b[105m", "\x1b[49m"), + bgCyanBright: f("\x1b[106m", "\x1b[49m"), + bgWhiteBright: f("\x1b[107m", "\x1b[49m"), + } +} module.exports = createColors() module.exports.createColors = createColors @@ -63927,27 +68121,29 @@ module.exports.createColors = createColors /***/ }), -/***/ 8569: +/***/ 78569: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = __nccwpck_require__(3322); +module.exports = __nccwpck_require__(33322); /***/ }), -/***/ 6099: +/***/ 16099: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(1017); +const path = __nccwpck_require__(71017); const WIN_SLASH = '\\\\/'; const WIN_NO_SLASH = `[^${WIN_SLASH}]`; +const DEFAULT_MAX_EXTGLOB_RECURSION = 0; + /** * Posix glob regex */ @@ -64011,6 +68207,7 @@ const WINDOWS_CHARS = { */ const POSIX_REGEX_SOURCE = { + __proto__: null, alnum: 'a-zA-Z0-9', alpha: 'a-zA-Z', ascii: '\\x00-\\x7F', @@ -64028,6 +68225,7 @@ const POSIX_REGEX_SOURCE = { }; module.exports = { + DEFAULT_MAX_EXTGLOB_RECURSION, MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE, @@ -64041,6 +68239,7 @@ module.exports = { // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { + __proto__: null, '***': '*', '**/**': '**', '**/**/**': '**' @@ -64125,14 +68324,14 @@ module.exports = { /***/ }), -/***/ 2139: +/***/ 92139: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const constants = __nccwpck_require__(6099); -const utils = __nccwpck_require__(479); +const constants = __nccwpck_require__(16099); +const utils = __nccwpck_require__(30479); /** * Constants @@ -64176,6 +68375,277 @@ const syntaxError = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; +const splitTopLevel = input => { + const parts = []; + let bracket = 0; + let paren = 0; + let quote = 0; + let value = ''; + let escaped = false; + + for (const ch of input) { + if (escaped === true) { + value += ch; + escaped = false; + continue; + } + + if (ch === '\\') { + value += ch; + escaped = true; + continue; + } + + if (ch === '"') { + quote = quote === 1 ? 0 : 1; + value += ch; + continue; + } + + if (quote === 0) { + if (ch === '[') { + bracket++; + } else if (ch === ']' && bracket > 0) { + bracket--; + } else if (bracket === 0) { + if (ch === '(') { + paren++; + } else if (ch === ')' && paren > 0) { + paren--; + } else if (ch === '|' && paren === 0) { + parts.push(value); + value = ''; + continue; + } + } + } + + value += ch; + } + + parts.push(value); + return parts; +}; + +const isPlainBranch = branch => { + let escaped = false; + + for (const ch of branch) { + if (escaped === true) { + escaped = false; + continue; + } + + if (ch === '\\') { + escaped = true; + continue; + } + + if (/[?*+@!()[\]{}]/.test(ch)) { + return false; + } + } + + return true; +}; + +const normalizeSimpleBranch = branch => { + let value = branch.trim(); + let changed = true; + + while (changed === true) { + changed = false; + + if (/^@\([^\\()[\]{}|]+\)$/.test(value)) { + value = value.slice(2, -1); + changed = true; + } + } + + if (!isPlainBranch(value)) { + return; + } + + return value.replace(/\\(.)/g, '$1'); +}; + +const hasRepeatedCharPrefixOverlap = branches => { + const values = branches.map(normalizeSimpleBranch).filter(Boolean); + + for (let i = 0; i < values.length; i++) { + for (let j = i + 1; j < values.length; j++) { + const a = values[i]; + const b = values[j]; + const char = a[0]; + + if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) { + continue; + } + + if (a === b || a.startsWith(b) || b.startsWith(a)) { + return true; + } + } + } + + return false; +}; + +const parseRepeatedExtglob = (pattern, requireEnd = true) => { + if ((pattern[0] !== '+' && pattern[0] !== '*') || pattern[1] !== '(') { + return; + } + + let bracket = 0; + let paren = 0; + let quote = 0; + let escaped = false; + + for (let i = 1; i < pattern.length; i++) { + const ch = pattern[i]; + + if (escaped === true) { + escaped = false; + continue; + } + + if (ch === '\\') { + escaped = true; + continue; + } + + if (ch === '"') { + quote = quote === 1 ? 0 : 1; + continue; + } + + if (quote === 1) { + continue; + } + + if (ch === '[') { + bracket++; + continue; + } + + if (ch === ']' && bracket > 0) { + bracket--; + continue; + } + + if (bracket > 0) { + continue; + } + + if (ch === '(') { + paren++; + continue; + } + + if (ch === ')') { + paren--; + + if (paren === 0) { + if (requireEnd === true && i !== pattern.length - 1) { + return; + } + + return { + type: pattern[0], + body: pattern.slice(2, i), + end: i + }; + } + } + } +}; + +const getStarExtglobSequenceOutput = pattern => { + let index = 0; + const chars = []; + + while (index < pattern.length) { + const match = parseRepeatedExtglob(pattern.slice(index), false); + + if (!match || match.type !== '*') { + return; + } + + const branches = splitTopLevel(match.body).map(branch => branch.trim()); + if (branches.length !== 1) { + return; + } + + const branch = normalizeSimpleBranch(branches[0]); + if (!branch || branch.length !== 1) { + return; + } + + chars.push(branch); + index += match.end + 1; + } + + if (chars.length < 1) { + return; + } + + const source = chars.length === 1 + ? utils.escapeRegex(chars[0]) + : `[${chars.map(ch => utils.escapeRegex(ch)).join('')}]`; + + return `${source}*`; +}; + +const repeatedExtglobRecursion = pattern => { + let depth = 0; + let value = pattern.trim(); + let match = parseRepeatedExtglob(value); + + while (match) { + depth++; + value = match.body.trim(); + match = parseRepeatedExtglob(value); + } + + return depth; +}; + +const analyzeRepeatedExtglob = (body, options) => { + if (options.maxExtglobRecursion === false) { + return { risky: false }; + } + + const max = + typeof options.maxExtglobRecursion === 'number' + ? options.maxExtglobRecursion + : constants.DEFAULT_MAX_EXTGLOB_RECURSION; + + const branches = splitTopLevel(body).map(branch => branch.trim()); + + if (branches.length > 1) { + if ( + branches.some(branch => branch === '') || + branches.some(branch => /^[*?]+$/.test(branch)) || + hasRepeatedCharPrefixOverlap(branches) + ) { + return { risky: true }; + } + } + + for (const branch of branches) { + const safeOutput = getStarExtglobSequenceOutput(branch); + if (safeOutput) { + return { risky: true, safeOutput }; + } + + if (repeatedExtglobRecursion(branch) > max) { + return { risky: true }; + } + } + + return { risky: false }; +}; + /** * Parse the given input string. * @param {String} input @@ -64357,6 +68827,8 @@ const parse = (input, options) => { token.prev = prev; token.parens = state.parens; token.output = state.output; + token.startIndex = state.index; + token.tokensIndex = tokens.length; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); @@ -64366,6 +68838,34 @@ const parse = (input, options) => { }; const extglobClose = token => { + const literal = input.slice(token.startIndex, state.index + 1); + const body = input.slice(token.startIndex + 2, state.index); + const analysis = analyzeRepeatedExtglob(body, opts); + + if ((token.type === 'plus' || token.type === 'star') && analysis.risky) { + const safeOutput = analysis.safeOutput + ? (token.output ? '' : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) + : undefined; + const open = tokens[token.tokensIndex]; + + open.type = 'text'; + open.value = literal; + open.output = safeOutput || utils.escapeRegex(literal); + + for (let i = token.tokensIndex + 1; i < tokens.length; i++) { + tokens[i].value = ''; + tokens[i].output = ''; + delete tokens[i].suffix; + } + + state.output = token.output + open.output; + state.backtrack = true; + + push({ type: 'paren', extglob: true, value, output: '' }); + decrement('parens'); + return; + } + let output = token.close + (opts.capture ? ')' : ''); let rest; @@ -65224,17 +69724,17 @@ module.exports = parse; /***/ }), -/***/ 3322: +/***/ 33322: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(1017); -const scan = __nccwpck_require__(2429); -const parse = __nccwpck_require__(2139); -const utils = __nccwpck_require__(479); -const constants = __nccwpck_require__(6099); +const path = __nccwpck_require__(71017); +const scan = __nccwpck_require__(32429); +const parse = __nccwpck_require__(92139); +const utils = __nccwpck_require__(30479); +const constants = __nccwpck_require__(16099); const isObject = val => val && typeof val === 'object' && !Array.isArray(val); /** @@ -65574,13 +70074,13 @@ module.exports = picomatch; /***/ }), -/***/ 2429: +/***/ 32429: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const utils = __nccwpck_require__(479); +const utils = __nccwpck_require__(30479); const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ @@ -65597,7 +70097,7 @@ const { CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_RIGHT_SQUARE_BRACKET /* ] */ -} = __nccwpck_require__(6099); +} = __nccwpck_require__(16099); const isPathSeparator = code => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; @@ -65973,20 +70473,20 @@ module.exports = scan; /***/ }), -/***/ 479: +/***/ 30479: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -const path = __nccwpck_require__(1017); +const path = __nccwpck_require__(71017); const win32 = process.platform === 'win32'; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL -} = __nccwpck_require__(6099); +} = __nccwpck_require__(16099); exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); @@ -66079,14 +70579,14 @@ module.exports = AtWord; /***/ }), -/***/ 2946: +/***/ 12946: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Container = __nccwpck_require__(93); -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class Colon extends Node { constructor (opts) { @@ -66102,14 +70602,14 @@ module.exports = Colon; /***/ }), -/***/ 9475: +/***/ 59475: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Container = __nccwpck_require__(93); -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class Comma extends Node { constructor (opts) { @@ -66125,14 +70625,14 @@ module.exports = Comma; /***/ }), -/***/ 6227: +/***/ 36227: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Container = __nccwpck_require__(93); -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class Comment extends Node { constructor (opts) { @@ -66165,7 +70665,7 @@ module.exports = Comment; "use strict"; -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class Container extends Node { @@ -66377,7 +70877,7 @@ module.exports = Container; /***/ }), -/***/ 5118: +/***/ 75118: /***/ ((module) => { "use strict"; @@ -66404,7 +70904,7 @@ module.exports = ParserError; /***/ }), -/***/ 6974: +/***/ 36974: /***/ ((module) => { "use strict"; @@ -66431,7 +70931,7 @@ module.exports = TokenizeError; /***/ }), -/***/ 1773: +/***/ 51773: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -66455,7 +70955,7 @@ module.exports = FunctionNode; /***/ }), -/***/ 3184: +/***/ 83184: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -66463,17 +70963,17 @@ module.exports = FunctionNode; const Parser = __nccwpck_require__(8281); const AtWord = __nccwpck_require__(766); -const Colon = __nccwpck_require__(2946); -const Comma = __nccwpck_require__(9475); -const Comment = __nccwpck_require__(6227); -const Func = __nccwpck_require__(1773); -const Num = __nccwpck_require__(8339); -const Operator = __nccwpck_require__(6041); -const Paren = __nccwpck_require__(1586); -const Str = __nccwpck_require__(9275); -const UnicodeRange = __nccwpck_require__(3920); -const Value = __nccwpck_require__(8167); -const Word = __nccwpck_require__(3410); +const Colon = __nccwpck_require__(12946); +const Comma = __nccwpck_require__(59475); +const Comment = __nccwpck_require__(36227); +const Func = __nccwpck_require__(51773); +const Num = __nccwpck_require__(68339); +const Operator = __nccwpck_require__(86041); +const Paren = __nccwpck_require__(61586); +const Str = __nccwpck_require__(29275); +const UnicodeRange = __nccwpck_require__(73920); +const Value = __nccwpck_require__(78167); +const Word = __nccwpck_require__(43410); let parser = function (source, options) { return new Parser(source, options); @@ -66532,7 +71032,7 @@ module.exports = parser; /***/ }), -/***/ 5809: +/***/ 35809: /***/ ((module) => { "use strict"; @@ -66754,14 +71254,14 @@ module.exports = class Node { /***/ }), -/***/ 8339: +/***/ 68339: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Container = __nccwpck_require__(93); -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class NumberNode extends Node { constructor (opts) { @@ -66787,14 +71287,14 @@ module.exports = NumberNode; /***/ }), -/***/ 6041: +/***/ 86041: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Container = __nccwpck_require__(93); -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class Operator extends Node { constructor (opts) { @@ -66810,14 +71310,14 @@ module.exports = Operator; /***/ }), -/***/ 1586: +/***/ 61586: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Container = __nccwpck_require__(93); -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class Parenthesis extends Node { constructor (opts) { @@ -66840,27 +71340,27 @@ module.exports = Parenthesis; "use strict"; -const Root = __nccwpck_require__(543); -const Value = __nccwpck_require__(8167); +const Root = __nccwpck_require__(80543); +const Value = __nccwpck_require__(78167); const AtWord = __nccwpck_require__(766); -const Colon = __nccwpck_require__(2946); -const Comma = __nccwpck_require__(9475); -const Comment = __nccwpck_require__(6227); -const Func = __nccwpck_require__(1773); -const Numbr = __nccwpck_require__(8339); -const Operator = __nccwpck_require__(6041); -const Paren = __nccwpck_require__(1586); -const Str = __nccwpck_require__(9275); -const Word = __nccwpck_require__(3410); -const UnicodeRange = __nccwpck_require__(3920); - -const tokenize = __nccwpck_require__(7492); - -const flatten = __nccwpck_require__(7630); -const indexesOf = __nccwpck_require__(5977); -const uniq = __nccwpck_require__(974); -const ParserError = __nccwpck_require__(5118); +const Colon = __nccwpck_require__(12946); +const Comma = __nccwpck_require__(59475); +const Comment = __nccwpck_require__(36227); +const Func = __nccwpck_require__(51773); +const Numbr = __nccwpck_require__(68339); +const Operator = __nccwpck_require__(86041); +const Paren = __nccwpck_require__(61586); +const Str = __nccwpck_require__(29275); +const Word = __nccwpck_require__(43410); +const UnicodeRange = __nccwpck_require__(73920); + +const tokenize = __nccwpck_require__(27492); + +const flatten = __nccwpck_require__(67630); +const indexesOf = __nccwpck_require__(65977); +const uniq = __nccwpck_require__(90974); +const ParserError = __nccwpck_require__(75118); function sortAscending (list) { return list.sort((a, b) => a - b); @@ -67418,7 +71918,7 @@ module.exports = class Parser { /***/ }), -/***/ 543: +/***/ 80543: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -67436,14 +71936,14 @@ module.exports = class Root extends Container { /***/ }), -/***/ 9275: +/***/ 29275: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Container = __nccwpck_require__(93); -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class StringNode extends Node { constructor (opts) { @@ -67472,7 +71972,7 @@ module.exports = StringNode; /***/ }), -/***/ 7492: +/***/ 27492: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -67511,8 +72011,8 @@ const wordEndNum = /[ \n\t\r\(\)\{\}\*:;@!&'"\-\+\|~>,\[\]\\]|\//g; const alphaNum = /^[a-z0-9]/i; const unicodeRange = /^[a-f0-9?\-]/i; -const util = __nccwpck_require__(3837); -const TokenizeError = __nccwpck_require__(6974); +const util = __nccwpck_require__(73837); +const TokenizeError = __nccwpck_require__(36974); module.exports = function tokenize (input, options) { @@ -67874,14 +72374,14 @@ module.exports = function tokenize (input, options) { /***/ }), -/***/ 3920: +/***/ 73920: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Container = __nccwpck_require__(93); -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class UnicodeRange extends Node { constructor (opts) { @@ -67897,7 +72397,7 @@ module.exports = UnicodeRange; /***/ }), -/***/ 8167: +/***/ 78167: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; @@ -67916,14 +72416,14 @@ module.exports = class Value extends Container { /***/ }), -/***/ 3410: +/***/ 43410: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; const Container = __nccwpck_require__(93); -const Node = __nccwpck_require__(5809); +const Node = __nccwpck_require__(35809); class Word extends Node { constructor (opts) { @@ -67939,13 +72439,13 @@ module.exports = Word; /***/ }), -/***/ 4193: +/***/ 54193: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let Container = __nccwpck_require__(6919) +let Container = __nccwpck_require__(56919) class AtRule extends Container { constructor(defaults) { @@ -67972,13 +72472,13 @@ Container.registerAtRule(AtRule) /***/ }), -/***/ 7592: +/***/ 37592: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let Node = __nccwpck_require__(8557) +let Node = __nccwpck_require__(48557) class Comment extends Node { constructor(defaults) { @@ -67993,43 +72493,81 @@ Comment.default = Comment /***/ }), -/***/ 6919: +/***/ 56919: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let { isClean, my } = __nccwpck_require__(2594) -let Declaration = __nccwpck_require__(3522) -let Comment = __nccwpck_require__(7592) -let Node = __nccwpck_require__(8557) +let Comment = __nccwpck_require__(37592) +let Declaration = __nccwpck_require__(33522) +let Node = __nccwpck_require__(48557) +let { isClean, my } = __nccwpck_require__(32594) -let parse, Rule, AtRule +let AtRule, parse, Root, Rule function cleanSource(nodes) { - return nodes.map(i => { - if (i.nodes) i.nodes = cleanSource(i.nodes) - delete i.source - return i - }) + let stack = nodes.slice() + while (stack.length > 0) { + let node = stack.pop() + delete node.source + if (node.nodes) { + node.nodes = node.nodes.slice() + for (let i of node.nodes) stack.push(i) + } + } + return nodes.slice() } -function markDirtyUp(node) { - node[isClean] = false - if (node.proxyOf.nodes) { - for (let i of node.proxyOf.nodes) { - markDirtyUp(i) +function markTreeDirty(node) { + let stack = [node] + while (stack.length > 0) { + let next = stack.pop() + next[isClean] = false + if (next.proxyOf.nodes) { + for (let i of next.proxyOf.nodes) stack.push(i) } } } class Container extends Node { - push(child) { - child.parent = this - this.proxyOf.nodes.push(child) + get first() { + if (!this.proxyOf.nodes) return undefined + return this.proxyOf.nodes[0] + } + + get last() { + if (!this.proxyOf.nodes) return undefined + return this.proxyOf.nodes[this.proxyOf.nodes.length - 1] + } + + append(...children) { + for (let child of children) { + let nodes = this.normalize(child, this.last) + for (let node of nodes) this.proxyOf.nodes.push(node) + } + + this.markDirty() + return this } + cleanRaws(keepBetween) { + let stack = [this] + while (stack.length > 0) { + let node = stack.pop() + if (node !== this && node.cleanRaws !== Container.prototype.cleanRaws) { + // Subclass with own logic; let it handle its subtree + node.cleanRaws(keepBetween) + continue + } + Node.prototype.cleanRaws.call(node, keepBetween) + if (node.nodes) { + for (let child of node.nodes) stack.push(child) + } + } + } + each(callback) { if (!this.proxyOf.nodes) return undefined let iterator = this.getIterator() @@ -68047,104 +72585,89 @@ class Container extends Node { return result } - walk(callback) { - return this.each((child, i) => { - let result - try { - result = callback(child, i) - } catch (e) { - throw child.addToError(e) - } - if (result !== false && child.walk) { - result = child.walk(callback) - } - - return result - }) + every(condition) { + return this.nodes.every(condition) } - walkDecls(prop, callback) { - if (!callback) { - callback = prop - return this.walk((child, i) => { - if (child.type === 'decl') { - return callback(child, i) - } - }) - } - if (prop instanceof RegExp) { - return this.walk((child, i) => { - if (child.type === 'decl' && prop.test(child.prop)) { - return callback(child, i) - } - }) - } - return this.walk((child, i) => { - if (child.type === 'decl' && child.prop === prop) { - return callback(child, i) - } - }) - } + getIterator() { + if (!this.lastEach) this.lastEach = 0 + if (!this.indexes) this.indexes = {} - walkRules(selector, callback) { - if (!callback) { - callback = selector + this.lastEach += 1 + let iterator = this.lastEach + this.indexes[iterator] = 0 - return this.walk((child, i) => { - if (child.type === 'rule') { - return callback(child, i) - } - }) - } - if (selector instanceof RegExp) { - return this.walk((child, i) => { - if (child.type === 'rule' && selector.test(child.selector)) { - return callback(child, i) - } - }) - } - return this.walk((child, i) => { - if (child.type === 'rule' && child.selector === selector) { - return callback(child, i) - } - }) + return iterator } - walkAtRules(name, callback) { - if (!callback) { - callback = name - return this.walk((child, i) => { - if (child.type === 'atrule') { - return callback(child, i) + getProxyProcessor() { + return { + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (!node[prop]) { + return node[prop] + } else if ( + prop === 'each' || + (typeof prop === 'string' && prop.startsWith('walk')) + ) { + return (...args) => { + return node[prop]( + ...args.map(i => { + if (typeof i === 'function') { + return (child, index) => i(child.toProxy(), index) + } else { + return i + } + }) + ) + } + } else if (prop === 'every' || prop === 'some') { + return cb => { + return node[prop]((child, ...other) => + cb(child.toProxy(), ...other) + ) + } + } else if (prop === 'root') { + return () => node.root().toProxy() + } else if (prop === 'nodes') { + return node.nodes.map(i => i.toProxy()) + } else if (prop === 'first' || prop === 'last') { + return node[prop].toProxy() + } else { + return node[prop] } - }) - } - if (name instanceof RegExp) { - return this.walk((child, i) => { - if (child.type === 'atrule' && name.test(child.name)) { - return callback(child, i) + }, + + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value + if (prop === 'name' || prop === 'params' || prop === 'selector') { + node.markDirty() } - }) - } - return this.walk((child, i) => { - if (child.type === 'atrule' && child.name === name) { - return callback(child, i) + return true } - }) + } } - walkComments(callback) { - return this.walk((child, i) => { - if (child.type === 'comment') { - return callback(child, i) - } - }) + index(child) { + if (typeof child === 'number') return child + if (child.proxyOf) child = child.proxyOf + return this.proxyOf.nodes.indexOf(child) } - append(...children) { - for (let child of children) { - let nodes = this.normalize(child, this.last) - for (let node of nodes) this.proxyOf.nodes.push(node) + insertAfter(exist, add) { + let existIndex = this.index(exist) + let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse() + existIndex = this.index(exist) + for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node) + + let index + for (let id in this.indexes) { + index = this.indexes[id] + if (existIndex < index) { + this.indexes[id] = index + nodes.length + } } this.markDirty() @@ -68152,13 +72675,22 @@ class Container extends Node { return this } - prepend(...children) { - children = children.reverse() - for (let child of children) { - let nodes = this.normalize(child, this.first, 'prepend').reverse() - for (let node of nodes) this.proxyOf.nodes.unshift(node) - for (let id in this.indexes) { - this.indexes[id] = this.indexes[id] + nodes.length + insertBefore(exist, add) { + let existIndex = this.index(exist) + let type = existIndex === 0 ? 'prepend' : false + let nodes = this.normalize( + add, + this.proxyOf.nodes[existIndex], + type + ).reverse() + existIndex = this.index(exist) + for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node) + + let index + for (let id in this.indexes) { + index = this.indexes[id] + if (existIndex <= index) { + this.indexes[id] = index + nodes.length } } @@ -68167,25 +72699,67 @@ class Container extends Node { return this } - cleanRaws(keepBetween) { - super.cleanRaws(keepBetween) - if (this.nodes) { - for (let node of this.nodes) node.cleanRaws(keepBetween) + normalize(nodes, sample) { + if (typeof nodes === 'string') { + nodes = cleanSource(parse(nodes).nodes) + } else if (typeof nodes === 'undefined') { + nodes = [] + } else if (Array.isArray(nodes)) { + nodes = nodes.slice(0) + for (let i of nodes) { + if (i.parent) i.parent.removeChild(i, 'ignore') + } + } else if (nodes.type === 'root' && this.type !== 'document') { + nodes = nodes.nodes.slice(0) + for (let i of nodes) { + if (i.parent) i.parent.removeChild(i, 'ignore') + } + } else if (nodes.type) { + nodes = [nodes] + } else if (nodes.prop) { + if (typeof nodes.value === 'undefined') { + throw new Error('Value field is missed in node creation') + } else if (typeof nodes.value !== 'string') { + nodes.value = String(nodes.value) + } + nodes = [new Declaration(nodes)] + } else if (nodes.selector || nodes.selectors) { + nodes = [new Rule(nodes)] + } else if (nodes.name) { + nodes = [new AtRule(nodes)] + } else if (nodes.text) { + nodes = [new Comment(nodes)] + } else { + throw new Error('Unknown node type in node creation') } - } - insertBefore(exist, add) { - exist = this.index(exist) + let processed = nodes.map(i => { + /* c8 ignore next */ + if (!i[my]) Container.rebuild(i) + i = i.proxyOf + if (i.parent) i.parent.removeChild(i) + if (i[isClean]) markTreeDirty(i) - let type = exist === 0 ? 'prepend' : false - let nodes = this.normalize(add, this.proxyOf.nodes[exist], type).reverse() - for (let node of nodes) this.proxyOf.nodes.splice(exist, 0, node) + if (!i.raws) i.raws = {} + if (typeof i.raws.before === 'undefined') { + if (sample && typeof sample.raws.before !== 'undefined') { + i.raws.before = sample.raws.before.replace(/\S/g, '') + } + } + i.parent = this.proxyOf + return i + }) - let index - for (let id in this.indexes) { - index = this.indexes[id] - if (exist <= index) { - this.indexes[id] = index + nodes.length + return processed + } + + prepend(...children) { + children = children.reverse() + for (let child of children) { + let nodes = this.normalize(child, this.first, 'prepend').reverse() + for (let node of nodes) this.proxyOf.nodes.unshift(node) + for (let id in this.indexes) { + this.indexes[id] = this.indexes[id] + nodes.length } } @@ -68194,19 +72768,15 @@ class Container extends Node { return this } - insertAfter(exist, add) { - exist = this.index(exist) - - let nodes = this.normalize(add, this.proxyOf.nodes[exist]).reverse() - for (let node of nodes) this.proxyOf.nodes.splice(exist + 1, 0, node) + push(child) { + child.parent = this + this.proxyOf.nodes.push(child) + return this + } - let index - for (let id in this.indexes) { - index = this.indexes[id] - if (exist < index) { - this.indexes[id] = index + nodes.length - } - } + removeAll() { + for (let node of this.proxyOf.nodes) node.parent = undefined + this.proxyOf.nodes = [] this.markDirty() @@ -68231,15 +72801,6 @@ class Container extends Node { return this } - removeAll() { - for (let node of this.proxyOf.nodes) node.parent = undefined - this.proxyOf.nodes = [] - - this.markDirty() - - return this - } - replaceValues(pattern, opts, callback) { if (!callback) { callback = opts @@ -68258,139 +72819,131 @@ class Container extends Node { return this } - every(condition) { - return this.nodes.every(condition) - } - some(condition) { return this.nodes.some(condition) } - index(child) { - if (typeof child === 'number') return child - if (child.proxyOf) child = child.proxyOf - return this.proxyOf.nodes.indexOf(child) - } - - get first() { + walk(callback) { if (!this.proxyOf.nodes) return undefined - return this.proxyOf.nodes[0] - } - get last() { - if (!this.proxyOf.nodes) return undefined - return this.proxyOf.nodes[this.proxyOf.nodes.length - 1] - } + // An explicit stack instead of recursive `each()` calls to survive + // deeply nested trees. Each frame keeps a live `indexes` slot, so + // insertion and removal during the walk behave like `each()`: the + // slot stays at the current child until its subtree is finished. + let stack = [{ iterator: this.getIterator(), node: this.proxyOf }] + + while (stack.length > 0) { + let { iterator, node } = stack[stack.length - 1] + let index = node.indexes[iterator] + + if (index >= node.proxyOf.nodes.length) { + delete node.indexes[iterator] + stack.pop() + let parent = stack[stack.length - 1] + // Finish the parent’s step for the child subtree we just left + if (parent) parent.node.indexes[parent.iterator] += 1 + continue + } - normalize(nodes, sample) { - if (typeof nodes === 'string') { - nodes = cleanSource(parse(nodes).nodes) - } else if (Array.isArray(nodes)) { - nodes = nodes.slice(0) - for (let i of nodes) { - if (i.parent) i.parent.removeChild(i, 'ignore') + let child = node.proxyOf.nodes[index] + let result + try { + result = callback(child, index) + } catch (e) { + throw child.addToError(e) } - } else if (nodes.type === 'root' && this.type !== 'document') { - nodes = nodes.nodes.slice(0) - for (let i of nodes) { - if (i.parent) i.parent.removeChild(i, 'ignore') + if (result === false) { + for (let opened of stack) { + delete opened.node.indexes[opened.iterator] + } + return false } - } else if (nodes.type) { - nodes = [nodes] - } else if (nodes.prop) { - if (typeof nodes.value === 'undefined') { - throw new Error('Value field is missed in node creation') - } else if (typeof nodes.value !== 'string') { - nodes.value = String(nodes.value) + if (child.walk && child.proxyOf.nodes) { + stack.push({ iterator: child.getIterator(), node: child }) + } else { + node.indexes[iterator] += 1 } - nodes = [new Declaration(nodes)] - } else if (nodes.selector) { - nodes = [new Rule(nodes)] - } else if (nodes.name) { - nodes = [new AtRule(nodes)] - } else if (nodes.text) { - nodes = [new Comment(nodes)] - } else { - throw new Error('Unknown node type in node creation') } - let processed = nodes.map(i => { - /* c8 ignore next */ - if (!i[my]) Container.rebuild(i) - i = i.proxyOf - if (i.parent) i.parent.removeChild(i) - if (i[isClean]) markDirtyUp(i) - if (typeof i.raws.before === 'undefined') { - if (sample && typeof sample.raws.before !== 'undefined') { - i.raws.before = sample.raws.before.replace(/\S/g, '') + return undefined + } + + walkAtRules(name, callback) { + if (!callback) { + callback = name + return this.walk((child, i) => { + if (child.type === 'atrule') { + return callback(child, i) } + }) + } + if (name instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'atrule' && name.test(child.name)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'atrule' && child.name === name) { + return callback(child, i) } - i.parent = this.proxyOf - return i }) + } - return processed + walkComments(callback) { + return this.walk((child, i) => { + if (child.type === 'comment') { + return callback(child, i) + } + }) } - getProxyProcessor() { - return { - set(node, prop, value) { - if (node[prop] === value) return true - node[prop] = value - if (prop === 'name' || prop === 'params' || prop === 'selector') { - node.markDirty() + walkDecls(prop, callback) { + if (!callback) { + callback = prop + return this.walk((child, i) => { + if (child.type === 'decl') { + return callback(child, i) } - return true - }, - - get(node, prop) { - if (prop === 'proxyOf') { - return node - } else if (!node[prop]) { - return node[prop] - } else if ( - prop === 'each' || - (typeof prop === 'string' && prop.startsWith('walk')) - ) { - return (...args) => { - return node[prop]( - ...args.map(i => { - if (typeof i === 'function') { - return (child, index) => i(child.toProxy(), index) - } else { - return i - } - }) - ) - } - } else if (prop === 'every' || prop === 'some') { - return cb => { - return node[prop]((child, ...other) => - cb(child.toProxy(), ...other) - ) - } - } else if (prop === 'root') { - return () => node.root().toProxy() - } else if (prop === 'nodes') { - return node.nodes.map(i => i.toProxy()) - } else if (prop === 'first' || prop === 'last') { - return node[prop].toProxy() - } else { - return node[prop] + }) + } + if (prop instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'decl' && prop.test(child.prop)) { + return callback(child, i) } - } + }) } + return this.walk((child, i) => { + if (child.type === 'decl' && child.prop === prop) { + return callback(child, i) + } + }) } - getIterator() { - if (!this.lastEach) this.lastEach = 0 - if (!this.indexes) this.indexes = {} - - this.lastEach += 1 - let iterator = this.lastEach - this.indexes[iterator] = 0 + walkRules(selector, callback) { + if (!callback) { + callback = selector - return iterator + return this.walk((child, i) => { + if (child.type === 'rule') { + return callback(child, i) + } + }) + } + if (selector instanceof RegExp) { + return this.walk((child, i) => { + if (child.type === 'rule' && selector.test(child.selector)) { + return callback(child, i) + } + }) + } + return this.walk((child, i) => { + if (child.type === 'rule' && child.selector === selector) { + return callback(child, i) + } + }) } } @@ -68406,27 +72959,35 @@ Container.registerAtRule = dependant => { AtRule = dependant } +Container.registerRoot = dependant => { + Root = dependant +} + module.exports = Container Container.default = Container /* c8 ignore start */ Container.rebuild = node => { - if (node.type === 'atrule') { - Object.setPrototypeOf(node, AtRule.prototype) - } else if (node.type === 'rule') { - Object.setPrototypeOf(node, Rule.prototype) - } else if (node.type === 'decl') { - Object.setPrototypeOf(node, Declaration.prototype) - } else if (node.type === 'comment') { - Object.setPrototypeOf(node, Comment.prototype) - } + let stack = [node] + while (stack.length > 0) { + let next = stack.pop() + if (next.type === 'atrule') { + Object.setPrototypeOf(next, AtRule.prototype) + } else if (next.type === 'rule') { + Object.setPrototypeOf(next, Rule.prototype) + } else if (next.type === 'decl') { + Object.setPrototypeOf(next, Declaration.prototype) + } else if (next.type === 'comment') { + Object.setPrototypeOf(next, Comment.prototype) + } else if (next.type === 'root') { + Object.setPrototypeOf(next, Root.prototype) + } - node[my] = true + next[my] = true - if (node.nodes) { - node.nodes.forEach(child => { - Container.rebuild(child) - }) + if (next.nodes) { + for (let child of next.nodes) stack.push(child) + } } } /* c8 ignore stop */ @@ -68434,15 +72995,15 @@ Container.rebuild = node => { /***/ }), -/***/ 3279: +/***/ 63279: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let pico = __nccwpck_require__(7023) +let pico = __nccwpck_require__(37023) -let terminalHighlight = __nccwpck_require__(1040) +let terminalHighlight = __nccwpck_require__(51040) class CssSyntaxError extends Error { constructor(message, line, column, source, file, plugin) { @@ -68492,37 +73053,70 @@ class CssSyntaxError extends Error { let css = this.source if (color == null) color = pico.isColorSupported - if (terminalHighlight) { - if (color) css = terminalHighlight(css) + + let aside = text => text + let mark = text => text + let highlight = text => text + if (color) { + let { bold, gray, red } = pico.createColors(true) + mark = text => bold(red(text)) + aside = text => gray(text) + if (terminalHighlight) { + highlight = text => terminalHighlight(text) + } } let lines = css.split(/\r?\n/) let start = Math.max(this.line - 3, 0) let end = Math.min(this.line + 2, lines.length) - let maxWidth = String(end).length - let mark, aside - if (color) { - let { bold, red, gray } = pico.createColors(true) - mark = text => bold(red(text)) - aside = text => gray(text) - } else { - mark = aside = str => str - } - return lines .slice(start, end) .map((line, index) => { let number = start + 1 + index let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ' if (number === this.line) { + if (line.length > 160) { + let padding = 20 + let subLineStart = Math.max(0, this.column - padding) + let subLineEnd = Math.max( + this.column + padding, + this.endColumn + padding + ) + let subLine = line.slice(subLineStart, subLineEnd) + + let spacing = + aside(gutter.replace(/\d/g, ' ')) + + line + .slice(0, Math.min(this.column - 1, padding - 1)) + .replace(/[^\t]/g, ' ') + + return ( + mark('>') + + aside(gutter) + + highlight(subLine) + + '\n ' + + spacing + + mark('^') + ) + } + let spacing = aside(gutter.replace(/\d/g, ' ')) + line.slice(0, this.column - 1).replace(/[^\t]/g, ' ') - return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^') + + return ( + mark('>') + + aside(gutter) + + highlight(line) + + '\n ' + + spacing + + mark('^') + ) } - return ' ' + aside(gutter) + line + + return ' ' + aside(gutter) + highlight(line) }) .join('\n') } @@ -68542,15 +73136,19 @@ CssSyntaxError.default = CssSyntaxError /***/ }), -/***/ 3522: +/***/ 33522: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let Node = __nccwpck_require__(8557) +let Node = __nccwpck_require__(48557) class Declaration extends Node { + get variable() { + return this.prop.startsWith('--') || this.prop[0] === '$' + } + constructor(defaults) { if ( defaults && @@ -68562,10 +73160,6 @@ class Declaration extends Node { super(defaults) this.type = 'decl' } - - get variable() { - return this.prop.startsWith('--') || this.prop[0] === '$' - } } module.exports = Declaration @@ -68574,13 +73168,13 @@ Declaration.default = Declaration /***/ }), -/***/ 8085: +/***/ 58085: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let Container = __nccwpck_require__(6919) +let Container = __nccwpck_require__(56919) let LazyResult, Processor @@ -68615,40 +73209,38 @@ Document.default = Document /***/ }), -/***/ 1543: +/***/ 71543: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let Declaration = __nccwpck_require__(3522) -let PreviousMap = __nccwpck_require__(1090) -let Comment = __nccwpck_require__(7592) -let AtRule = __nccwpck_require__(4193) +let AtRule = __nccwpck_require__(54193) +let Comment = __nccwpck_require__(37592) +let Declaration = __nccwpck_require__(33522) let Input = __nccwpck_require__(2690) -let Root = __nccwpck_require__(2630) -let Rule = __nccwpck_require__(2234) - -function fromJSON(json, inputs) { - if (Array.isArray(json)) return json.map(n => fromJSON(n)) - - let { inputs: ownInputs, ...defaults } = json - if (ownInputs) { - inputs = [] - for (let input of ownInputs) { - let inputHydrated = { ...input, __proto__: Input.prototype } - if (inputHydrated.map) { - inputHydrated.map = { - ...inputHydrated.map, - __proto__: PreviousMap.prototype - } +let PreviousMap = __nccwpck_require__(91090) +let Root = __nccwpck_require__(22630) +let Rule = __nccwpck_require__(12234) + +function hydrateInputs(json, inputs) { + if (!json.inputs) return inputs + return json.inputs.map(input => { + let inputHydrated = { ...input, __proto__: Input.prototype } + if (inputHydrated.map) { + inputHydrated.map = { + ...inputHydrated.map, + __proto__: PreviousMap.prototype } - inputs.push(inputHydrated) } - } - if (defaults.nodes) { - defaults.nodes = json.nodes.map(n => fromJSON(n, inputs)) - } + return inputHydrated + }) +} + +function constructNode(json, inputs, children) { + let defaults = { ...json } + delete defaults.inputs + delete defaults.nodes if (defaults.source) { let { inputId, ...source } = defaults.source defaults.source = source @@ -68656,19 +73248,74 @@ function fromJSON(json, inputs) { defaults.source.input = inputs[inputId] } } + + let node if (defaults.type === 'root') { - return new Root(defaults) + node = new Root(defaults) } else if (defaults.type === 'decl') { - return new Declaration(defaults) + node = new Declaration(defaults) } else if (defaults.type === 'rule') { - return new Rule(defaults) + node = new Rule(defaults) } else if (defaults.type === 'comment') { - return new Comment(defaults) + node = new Comment(defaults) } else if (defaults.type === 'atrule') { - return new AtRule(defaults) + node = new AtRule(defaults) } else { throw new Error('Unknown node type: ' + json.type) } + + // Rehydrated children are attached after construction. Passing them + // through the container constructor would re-run insertion spacing + // normalization and overwrite each child's own `raws.before`. + if (children) { + node.nodes = children + for (let child of children) child.parent = node + } + + return node +} + +function fromJSON(json, inputs) { + if (Array.isArray(json)) return json.map(n => fromJSON(n)) + + // An explicit stack instead of recursive calls to survive deeply + // nested trees. Children are rehydrated before their parent node + // is constructed. + let result + let stack = [ + { childIndex: 0, children: [], inputs: hydrateInputs(json, inputs), json } + ] + + while (stack.length > 0) { + let frame = stack[stack.length - 1] + let jsonNodes = frame.json.nodes + + if (jsonNodes && frame.childIndex < jsonNodes.length) { + let childJson = jsonNodes[frame.childIndex] + frame.childIndex += 1 + stack.push({ + childIndex: 0, + children: [], + inputs: hydrateInputs(childJson, frame.inputs), + json: childJson + }) + continue + } + + stack.pop() + let node = constructNode( + frame.json, + frame.inputs, + jsonNodes ? frame.children : undefined + ) + if (stack.length > 0) { + stack[stack.length - 1].children.push(node) + } else { + result = node + } + } + + return result } module.exports = fromJSON @@ -68683,21 +73330,40 @@ fromJSON.default = fromJSON "use strict"; -let { SourceMapConsumer, SourceMapGenerator } = __nccwpck_require__(6766) -let { fileURLToPath, pathToFileURL } = __nccwpck_require__(7310) -let { resolve, isAbsolute } = __nccwpck_require__(1017) -let { nanoid } = __nccwpck_require__(3163) +let { nanoid } = __nccwpck_require__(83163) +let { isAbsolute, resolve } = __nccwpck_require__(71017) +let { SourceMapConsumer, SourceMapGenerator } = __nccwpck_require__(26766) +let { fileURLToPath, pathToFileURL } = __nccwpck_require__(57310) -let terminalHighlight = __nccwpck_require__(1040) -let CssSyntaxError = __nccwpck_require__(3279) -let PreviousMap = __nccwpck_require__(1090) +let CssSyntaxError = __nccwpck_require__(63279) +let PreviousMap = __nccwpck_require__(91090) +let terminalHighlight = __nccwpck_require__(51040) -let fromOffsetCache = Symbol('fromOffsetCache') +let lineToIndexCache = Symbol('lineToIndexCache') let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) let pathAvailable = Boolean(resolve && isAbsolute) +function getLineToIndex(input) { + if (input[lineToIndexCache]) return input[lineToIndexCache] + let lines = input.css.split('\n') + let lineToIndex = new Array(lines.length) + let prevIndex = 0 + + for (let i = 0, l = lines.length; i < l; i++) { + lineToIndex[i] = prevIndex + prevIndex += lines[i].length + 1 + } + + input[lineToIndexCache] = lineToIndex + return lineToIndex +} + class Input { + get from() { + return this.file || this.id + } + constructor(css, opts = {}) { if ( css === null || @@ -68716,6 +73382,9 @@ class Input { this.hasBOM = false } + this.document = this.css + if (opts.document) this.document = opts.document.toString() + if (opts.from) { if ( !pathAvailable || @@ -68743,74 +73412,39 @@ class Input { if (this.map) this.map.file = this.from } - fromOffset(offset) { - let lastLine, lineToIndex - if (!this[fromOffsetCache]) { - let lines = this.css.split('\n') - lineToIndex = new Array(lines.length) - let prevIndex = 0 - - for (let i = 0, l = lines.length; i < l; i++) { - lineToIndex[i] = prevIndex - prevIndex += lines[i].length + 1 - } - - this[fromOffsetCache] = lineToIndex - } else { - lineToIndex = this[fromOffsetCache] - } - lastLine = lineToIndex[lineToIndex.length - 1] - - let min = 0 - if (offset >= lastLine) { - min = lineToIndex.length - 1 - } else { - let max = lineToIndex.length - 2 - let mid - while (min < max) { - mid = min + ((max - min) >> 1) - if (offset < lineToIndex[mid]) { - max = mid - 1 - } else if (offset >= lineToIndex[mid + 1]) { - min = mid + 1 - } else { - min = mid - break - } - } - } - return { - line: min + 1, - col: offset - lineToIndex[min] + 1 - } - } - error(message, line, column, opts = {}) { - let result, endLine, endColumn + let endColumn, endLine, endOffset, offset, result if (line && typeof line === 'object') { let start = line let end = column - if (typeof line.offset === 'number') { - let pos = this.fromOffset(start.offset) + if (typeof start.offset === 'number') { + offset = start.offset + let pos = this.fromOffset(offset) line = pos.line column = pos.col } else { line = start.line column = start.column + offset = this.fromLineAndColumn(line, column) } if (typeof end.offset === 'number') { - let pos = this.fromOffset(end.offset) + endOffset = end.offset + let pos = this.fromOffset(endOffset) endLine = pos.line endColumn = pos.col } else { endLine = end.line endColumn = end.column + endOffset = this.fromLineAndColumn(end.line, end.column) } } else if (!column) { - let pos = this.fromOffset(line) + offset = line + let pos = this.fromOffset(offset) line = pos.line column = pos.col + } else { + offset = this.fromLineAndColumn(line, column) } let origin = this.origin(line, column, endLine, endColumn) @@ -68819,10 +73453,10 @@ class Input { message, origin.endLine === undefined ? origin.line - : { line: origin.line, column: origin.column }, + : { column: origin.column, line: origin.line }, origin.endLine === undefined ? origin.column - : { line: origin.endLine, column: origin.endColumn }, + : { column: origin.endColumn, line: origin.endLine }, origin.source, origin.file, opts.plugin @@ -68830,15 +73464,23 @@ class Input { } else { result = new CssSyntaxError( message, - endLine === undefined ? line : { line, column }, - endLine === undefined ? column : { line: endLine, column: endColumn }, + endLine === undefined ? line : { column, line }, + endLine === undefined ? column : { column: endColumn, line: endLine }, this.css, this.file, opts.plugin ) } - result.input = { line, column, endLine, endColumn, source: this.css } + result.input = { + column, + endColumn, + endLine, + endOffset, + line, + offset, + source: this.css + } if (this.file) { if (pathToFileURL) { result.input.url = pathToFileURL(this.file).toString() @@ -68849,16 +73491,66 @@ class Input { return result } + fromLineAndColumn(line, column) { + let lineToIndex = getLineToIndex(this) + let index = lineToIndex[line - 1] + return index + column - 1 + } + + fromOffset(offset) { + let lineToIndex = getLineToIndex(this) + let lastLine = lineToIndex[lineToIndex.length - 1] + + let min = 0 + if (offset >= lastLine) { + min = lineToIndex.length - 1 + } else { + let max = lineToIndex.length - 2 + let mid + while (min < max) { + mid = min + ((max - min) >> 1) + if (offset < lineToIndex[mid]) { + max = mid - 1 + } else if (offset >= lineToIndex[mid + 1]) { + min = mid + 1 + } else { + min = mid + break + } + } + } + return { + col: offset - lineToIndex[min] + 1, + line: min + 1 + } + } + + mapResolve(file) { + if (/^\w+:\/\//.test(file)) { + return file + } + return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file) + } + origin(line, column, endLine, endColumn) { if (!this.map) return false let consumer = this.map.consumer() - let from = consumer.originalPositionFor({ line, column }) + let from = consumer.originalPositionFor({ column: column - 1, line }) if (!from.source) return false let to if (typeof endLine === 'number') { - to = consumer.originalPositionFor({ line: endLine, column: endColumn }) + let toPosition = consumer.originalPositionFor({ + column: endColumn - 1, + line: endLine + }) + // The source map may not have a mapping that covers the end position + // (`originalPositionFor()` then returns `null` for `line`/`column` + // instead of omitting them). Treat that the same as not requesting + // an end position at all, so `endLine`/`endColumn` stay a consistent + // `undefined` pair instead of a mix of `null` and a bogus number. + if (toPosition.source) to = toPosition } let fromUrl @@ -68873,11 +73565,11 @@ class Input { } let result = { - url: fromUrl.toString(), - line: from.line, - column: from.column, + column: from.column + 1, + endColumn: to && to.column + 1, endLine: to && to.line, - endColumn: to && to.column + line: from.line, + url: fromUrl.toString() } if (fromUrl.protocol === 'file:') { @@ -68895,17 +73587,6 @@ class Input { return result } - mapResolve(file) { - if (/^\w+:\/\//.test(file)) { - return file - } - return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file) - } - - get from() { - return this.file || this.id - } - toJSON() { let json = {} for (let name of ['hasBOM', 'css', 'file', 'id']) { @@ -68933,54 +73614,54 @@ if (terminalHighlight && terminalHighlight.registerInput) { /***/ }), -/***/ 6310: +/***/ 46310: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let { isClean, my } = __nccwpck_require__(2594) -let MapGenerator = __nccwpck_require__(3091) -let stringify = __nccwpck_require__(4793) -let Container = __nccwpck_require__(6919) -let Document = __nccwpck_require__(8085) -let warnOnce = __nccwpck_require__(1600) -let Result = __nccwpck_require__(6846) +let Container = __nccwpck_require__(56919) +let Document = __nccwpck_require__(58085) +let MapGenerator = __nccwpck_require__(93091) let parse = __nccwpck_require__(2128) -let Root = __nccwpck_require__(2630) +let Result = __nccwpck_require__(66846) +let Root = __nccwpck_require__(22630) +let stringify = __nccwpck_require__(34793) +let { isClean, my } = __nccwpck_require__(32594) +let warnOnce = __nccwpck_require__(21600) const TYPE_TO_CLASS_NAME = { - document: 'Document', - root: 'Root', atrule: 'AtRule', - rule: 'Rule', + comment: 'Comment', decl: 'Declaration', - comment: 'Comment' + document: 'Document', + root: 'Root', + rule: 'Rule' } const PLUGIN_PROPS = { - postcssPlugin: true, - prepare: true, - Once: true, - Document: true, - Root: true, - Declaration: true, - Rule: true, AtRule: true, - Comment: true, - DeclarationExit: true, - RuleExit: true, AtRuleExit: true, + Comment: true, CommentExit: true, - RootExit: true, + Declaration: true, + DeclarationExit: true, + Document: true, DocumentExit: true, - OnceExit: true + Once: true, + OnceExit: true, + postcssPlugin: true, + prepare: true, + Root: true, + RootExit: true, + Rule: true, + RuleExit: true } const NOT_VISITORS = { + Once: true, postcssPlugin: true, - prepare: true, - Once: true + prepare: true } const CHILDREN = 0 @@ -69026,24 +73707,62 @@ function toStack(node) { } return { - node, - events, eventIndex: 0, - visitors: [], + events, + iterator: 0, + node, visitorIndex: 0, - iterator: 0 + visitors: [] } } function cleanMarks(node) { - node[isClean] = false - if (node.nodes) node.nodes.forEach(i => cleanMarks(i)) + let stack = [node] + while (stack.length > 0) { + let next = stack.pop() + next[isClean] = false + if (next.nodes) { + for (let i of next.nodes) stack.push(i) + } + } return node } let postcss = {} class LazyResult { + get content() { + return this.stringify().content + } + + get css() { + return this.stringify().css + } + + get map() { + return this.stringify().map + } + + get messages() { + return this.sync().messages + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + + get root() { + return this.sync().root + } + + get [Symbol.toStringTag]() { + return 'LazyResult' + } + constructor(processor, css, opts) { this.stringified = false this.processed = false @@ -69082,7 +73801,7 @@ class LazyResult { } this.result = new Result(processor, root, opts) - this.helpers = { ...postcss, result: this.result, postcss } + this.helpers = { ...postcss, postcss, result: this.result } this.plugins = this.processor.plugins.map(plugin => { if (typeof plugin === 'object' && plugin.prepare) { return { ...plugin, ...plugin.prepare(this.result) } @@ -69092,67 +73811,6 @@ class LazyResult { }) } - get [Symbol.toStringTag]() { - return 'LazyResult' - } - - get processor() { - return this.result.processor - } - - get opts() { - return this.result.opts - } - - get css() { - return this.stringify().css - } - - get content() { - return this.stringify().content - } - - get map() { - return this.stringify().map - } - - get root() { - return this.sync().root - } - - get messages() { - return this.sync().messages - } - - warnings() { - return this.sync().warnings() - } - - toString() { - return this.css - } - - then(onFulfilled, onRejected) { - if (process.env.NODE_ENV !== 'production') { - if (!('from' in this.opts)) { - warnOnce( - 'Without `from` option PostCSS could generate wrong source map ' + - 'and will not find Browserslist config. Set it to CSS file path ' + - 'or to `undefined` to prevent this warning.' - ) - } - } - return this.async().then(onFulfilled, onRejected) - } - - catch(onRejected) { - return this.async().catch(onRejected) - } - - finally(onFinally) { - return this.async().then(onFinally, onFinally) - } - async() { if (this.error) return Promise.reject(this.error) if (this.processed) return Promise.resolve(this.result) @@ -69162,124 +73820,12 @@ class LazyResult { return this.processing } - sync() { - if (this.error) throw this.error - if (this.processed) return this.result - this.processed = true - - if (this.processing) { - throw this.getAsyncError() - } - - for (let plugin of this.plugins) { - let promise = this.runOnRoot(plugin) - if (isPromise(promise)) { - throw this.getAsyncError() - } - } - - this.prepareVisitors() - if (this.hasListener) { - let root = this.result.root - while (!root[isClean]) { - root[isClean] = true - this.walkSync(root) - } - if (this.listeners.OnceExit) { - if (root.type === 'document') { - for (let subRoot of root.nodes) { - this.visitSync(this.listeners.OnceExit, subRoot) - } - } else { - this.visitSync(this.listeners.OnceExit, root) - } - } - } - - return this.result - } - - stringify() { - if (this.error) throw this.error - if (this.stringified) return this.result - this.stringified = true - - this.sync() - - let opts = this.result.opts - let str = stringify - if (opts.syntax) str = opts.syntax.stringify - if (opts.stringifier) str = opts.stringifier - if (str.stringify) str = str.stringify - - let map = new MapGenerator(str, this.result.root, this.result.opts) - let data = map.generate() - this.result.css = data[0] - this.result.map = data[1] - - return this.result - } - - walkSync(node) { - node[isClean] = true - let events = getEvents(node) - for (let event of events) { - if (event === CHILDREN) { - if (node.nodes) { - node.each(child => { - if (!child[isClean]) this.walkSync(child) - }) - } - } else { - let visitors = this.listeners[event] - if (visitors) { - if (this.visitSync(visitors, node.toProxy())) return - } - } - } - } - - visitSync(visitors, node) { - for (let [plugin, visitor] of visitors) { - this.result.lastPlugin = plugin - let promise - try { - promise = visitor(node, this.helpers) - } catch (e) { - throw this.handleError(e, node.proxyOf) - } - if (node.type !== 'root' && node.type !== 'document' && !node.parent) { - return true - } - if (isPromise(promise)) { - throw this.getAsyncError() - } - } + catch(onRejected) { + return this.async().catch(onRejected) } - runOnRoot(plugin) { - this.result.lastPlugin = plugin - try { - if (typeof plugin === 'object' && plugin.Once) { - if (this.result.root.type === 'document') { - let roots = this.result.root.nodes.map(root => - plugin.Once(root, this.helpers) - ) - - if (isPromise(roots[0])) { - return Promise.all(roots) - } - - return roots - } - - return plugin.Once(this.result.root, this.helpers) - } else if (typeof plugin === 'function') { - return plugin(this.result.root, this.result) - } - } catch (error) { - throw this.handleError(error) - } + finally(onFinally) { + return this.async().then(onFinally, onFinally) } getAsyncError() { @@ -69325,6 +73871,44 @@ class LazyResult { return error } + prepareVisitors() { + this.listeners = {} + let add = (plugin, type, cb) => { + if (!this.listeners[type]) this.listeners[type] = [] + this.listeners[type].push([plugin, cb]) + } + for (let plugin of this.plugins) { + if (typeof plugin === 'object') { + for (let event in plugin) { + if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { + throw new Error( + `Unknown event ${event} in ${plugin.postcssPlugin}. ` + + `Try to update PostCSS (${this.processor.version} now).` + ) + } + if (!NOT_VISITORS[event]) { + if (typeof plugin[event] === 'object') { + for (let filter in plugin[event]) { + if (filter === '*') { + add(plugin, event, plugin[event][filter]) + } else { + add( + plugin, + event + '-' + filter.toLowerCase(), + plugin[event][filter] + ) + } + } + } else if (typeof plugin[event] === 'function') { + add(plugin, event, plugin[event]) + } + } + } + } + } + this.hasListener = Object.keys(this.listeners).length > 0 + } + async runAsync() { this.plugin = 0 for (let i = 0; i < this.plugins.length; i++) { @@ -69382,42 +73966,135 @@ class LazyResult { return this.stringify() } - prepareVisitors() { - this.listeners = {} - let add = (plugin, type, cb) => { - if (!this.listeners[type]) this.listeners[type] = [] - this.listeners[type].push([plugin, cb]) + runOnRoot(plugin) { + this.result.lastPlugin = plugin + try { + if (typeof plugin === 'object' && plugin.Once) { + if (this.result.root.type === 'document') { + let roots = this.result.root.nodes.map(root => + plugin.Once(root, this.helpers) + ) + + if (isPromise(roots[0])) { + return Promise.all(roots) + } + + return roots + } + + return plugin.Once(this.result.root, this.helpers) + } else if (typeof plugin === 'function') { + return plugin(this.result.root, this.result) + } + } catch (error) { + throw this.handleError(error) + } + } + + stringify() { + if (this.error) throw this.error + if (this.stringified) return this.result + this.stringified = true + + this.sync() + + let opts = this.result.opts + let str = stringify + if (opts.syntax) str = opts.syntax.stringify + if (opts.stringifier) str = opts.stringifier + if (str.stringify) str = str.stringify + + let rootSource = this.result.root.source + if ( + opts.map === undefined && + !(rootSource && rootSource.input && rootSource.input.map) + ) { + let result = '' + str(this.result.root, i => { + result += i + }) + this.result.css = result + return this.result + } + + let map = new MapGenerator(str, this.result.root, this.result.opts) + let data = map.generate() + this.result.css = data[0] + this.result.map = data[1] + + return this.result + } + + sync() { + if (this.error) throw this.error + if (this.processed) return this.result + this.processed = true + + if (this.processing) { + throw this.getAsyncError() } + for (let plugin of this.plugins) { - if (typeof plugin === 'object') { - for (let event in plugin) { - if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { - throw new Error( - `Unknown event ${event} in ${plugin.postcssPlugin}. ` + - `Try to update PostCSS (${this.processor.version} now).` - ) - } - if (!NOT_VISITORS[event]) { - if (typeof plugin[event] === 'object') { - for (let filter in plugin[event]) { - if (filter === '*') { - add(plugin, event, plugin[event][filter]) - } else { - add( - plugin, - event + '-' + filter.toLowerCase(), - plugin[event][filter] - ) - } - } - } else if (typeof plugin[event] === 'function') { - add(plugin, event, plugin[event]) - } + let promise = this.runOnRoot(plugin) + if (isPromise(promise)) { + throw this.getAsyncError() + } + } + + this.prepareVisitors() + if (this.hasListener) { + let root = this.result.root + while (!root[isClean]) { + root[isClean] = true + this.walkSync(root) + } + if (this.listeners.OnceExit) { + if (root.type === 'document') { + for (let subRoot of root.nodes) { + this.visitSync(this.listeners.OnceExit, subRoot) } + } else { + this.visitSync(this.listeners.OnceExit, root) } } } - this.hasListener = Object.keys(this.listeners).length > 0 + + return this.result + } + + then(onFulfilled, onRejected) { + if (process.env.NODE_ENV !== 'production') { + if (!('from' in this.opts)) { + warnOnce( + 'Without `from` option PostCSS could generate wrong source map ' + + 'and will not find Browserslist config. Set it to CSS file path ' + + 'or to `undefined` to prevent this warning.' + ) + } + } + return this.async().then(onFulfilled, onRejected) + } + + toString() { + return this.css + } + + visitSync(visitors, node) { + for (let [plugin, visitor] of visitors) { + this.result.lastPlugin = plugin + let promise + try { + promise = visitor(node, this.helpers) + } catch (e) { + throw this.handleError(e, node.proxyOf) + } + if (node.type !== 'root' && node.type !== 'document' && !node.parent) { + return true + } + if (isPromise(promise)) { + throw this.getAsyncError() + } + } } visitTick(stack) { @@ -69476,6 +74153,65 @@ class LazyResult { } stack.pop() } + + walkSync(node) { + // An explicit stack like in async `visitTick()` to survive deeply + // nested trees. Unlike `visitTick()`, nodes are marked clean only + // on entering, so a node dirtied by its own visitors is revisited + // on the next pass. + node[isClean] = true + let stack = [{ eventIndex: 0, events: getEvents(node), iterator: 0, node }] + + while (stack.length > 0) { + let visit = stack[stack.length - 1] + let visitNode = visit.node + + if (visit.iterator !== 0) { + let iterator = visit.iterator + let child + let descended = false + while ((child = visitNode.nodes[visitNode.indexes[iterator]])) { + visitNode.indexes[iterator] += 1 + if (!child[isClean]) { + child[isClean] = true + stack.push({ + eventIndex: 0, + events: getEvents(child), + iterator: 0, + node: child + }) + descended = true + break + } + } + if (descended) continue + visit.iterator = 0 + delete visitNode.indexes[iterator] + } + + if (visit.eventIndex < visit.events.length) { + let event = visit.events[visit.eventIndex] + visit.eventIndex += 1 + if (event === CHILDREN) { + if (visitNode.nodes && visitNode.nodes.length) { + visit.iterator = visitNode.getIterator() + } + } else { + let visitors = this.listeners[event] + if (visitors) { + if (this.visitSync(visitors, visitNode.toProxy())) stack.pop() + } + } + continue + } + + stack.pop() + } + } + + warnings() { + return this.sync().warnings() + } } LazyResult.registerPostcss = dependant => { @@ -69491,20 +74227,30 @@ Document.registerLazyResult(LazyResult) /***/ }), -/***/ 1608: +/***/ 41608: /***/ ((module) => { "use strict"; let list = { + comma(string) { + return list.split(string, [','], true) + }, + + space(string) { + let spaces = [' ', '\n', '\t'] + return list.split(string, spaces) + }, + split(string, separators, last) { let array = [] let current = '' let split = false let func = 0 - let quote = false + let inQuote = false + let prevQuote = '' let escape = false for (let letter of string) { @@ -69512,12 +74258,13 @@ let list = { escape = false } else if (letter === '\\') { escape = true - } else if (quote) { - if (letter === quote) { - quote = false + } else if (inQuote) { + if (letter === prevQuote) { + inQuote = false } } else if (letter === '"' || letter === "'") { - quote = letter + inQuote = true + prevQuote = letter } else if (letter === '(') { func += 1 } else if (letter === ')') { @@ -69537,15 +74284,6 @@ let list = { if (last || current !== '') array.push(current.trim()) return array - }, - - space(string) { - let spaces = [' ', '\n', '\t'] - return list.split(string, spaces) - }, - - comma(string) { - return list.split(string, [','], true) } } @@ -69555,15 +74293,15 @@ list.default = list /***/ }), -/***/ 3091: +/***/ 93091: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let { SourceMapConsumer, SourceMapGenerator } = __nccwpck_require__(6766) -let { dirname, resolve, relative, sep } = __nccwpck_require__(1017) -let { pathToFileURL } = __nccwpck_require__(7310) +let { dirname, relative, resolve, sep } = __nccwpck_require__(71017) +let { SourceMapConsumer, SourceMapGenerator } = __nccwpck_require__(26766) +let { pathToFileURL } = __nccwpck_require__(57310) let Input = __nccwpck_require__(2690) @@ -69577,100 +74315,31 @@ class MapGenerator { this.root = root this.opts = opts this.css = cssString - } - - isMap() { - if (typeof this.opts.map !== 'undefined') { - return !!this.opts.map - } - return this.previous().length > 0 - } - - previous() { - if (!this.previousMaps) { - this.previousMaps = [] - if (this.root) { - this.root.walk(node => { - if (node.source && node.source.input.map) { - let map = node.source.input.map - if (!this.previousMaps.includes(map)) { - this.previousMaps.push(map) - } - } - }) - } else { - let input = new Input(this.css, this.opts) - if (input.map) this.previousMaps.push(input.map) - } - } - - return this.previousMaps - } - - isInline() { - if (typeof this.mapOpts.inline !== 'undefined') { - return this.mapOpts.inline - } - - let annotation = this.mapOpts.annotation - if (typeof annotation !== 'undefined' && annotation !== true) { - return false - } - - if (this.previous().length) { - return this.previous().some(i => i.inline) - } - return true - } + this.originalCSS = cssString + this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute - isSourcesContent() { - if (typeof this.mapOpts.sourcesContent !== 'undefined') { - return this.mapOpts.sourcesContent - } - if (this.previous().length) { - return this.previous().some(i => i.withContent()) - } - return true + this.memoizedFileURLs = new Map() + this.memoizedPaths = new Map() + this.memoizedURLs = new Map() } - clearAnnotation() { - if (this.mapOpts.annotation === false) return + addAnnotation() { + let content - if (this.root) { - let node - for (let i = this.root.nodes.length - 1; i >= 0; i--) { - node = this.root.nodes[i] - if (node.type !== 'comment') continue - if (node.text.indexOf('# sourceMappingURL=') === 0) { - this.root.removeChild(i) - } - } - } else if (this.css) { - this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, '') + if (this.isInline()) { + content = + 'data:application/json;base64,' + this.toBase64(this.map.toString()) + } else if (typeof this.mapOpts.annotation === 'string') { + content = this.mapOpts.annotation + } else if (typeof this.mapOpts.annotation === 'function') { + content = this.mapOpts.annotation(this.opts.to, this.root) + } else { + content = this.outputFile() + '.map' } - } + let eol = '\n' + if (this.css.includes('\r\n')) eol = '\r\n' - setSourcesContent() { - let already = {} - if (this.root) { - this.root.walk(node => { - if (node.source) { - let from = node.source.input.from - if (from && !already[from]) { - already[from] = true - this.map.setSourceContent( - this.toUrl(this.path(from)), - node.source.input.css - ) - } - } - }) - } else if (this.css) { - let from = this.opts.from - ? this.toUrl(this.path(this.opts.from)) - : '' - this.map.setSourceContent(from, this.css) - } + this.css += eol + '/*# sourceMappingURL=' + content + ' */' } applyPrevMaps() { @@ -69682,7 +74351,7 @@ class MapGenerator { if (this.mapOpts.sourcesContent === false) { map = new SourceMapConsumer(prev.text) if (map.sourcesContent) { - map.sourcesContent = map.sourcesContent.map(() => null) + map.sourcesContent = null } } else { map = prev.consumer() @@ -69692,53 +74361,41 @@ class MapGenerator { } } - isAnnotation() { - if (this.isInline()) { - return true - } - if (typeof this.mapOpts.annotation !== 'undefined') { - return this.mapOpts.annotation - } - if (this.previous().length) { - return this.previous().some(i => i.annotation) - } - return true - } - - toBase64(str) { - if (Buffer) { - return Buffer.from(str).toString('base64') - } else { - return window.btoa(unescape(encodeURIComponent(str))) - } - } - - addAnnotation() { - let content + clearAnnotation() { + if (this.mapOpts.annotation === false) return - if (this.isInline()) { - content = - 'data:application/json;base64,' + this.toBase64(this.map.toString()) - } else if (typeof this.mapOpts.annotation === 'string') { - content = this.mapOpts.annotation - } else if (typeof this.mapOpts.annotation === 'function') { - content = this.mapOpts.annotation(this.opts.to, this.root) - } else { - content = this.outputFile() + '.map' + if (this.root) { + let node + for (let i = this.root.nodes.length - 1; i >= 0; i--) { + node = this.root.nodes[i] + if (node.type !== 'comment') continue + if (node.text.startsWith('# sourceMappingURL=')) { + this.root.removeChild(i) + } + } + } else if (this.css) { + let startIndex + while ((startIndex = this.css.lastIndexOf('/*#')) !== -1) { + let endIndex = this.css.indexOf('*/', startIndex + 3) + if (endIndex === -1) break + while (startIndex > 0 && this.css[startIndex - 1] === '\n') { + startIndex-- + } + this.css = this.css.slice(0, startIndex) + this.css.slice(endIndex + 2) + } } - let eol = '\n' - if (this.css.includes('\r\n')) eol = '\r\n' - - this.css += eol + '/*# sourceMappingURL=' + content + ' */' } - outputFile() { - if (this.opts.to) { - return this.path(this.opts.to) - } else if (this.opts.from) { - return this.path(this.opts.from) + generate() { + this.clearAnnotation() + if (pathAvailable && sourceMapAvailable && this.isMap()) { + return this.generateMap() } else { - return 'to.css' + let result = '' + this.stringify(this.root, i => { + result += i + }) + return [result] } } @@ -69748,15 +74405,20 @@ class MapGenerator { } else if (this.previous().length === 1) { let prev = this.previous()[0].consumer() prev.file = this.outputFile() - this.map = SourceMapGenerator.fromSourceMap(prev) + this.map = SourceMapGenerator.fromSourceMap(prev, { + ignoreInvalidMapping: true + }) } else { - this.map = new SourceMapGenerator({ file: this.outputFile() }) + this.map = new SourceMapGenerator({ + file: this.outputFile(), + ignoreInvalidMapping: true + }) this.map.addMapping({ + generated: { column: 0, line: 1 }, + original: { column: 0, line: 1 }, source: this.opts.from ? this.toUrl(this.path(this.opts.from)) - : '', - generated: { line: 1, column: 0 }, - original: { line: 1, column: 0 } + : '' }) } @@ -69771,59 +74433,24 @@ class MapGenerator { } } - path(file) { - if (file.indexOf('<') === 0) return file - if (/^\w+:\/\//.test(file)) return file - if (this.mapOpts.absolute) return file - - let from = this.opts.to ? dirname(this.opts.to) : '.' - - if (typeof this.mapOpts.annotation === 'string') { - from = dirname(resolve(from, this.mapOpts.annotation)) - } - - file = relative(from, file) - return file - } - - toUrl(path) { - if (sep === '\\') { - path = path.replace(/\\/g, '/') - } - return encodeURI(path).replace(/[#?]/g, encodeURIComponent) - } - - sourcePath(node) { - if (this.mapOpts.from) { - return this.toUrl(this.mapOpts.from) - } else if (this.mapOpts.absolute) { - if (pathToFileURL) { - return pathToFileURL(node.source.input.from).toString() - } else { - throw new Error( - '`map.absolute` option is not available in this PostCSS build' - ) - } - } else { - return this.toUrl(this.path(node.source.input.from)) - } - } - generateString() { this.css = '' - this.map = new SourceMapGenerator({ file: this.outputFile() }) + this.map = new SourceMapGenerator({ + file: this.outputFile(), + ignoreInvalidMapping: true + }) let line = 1 let column = 1 let noSource = '' let mapping = { - source: '', - generated: { line: 0, column: 0 }, - original: { line: 0, column: 0 } + generated: { column: 0, line: 0 }, + original: { column: 0, line: 0 }, + source: '' } - let lines, last + let last, lines this.stringify(this.root, (str, node, type) => { this.css += str @@ -69854,7 +74481,9 @@ class MapGenerator { if (node && type !== 'start') { let p = node.parent || { raws: {} } - if (node.type !== 'decl' || node !== p.last || p.raws.semicolon) { + let childless = + node.type === 'decl' || (node.type === 'atrule' && !node.nodes) + if (!childless || node !== p.last || p.raws.semicolon) { if (node.source && node.source.end) { mapping.source = this.sourcePath(node) mapping.original.line = node.source.end.line @@ -69875,95 +74504,216 @@ class MapGenerator { }) } - generate() { - this.clearAnnotation() - if (pathAvailable && sourceMapAvailable && this.isMap()) { - return this.generateMap() - } else { - let result = '' - this.stringify(this.root, i => { - result += i - }) - return [result] + isAnnotation() { + if (this.isInline()) { + return true + } + if (typeof this.mapOpts.annotation !== 'undefined') { + return this.mapOpts.annotation } + if (this.previous().length) { + return this.previous().some(i => i.annotation) + } + return true } -} -module.exports = MapGenerator + isInline() { + if (typeof this.mapOpts.inline !== 'undefined') { + return this.mapOpts.inline + } + let annotation = this.mapOpts.annotation + if (typeof annotation !== 'undefined' && annotation !== true) { + return false + } -/***/ }), + if (this.previous().length) { + return this.previous().some(i => i.inline) + } + return true + } -/***/ 9810: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + isMap() { + if (typeof this.opts.map !== 'undefined') { + return !!this.opts.map + } + return this.previous().length > 0 + } -"use strict"; + isSourcesContent() { + if (typeof this.mapOpts.sourcesContent !== 'undefined') { + return this.mapOpts.sourcesContent + } + if (this.previous().length) { + return this.previous().some(i => i.withContent()) + } + return true + } + outputFile() { + if (this.opts.to) { + return this.path(this.opts.to) + } else if (this.opts.from) { + return this.path(this.opts.from) + } else { + return 'to.css' + } + } -let MapGenerator = __nccwpck_require__(3091) -let stringify = __nccwpck_require__(4793) -let warnOnce = __nccwpck_require__(1600) -let parse = __nccwpck_require__(2128) -const Result = __nccwpck_require__(6846) + path(file) { + if (this.mapOpts.absolute) return file + if (file.charCodeAt(0) === 60 /* `<` */) return file + if (/^\w+:\/\//.test(file)) return file + let cached = this.memoizedPaths.get(file) + if (cached) return cached -class NoWorkResult { - constructor(processor, css, opts) { - css = css.toString() - this.stringified = false + let from = this.opts.to ? dirname(this.opts.to) : '.' - this._processor = processor - this._css = css - this._opts = opts - this._map = undefined - let root + if (typeof this.mapOpts.annotation === 'string') { + from = dirname(resolve(from, this.mapOpts.annotation)) + } - let str = stringify - this.result = new Result(this._processor, root, this._opts) - this.result.css = css + let path = relative(from, file) + this.memoizedPaths.set(file, path) - let self = this - Object.defineProperty(this.result, 'root', { - get() { - return self.root - } - }) + return path + } - let map = new MapGenerator(str, root, this._opts, css) - if (map.isMap()) { - let [generatedCSS, generatedMap] = map.generate() - if (generatedCSS) { - this.result.css = generatedCSS - } - if (generatedMap) { - this.result.map = generatedMap + previous() { + if (!this.previousMaps) { + this.previousMaps = [] + if (this.root) { + this.root.walk(node => { + if (node.source && node.source.input.map) { + let map = node.source.input.map + if (!this.previousMaps.includes(map)) { + this.previousMaps.push(map) + } + } + }) + } else { + let input = new Input(this.originalCSS, this.opts) + if (input.map) this.previousMaps.push(input.map) } } + + return this.previousMaps } - get [Symbol.toStringTag]() { - return 'NoWorkResult' + setSourcesContent() { + let already = {} + if (this.root) { + this.root.walk(node => { + if (node.source) { + let from = node.source.input.from + if (from && !already[from]) { + already[from] = true + let fromUrl = this.usesFileUrls + ? this.toFileUrl(from) + : this.toUrl(this.path(from)) + this.map.setSourceContent(fromUrl, node.source.input.css) + } + } + }) + } else if (this.css) { + let from = this.opts.from + ? this.toUrl(this.path(this.opts.from)) + : '' + this.map.setSourceContent(from, this.css) + } } - get processor() { - return this.result.processor + sourcePath(node) { + if (this.mapOpts.from) { + return this.toUrl(this.mapOpts.from) + } else if (this.usesFileUrls) { + return this.toFileUrl(node.source.input.from) + } else { + return this.toUrl(this.path(node.source.input.from)) + } } - get opts() { - return this.result.opts + toBase64(str) { + if (Buffer) { + return Buffer.from(str).toString('base64') + } else { + return window.btoa(unescape(encodeURIComponent(str))) + } } - get css() { - return this.result.css + toFileUrl(path) { + let cached = this.memoizedFileURLs.get(path) + if (cached) return cached + + if (pathToFileURL) { + let fileURL = pathToFileURL(path).toString() + this.memoizedFileURLs.set(path, fileURL) + + return fileURL + } else { + throw new Error( + '`map.absolute` option is not available in this PostCSS build' + ) + } + } + + toUrl(path) { + let cached = this.memoizedURLs.get(path) + if (cached) return cached + + if (sep === '\\') { + path = path.replace(/\\/g, '/') + } + + let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent) + this.memoizedURLs.set(path, url) + + return url } +} +module.exports = MapGenerator + + +/***/ }), + +/***/ 69810: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +let MapGenerator = __nccwpck_require__(93091) +let parse = __nccwpck_require__(2128) +let Result = __nccwpck_require__(66846) +let stringify = __nccwpck_require__(34793) +let warnOnce = __nccwpck_require__(21600) + +class NoWorkResult { get content() { return this.result.css } + get css() { + return this.result.css + } + get map() { return this.result.map } + get messages() { + return [] + } + + get opts() { + return this.result.opts + } + + get processor() { + return this.result.processor + } + get root() { if (this._root) { return this._root @@ -69986,16 +74736,61 @@ class NoWorkResult { } } - get messages() { - return [] + get [Symbol.toStringTag]() { + return 'NoWorkResult' } - warnings() { - return [] + constructor(processor, css, opts) { + css = css.toString() + this.stringified = false + + this._processor = processor + this._css = css + this._opts = opts + this._map = undefined + + let str = stringify + this.result = new Result(this._processor, undefined, this._opts) + this.result.css = css + + let self = this + Object.defineProperty(this.result, 'root', { + get() { + return self.root + } + }) + + let map = new MapGenerator(str, undefined, this._opts, css) + if (map.isMap()) { + let [generatedCSS, generatedMap] = map.generate() + if (generatedCSS) { + this.result.css = generatedCSS + } + if (generatedMap) { + this.result.map = generatedMap + } + } else { + map.clearAnnotation() + this.result.css = map.css + } } - toString() { - return this._css + async() { + if (this.error) return Promise.reject(this.error) + return Promise.resolve(this.result) + } + + catch(onRejected) { + return this.async().catch(onRejected) + } + + finally(onFinally) { + return this.async().then(onFinally, onFinally) + } + + sync() { + if (this.error) throw this.error + return this.result } then(onFulfilled, onRejected) { @@ -70012,22 +74807,12 @@ class NoWorkResult { return this.async().then(onFulfilled, onRejected) } - catch(onRejected) { - return this.async().catch(onRejected) - } - - finally(onFinally) { - return this.async().then(onFinally, onFinally) - } - - async() { - if (this.error) return Promise.reject(this.error) - return Promise.resolve(this.result) + toString() { + return this._css } - sync() { - if (this.error) throw this.error - return this.result + warnings() { + return [] } } @@ -70037,55 +74822,106 @@ NoWorkResult.default = NoWorkResult /***/ }), -/***/ 8557: +/***/ 48557: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let { isClean, my } = __nccwpck_require__(2594) -let CssSyntaxError = __nccwpck_require__(3279) -let Stringifier = __nccwpck_require__(9414) -let stringify = __nccwpck_require__(4793) +let CssSyntaxError = __nccwpck_require__(63279) +let Stringifier = __nccwpck_require__(59414) +let stringify = __nccwpck_require__(34793) +let { isClean, my } = __nccwpck_require__(32594) function cloneNode(obj, parent) { let cloned = new obj.constructor() + // An explicit stack instead of recursive calls to survive deeply + // nested trees. Each entry is [source, its clone, clone's parent]. + let stack = [[obj, cloned, parent]] + + while (stack.length > 0) { + let [source, target, targetParent] = stack.pop() + for (let i in source) { + if (!Object.prototype.hasOwnProperty.call(source, i)) { + /* c8 ignore next 2 */ + continue + } + if (i === 'proxyCache') continue + let value = source[i] + let type = typeof value + + if (i === 'parent' && type === 'object') { + if (targetParent) target[i] = targetParent + } else if (i === 'source') { + target[i] = value + } else if (Array.isArray(value)) { + let children = [] + target[i] = children + for (let j of value) { + let childClone = new j.constructor() + children.push(childClone) + stack.push([j, childClone, target]) + } + } else { + if (type === 'object' && value !== null) { + let valueClone = new value.constructor() + stack.push([value, valueClone, undefined]) + value = valueClone + } + target[i] = value + } + } + } - for (let i in obj) { - if (!Object.prototype.hasOwnProperty.call(obj, i)) { - /* c8 ignore next 2 */ - continue + return cloned +} + +function sourceOffset(inputCSS, position) { + // Not all custom syntaxes support `offset` in `source.start` and `source.end` + if (position && typeof position.offset !== 'undefined') { + return position.offset + } + + let column = 1 + let line = 1 + let offset = 0 + + for (let i = 0; i < inputCSS.length; i++) { + if (line === position.line && column === position.column) { + offset = i + break } - if (i === 'proxyCache') continue - let value = obj[i] - let type = typeof value - if (i === 'parent' && type === 'object') { - if (parent) cloned[i] = parent - } else if (i === 'source') { - cloned[i] = value - } else if (Array.isArray(value)) { - cloned[i] = value.map(j => cloneNode(j, cloned)) + if (inputCSS[i] === '\n') { + column = 1 + line += 1 } else { - if (type === 'object' && value !== null) value = cloneNode(value) - cloned[i] = value + column += 1 } } - return cloned + return offset } class Node { + get proxyOf() { + return this + } + constructor(defaults = {}) { this.raws = {} this[isClean] = false this[my] = true - for (let name in defaults) { + for (let name of Object.keys(defaults)) { + if (name === '__proto__') continue if (name === 'nodes') { this.nodes = [] for (let node of defaults[name]) { - if (typeof node.clone === 'function') { + // Clone only nodes that already belong to another tree, so passing a + // freshly created (parent-less) node adopts that instance instead of + // a copy and keeps the caller's reference usable. See #1987. + if (typeof node.clone === 'function' && node.parent) { this.append(node.clone()) } else { this.append(node) @@ -70097,42 +74933,23 @@ class Node { } } - error(message, opts = {}) { - if (this.source) { - let { start, end } = this.rangeBy(opts) - return this.source.input.error( - message, - { line: start.line, column: start.column }, - { line: end.line, column: end.column }, - opts + addToError(error) { + error.postcssNode = this + if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { + let s = this.source + error.stack = error.stack.replace( + /\n\s{4}at /, + `$&${s.input.from}:${s.start.line}:${s.start.column}$&` ) } - return new CssSyntaxError(message) - } - - warn(result, text, opts) { - let data = { node: this } - for (let i in opts) data[i] = opts[i] - return result.warn(text, data) + return error } - remove() { - if (this.parent) { - this.parent.removeChild(this) - } - this.parent = undefined + after(add) { + this.parent.insertAfter(this, add) return this } - toString(stringifier = stringify) { - if (stringifier.stringify) stringifier = stringifier.stringify - let result = '' - stringifier(this, i => { - result += i - }) - return result - } - assign(overrides = {}) { for (let name in overrides) { this[name] = overrides[name] @@ -70140,6 +74957,17 @@ class Node { return this } + before(add) { + this.parent.insertBefore(this, add) + return this + } + + cleanRaws(keepBetween) { + delete this.raws.before + delete this.raws.after + if (!keepBetween) delete this.raws.between + } + clone(overrides = {}) { let cloned = cloneNode(this) for (let name in overrides) { @@ -70148,137 +74976,118 @@ class Node { return cloned } - cloneBefore(overrides = {}) { + cloneAfter(overrides = {}) { let cloned = this.clone(overrides) - this.parent.insertBefore(this, cloned) + this.parent.insertAfter(this, cloned) return cloned } - cloneAfter(overrides = {}) { + cloneBefore(overrides = {}) { let cloned = this.clone(overrides) - this.parent.insertAfter(this, cloned) + this.parent.insertBefore(this, cloned) return cloned } - replaceWith(...nodes) { - if (this.parent) { - let bookmark = this - let foundSelf = false - for (let node of nodes) { - if (node === this) { - foundSelf = true - } else if (foundSelf) { - this.parent.insertAfter(bookmark, node) - bookmark = node + error(message, opts = {}) { + if (this.source) { + let { end, start } = this.rangeBy(opts) + return this.source.input.error( + message, + { column: start.column, line: start.line }, + { column: end.column, line: end.line }, + opts + ) + } + return new CssSyntaxError(message) + } + + getProxyProcessor() { + return { + get(node, prop) { + if (prop === 'proxyOf') { + return node + } else if (prop === 'root') { + return () => node.root().toProxy() } else { - this.parent.insertBefore(bookmark, node) + return node[prop] } - } + }, - if (!foundSelf) { - this.remove() + set(node, prop, value) { + if (node[prop] === value) return true + node[prop] = value + if ( + prop === 'prop' || + prop === 'value' || + prop === 'name' || + prop === 'params' || + prop === 'important' || + /* c8 ignore next */ + prop === 'text' + ) { + node.markDirty() + } + return true } } - - return this - } - - next() { - if (!this.parent) return undefined - let index = this.parent.index(this) - return this.parent.nodes[index + 1] - } - - prev() { - if (!this.parent) return undefined - let index = this.parent.index(this) - return this.parent.nodes[index - 1] - } - - before(add) { - this.parent.insertBefore(this, add) - return this } - after(add) { - this.parent.insertAfter(this, add) - return this + /* c8 ignore next 3 */ + markClean() { + this[isClean] = true } - root() { - let result = this - while (result.parent && result.parent.type !== 'document') { - result = result.parent + markDirty() { + if (this[isClean]) { + this[isClean] = false + let next = this + while ((next = next.parent)) { + next[isClean] = false + } } - return result - } - - raw(prop, defaultType) { - let str = new Stringifier() - return str.raw(this, prop, defaultType) } - cleanRaws(keepBetween) { - delete this.raws.before - delete this.raws.after - if (!keepBetween) delete this.raws.between + next() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index + 1] } - toJSON(_, inputs) { - let fixed = {} - let emitInputs = inputs == null - inputs = inputs || new Map() - let inputsNextIndex = 0 - - for (let name in this) { - if (!Object.prototype.hasOwnProperty.call(this, name)) { - /* c8 ignore next 2 */ - continue - } - if (name === 'parent' || name === 'proxyCache') continue - let value = this[name] - - if (Array.isArray(value)) { - fixed[name] = value.map(i => { - if (typeof i === 'object' && i.toJSON) { - return i.toJSON(null, inputs) - } else { - return i - } - }) - } else if (typeof value === 'object' && value.toJSON) { - fixed[name] = value.toJSON(null, inputs) - } else if (name === 'source') { - let inputId = inputs.get(value.input) - if (inputId == null) { - inputId = inputsNextIndex - inputs.set(value.input, inputsNextIndex) - inputsNextIndex++ - } - fixed[name] = { - inputId, - start: value.start, - end: value.end - } - } else { - fixed[name] = value - } + positionBy(opts = {}) { + let inputString = + 'document' in this.source.input + ? this.source.input.document + : this.source.input.css + let pos = { + column: this.source.start.column, + line: this.source.start.line, + offset: sourceOffset(inputString, this.source.start) } - - if (emitInputs) { - fixed.inputs = [...inputs.keys()].map(input => input.toJSON()) + if (opts.index) { + pos = this.positionInside(opts.index) + } else if (opts.word) { + let stringRepresentation = inputString.slice( + sourceOffset(inputString, this.source.start), + sourceOffset(inputString, this.source.end) + ) + let index = stringRepresentation.indexOf(opts.word) + if (index !== -1) pos = this.positionInside(index) } - - return fixed + return pos } positionInside(index) { - let string = this.toString() let column = this.source.start.column let line = this.source.start.line - - for (let i = 0; i < index; i++) { - if (string[i] === '\n') { + let inputString = + 'document' in this.source.input + ? this.source.input.document + : this.source.input.css + let offset = sourceOffset(inputString, this.source.start) + let end = offset + index + + for (let i = offset; i < end; i++) { + if (inputString[i] === '\n') { column = 1 line += 1 } else { @@ -70286,37 +75095,50 @@ class Node { } } - return { line, column } + return { column, line, offset: end } } - positionBy(opts) { - let pos = this.source.start - if (opts.index) { - pos = this.positionInside(opts.index) - } else if (opts.word) { - let index = this.toString().indexOf(opts.word) - if (index !== -1) pos = this.positionInside(index) - } - return pos + prev() { + if (!this.parent) return undefined + let index = this.parent.index(this) + return this.parent.nodes[index - 1] } - rangeBy(opts) { + rangeBy(opts = {}) { + let inputString = + 'document' in this.source.input + ? this.source.input.document + : this.source.input.css let start = { + column: this.source.start.column, line: this.source.start.line, - column: this.source.start.column + offset: sourceOffset(inputString, this.source.start) } let end = this.source.end ? { + column: this.source.end.column + 1, line: this.source.end.line, - column: this.source.end.column + 1 + offset: + typeof this.source.end.offset === 'number' + ? // `source.end.offset` is exclusive, so we don't need to add 1 + this.source.end.offset + : // Since line/column in this.source.end is inclusive, + // the `sourceOffset(... , this.source.end)` returns an inclusive offset. + // So, we add 1 to convert it to exclusive. + sourceOffset(inputString, this.source.end) + 1 } : { + column: start.column + 1, line: start.line, - column: start.column + 1 + offset: start.offset + 1 } if (opts.word) { - let index = this.toString().indexOf(opts.word) + let stringRepresentation = inputString.slice( + sourceOffset(inputString, this.source.start), + sourceOffset(inputString, this.source.end) + ) + let index = stringRepresentation.indexOf(opts.word) if (index !== -1) { start = this.positionInside(index) end = this.positionInside(index + opts.word.length) @@ -70324,21 +75146,23 @@ class Node { } else { if (opts.start) { start = { + column: opts.start.column, line: opts.start.line, - column: opts.start.column + offset: sourceOffset(inputString, opts.start) } - } else if (opts.index) { + } else if (typeof opts.index === 'number') { start = this.positionInside(opts.index) } if (opts.end) { end = { + column: opts.end.column, line: opts.end.line, - column: opts.end.column + offset: sourceOffset(inputString, opts.end) } - } else if (opts.endIndex) { + } else if (typeof opts.endIndex === 'number') { end = this.positionInside(opts.endIndex) - } else if (opts.index) { + } else if (typeof opts.index === 'number') { end = this.positionInside(opts.index + 1) } } @@ -70347,41 +75171,128 @@ class Node { end.line < start.line || (end.line === start.line && end.column <= start.column) ) { - end = { line: start.line, column: start.column + 1 } + end = { + column: start.column + 1, + line: start.line, + offset: start.offset + 1 + } } - return { start, end } + return { end, start } } - getProxyProcessor() { - return { - set(node, prop, value) { - if (node[prop] === value) return true - node[prop] = value - if ( - prop === 'prop' || - prop === 'value' || - prop === 'name' || - prop === 'params' || - prop === 'important' || - /* c8 ignore next */ - prop === 'text' - ) { - node.markDirty() + raw(prop, defaultType) { + let str = new Stringifier() + return str.raw(this, prop, defaultType) + } + + remove() { + if (this.parent) { + this.parent.removeChild(this) + } + this.parent = undefined + return this + } + + replaceWith(...nodes) { + if (this.parent) { + let bookmark = this + let foundSelf = false + for (let node of nodes) { + if (node === this) { + foundSelf = true + } else if (foundSelf) { + this.parent.insertAfter(bookmark, node) + bookmark = node + } else { + this.parent.insertBefore(bookmark, node) } - return true - }, + } - get(node, prop) { - if (prop === 'proxyOf') { - return node - } else if (prop === 'root') { - return () => node.root().toProxy() + if (!foundSelf) { + this.remove() + } + } + + return this + } + + root() { + let result = this + while (result.parent && result.parent.type !== 'document') { + result = result.parent + } + return result + } + + toJSON(_, inputs) { + let emitInputs = inputs == null + inputs = inputs || new Map() + + // A worklist instead of recursive `toJSON()` calls to survive deeply + // nested trees. Each entry converts one node and writes the result + // into the already converted parent by [holder, key]. + let holderOfRoot = [] + let queue = [[this, holderOfRoot, 0]] + + for (let step = 0; step < queue.length; step++) { + let [node, holder, key] = queue[step] + let fixed = {} + holder[key] = fixed + + for (let name in node) { + if (!Object.prototype.hasOwnProperty.call(node, name)) { + /* c8 ignore next 2 */ + continue + } + if (name === 'parent' || name === 'proxyCache') continue + let value = node[name] + + if (Array.isArray(value)) { + let fixedArray = [] + fixed[name] = fixedArray + for (let i = 0; i < value.length; i++) { + let item = value[i] + if (typeof item === 'object' && item.toJSON) { + if (item.toJSON === Node.prototype.toJSON) { + queue.push([item, fixedArray, i]) + } else { + fixedArray[i] = item.toJSON(null, inputs) + } + } else { + fixedArray[i] = item + } + } + } else if (typeof value === 'object' && value.toJSON) { + if (value.toJSON === Node.prototype.toJSON) { + queue.push([value, fixed, name]) + } else { + fixed[name] = value.toJSON(null, inputs) + } + } else if (name === 'source') { + if (value == null) continue + let inputId = inputs.get(value.input) + if (inputId == null) { + inputId = inputs.size + inputs.set(value.input, inputId) + } + fixed[name] = { + end: value.end, + inputId, + start: value.start + } } else { - return node[prop] + fixed[name] = value } } } + + let fixed = holderOfRoot[0] + if (emitInputs) { + fixed.inputs = [...inputs.keys()].map(input => input.toJSON()) + } + + return fixed } toProxy() { @@ -70391,30 +75302,19 @@ class Node { return this.proxyCache } - addToError(error) { - error.postcssNode = this - if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { - let s = this.source - error.stack = error.stack.replace( - /\n\s{4}at /, - `$&${s.input.from}:${s.start.line}:${s.start.column}$&` - ) - } - return error - } - - markDirty() { - if (this[isClean]) { - this[isClean] = false - let next = this - while ((next = next.parent)) { - next[isClean] = false - } - } + toString(stringifier = stringify) { + if (stringifier.stringify) stringifier = stringifier.stringify + let result = '' + stringifier(this, i => { + result += i + }) + return result } - get proxyOf() { - return this + warn(result, text, opts = {}) { + let data = { node: this } + for (let i in opts) data[i] = opts[i] + return result.warn(text, data) } } @@ -70430,9 +75330,9 @@ Node.default = Node "use strict"; -let Container = __nccwpck_require__(6919) -let Parser = __nccwpck_require__(5613) +let Container = __nccwpck_require__(56919) let Input = __nccwpck_require__(2690) +let Parser = __nccwpck_require__(95613) function parse(css, opts) { let input = new Input(css, opts) @@ -70474,18 +75374,18 @@ Container.registerParse(parse) /***/ }), -/***/ 5613: +/***/ 95613: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let Declaration = __nccwpck_require__(3522) -let tokenizer = __nccwpck_require__(5790) -let Comment = __nccwpck_require__(7592) -let AtRule = __nccwpck_require__(4193) -let Root = __nccwpck_require__(2630) -let Rule = __nccwpck_require__(2234) +let AtRule = __nccwpck_require__(54193) +let Comment = __nccwpck_require__(37592) +let Declaration = __nccwpck_require__(33522) +let Root = __nccwpck_require__(22630) +let Rule = __nccwpck_require__(12234) +let tokenizer = __nccwpck_require__(45790) const SAFE_COMMENT_NEIGHBOR = { empty: true, @@ -70500,6 +75400,12 @@ function findLastWithPosition(tokens) { } } +function tokensToString(tokens, from, to) { + let result = '' + for (let i = from; i < to; i++) result += tokens[i][1] + return result +} + class Parser { constructor(input) { this.input = input @@ -70508,61 +75414,156 @@ class Parser { this.current = this.root this.spaces = '' this.semicolon = false - this.customProperty = false this.createTokenizer() - this.root.source = { input, start: { offset: 0, line: 1, column: 1 } } + this.root.source = { input, start: { column: 1, line: 1, offset: 0 } } } - createTokenizer() { - this.tokenizer = tokenizer(this.input) - } + atrule(token) { + let node = new AtRule() + node.name = token[1].slice(1) + if (node.name === '') { + this.unnamedAtrule(node, token) + } + this.init(node, token[2]) + + let type + let prev + let shift + let last = false + let open = false + let params = [] + let brackets = [] - parse() { - let token while (!this.tokenizer.endOfFile()) { token = this.tokenizer.nextToken() + type = token[0] - switch (token[0]) { - case 'space': - this.spaces += token[1] - break + if (type === '(' || type === '[') { + brackets.push(type === '(' ? ')' : ']') + } else if (type === '{' && brackets.length > 0) { + brackets.push('}') + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + } - case ';': - this.freeSemicolon(token) + if (brackets.length === 0) { + if (type === ';') { + node.source.end = this.getPosition(token[2]) + node.source.end.offset++ + this.semicolon = true break - - case '}': + } else if (type === '{') { + open = true + break + } else if (type === '}') { + if (params.length > 0) { + shift = params.length - 1 + prev = params[shift] + while (prev && prev[0] === 'space') { + prev = params[--shift] + } + if (prev) { + node.source.end = this.getPosition(prev[3] || prev[2]) + node.source.end.offset++ + } + } this.end(token) break + } else { + params.push(token) + } + } else { + params.push(token) + } - case 'comment': - this.comment(token) - break + if (this.tokenizer.endOfFile()) { + last = true + break + } + } - case 'at-word': - this.atrule(token) - break + node.raws.between = this.spacesAndCommentsFromEnd(params) + if (params.length) { + node.raws.afterName = this.spacesAndCommentsFromStart(params) + this.raw(node, 'params', params) + if (last) { + token = params[params.length - 1] + node.source.end = this.getPosition(token[3] || token[2]) + node.source.end.offset++ + this.spaces = node.raws.between + node.raws.between = '' + } + } else { + node.raws.afterName = '' + node.params = '' + } - case '{': - this.emptyRule(token) - break + if (open) { + node.nodes = [] + this.current = node + } + } - default: - this.other(token) - break + checkMissedSemicolon(tokens) { + let colon = this.colon(tokens) + if (colon === false) return + + let founded = 0 + let token + for (let j = colon - 1; j >= 0; j--) { + token = tokens[j] + if (token[0] !== 'space') { + founded += 1 + if (founded === 2) break } } - this.endFile() + // If the token is a word, e.g. `!important`, `red` or any other valid + // property's value. Then we need to return the colon after that word + // token. [3] is the "end" colon of that word. And because we need it + // after that one we do +1 to get the next one. + throw this.input.error( + 'Missed semicolon', + token[0] === 'word' ? token[3] + 1 : token[2] + ) + } + + colon(tokens) { + let brackets = 0 + let prev, token, type + for (let [i, element] of tokens.entries()) { + token = element + type = token[0] + + if (type === '(') { + brackets += 1 + } + if (type === ')') { + brackets -= 1 + } + if (brackets === 0 && type === ':') { + if (!prev) { + this.doubleColon(token) + } else if (prev[0] === 'word' && prev[1] === 'progid') { + continue + } else { + return i + } + } + + prev = token + } + return false } comment(token) { let node = new Comment() this.init(node, token[2]) node.source.end = this.getPosition(token[3] || token[2]) + node.source.end.offset++ let text = token[1].slice(2, -2) - if (/^\s*$/.test(text)) { + if (!text.trim()) { node.text = '' node.raws.left = text node.raws.right = '' @@ -70574,86 +75575,8 @@ class Parser { } } - emptyRule(token) { - let node = new Rule() - this.init(node, token[2]) - node.selector = '' - node.raws.between = '' - this.current = node - } - - other(start) { - let end = false - let type = null - let colon = false - let bracket = null - let brackets = [] - let customProperty = start[1].startsWith('--') - - let tokens = [] - let token = start - while (token) { - type = token[0] - tokens.push(token) - - if (type === '(' || type === '[') { - if (!bracket) bracket = token - brackets.push(type === '(' ? ')' : ']') - } else if (customProperty && colon && type === '{') { - if (!bracket) bracket = token - brackets.push('}') - } else if (brackets.length === 0) { - if (type === ';') { - if (colon) { - this.decl(tokens, customProperty) - return - } else { - break - } - } else if (type === '{') { - this.rule(tokens) - return - } else if (type === '}') { - this.tokenizer.back(tokens.pop()) - end = true - break - } else if (type === ':') { - colon = true - } - } else if (type === brackets[brackets.length - 1]) { - brackets.pop() - if (brackets.length === 0) bracket = null - } - - token = this.tokenizer.nextToken() - } - - if (this.tokenizer.endOfFile()) end = true - if (brackets.length > 0) this.unclosedBracket(bracket) - - if (end && colon) { - if (!customProperty) { - while (tokens.length) { - token = tokens[tokens.length - 1][0] - if (token !== 'space' && token !== 'comment') break - this.tokenizer.back(tokens.pop()) - } - } - this.decl(tokens, customProperty) - } else { - this.unknownWord(tokens) - } - } - - rule(tokens) { - tokens.pop() - - let node = new Rule() - this.init(node, tokens[0][2]) - - node.raws.between = this.spacesAndCommentsFromEnd(tokens) - this.raw(node, 'selector', tokens) - this.current = node + createTokenizer() { + this.tokenizer = tokenizer(this.input) } decl(tokens, customProperty) { @@ -70669,51 +75592,52 @@ class Parser { node.source.end = this.getPosition( last[3] || last[2] || findLastWithPosition(tokens) ) + node.source.end.offset++ - while (tokens[0][0] !== 'word') { - if (tokens.length === 1) this.unknownWord(tokens) - node.raws.before += tokens.shift()[1] + let start = 0 + while (tokens[start][0] !== 'word') { + if (start === tokens.length - 1) this.unknownWord([tokens[start]]) + start++ } - node.source.start = this.getPosition(tokens[0][2]) + node.raws.before += tokensToString(tokens, 0, start) + node.source.start = this.getPosition(tokens[start][2]) - node.prop = '' - while (tokens.length) { - let type = tokens[0][0] + let propStart = start + while (start < tokens.length) { + let type = tokens[start][0] if (type === ':' || type === 'space' || type === 'comment') { break } - node.prop += tokens.shift()[1] + start++ } + node.prop = tokensToString(tokens, propStart, start) - node.raws.between = '' - + let betweenStart = start let token - while (tokens.length) { - token = tokens.shift() - - if (token[0] === ':') { - node.raws.between += token[1] - break - } else { - if (token[0] === 'word' && /\w/.test(token[1])) { - this.unknownWord([token]) - } - node.raws.between += token[1] + while (start < tokens.length) { + token = tokens[start] + start++ + if (token[0] === ':') break + if (token[0] === 'word' && /\w/.test(token[1])) { + this.unknownWord([token]) } } + node.raws.between = tokensToString(tokens, betweenStart, start) if (node.prop[0] === '_' || node.prop[0] === '*') { node.raws.before += node.prop[0] node.prop = node.prop.slice(1) } - let firstSpaces = [] - let next - while (tokens.length) { - next = tokens[0][0] + let firstSpacesStart = start + while (start < tokens.length) { + let next = tokens[start][0] if (next !== 'space' && next !== 'comment') break - firstSpaces.push(tokens.shift()) + start++ } + let firstSpaces = tokens.slice(firstSpacesStart, start) + + tokens = tokens.slice(start) this.precheckMissedSemicolon(tokens) @@ -70730,12 +75654,12 @@ class Parser { let str = '' for (let j = i; j > 0; j--) { let type = cache[j][0] - if (str.trim().indexOf('!') === 0 && type !== 'space') { + if (str.trim().startsWith('!') && type !== 'space') { break } str = cache.pop()[1] + str } - if (str.trim().indexOf('!') === 0) { + if (str.trim().startsWith('!')) { node.important = true node.raws.important = str tokens = cache @@ -70760,87 +75684,20 @@ class Parser { } } - atrule(token) { - let node = new AtRule() - node.name = token[1].slice(1) - if (node.name === '') { - this.unnamedAtrule(node, token) - } - this.init(node, token[2]) - - let type - let prev - let shift - let last = false - let open = false - let params = [] - let brackets = [] - - while (!this.tokenizer.endOfFile()) { - token = this.tokenizer.nextToken() - type = token[0] - - if (type === '(' || type === '[') { - brackets.push(type === '(' ? ')' : ']') - } else if (type === '{' && brackets.length > 0) { - brackets.push('}') - } else if (type === brackets[brackets.length - 1]) { - brackets.pop() - } - - if (brackets.length === 0) { - if (type === ';') { - node.source.end = this.getPosition(token[2]) - this.semicolon = true - break - } else if (type === '{') { - open = true - break - } else if (type === '}') { - if (params.length > 0) { - shift = params.length - 1 - prev = params[shift] - while (prev && prev[0] === 'space') { - prev = params[--shift] - } - if (prev) { - node.source.end = this.getPosition(prev[3] || prev[2]) - } - } - this.end(token) - break - } else { - params.push(token) - } - } else { - params.push(token) - } - - if (this.tokenizer.endOfFile()) { - last = true - break - } - } - - node.raws.between = this.spacesAndCommentsFromEnd(params) - if (params.length) { - node.raws.afterName = this.spacesAndCommentsFromStart(params) - this.raw(node, 'params', params) - if (last) { - token = params[params.length - 1] - node.source.end = this.getPosition(token[3] || token[2]) - this.spaces = node.raws.between - node.raws.between = '' - } - } else { - node.raws.afterName = '' - node.params = '' - } + doubleColon(token) { + throw this.input.error( + 'Double colon', + { offset: token[2] }, + { offset: token[2] + token[1].length } + ) + } - if (open) { - node.nodes = [] - this.current = node - } + emptyRule(token) { + let node = new Rule() + this.init(node, token[2]) + node.selector = '' + node.raws.between = '' + this.current = node } end(token) { @@ -70854,6 +75711,7 @@ class Parser { if (this.current.parent) { this.current.source.end = this.getPosition(token[2]) + this.current.source.end.offset++ this.current = this.current.parent } else { this.unexpectedClose(token) @@ -70866,6 +75724,7 @@ class Parser { this.current.raws.semicolon = this.semicolon } this.current.raws.after = (this.current.raws.after || '') + this.spaces + this.root.source.end = this.getPosition(this.tokenizer.position()) } freeSemicolon(token) { @@ -70875,6 +75734,8 @@ class Parser { if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { prev.raws.ownSemicolon = this.spaces this.spaces = '' + prev.source.end = this.getPosition(token[2]) + prev.source.end.offset += prev.raws.ownSemicolon.length } } } @@ -70884,23 +75745,128 @@ class Parser { getPosition(offset) { let pos = this.input.fromOffset(offset) return { - offset, + column: pos.col, line: pos.line, - column: pos.col + offset } } init(node, offset) { this.current.push(node) node.source = { - start: this.getPosition(offset), - input: this.input + input: this.input, + start: this.getPosition(offset) } node.raws.before = this.spaces this.spaces = '' if (node.type !== 'comment') this.semicolon = false } + other(start) { + let end = false + let type = null + let colon = false + let bracket = null + let brackets = [] + let customProperty = start[1].startsWith('--') + + let tokens = [] + let token = start + while (token) { + type = token[0] + tokens.push(token) + + if (type === '(' || type === '[') { + if (!bracket) bracket = token + brackets.push(type === '(' ? ')' : ']') + } else if (customProperty && colon && type === '{') { + if (!bracket) bracket = token + brackets.push('}') + } else if (brackets.length === 0) { + if (type === ';') { + if (colon) { + this.decl(tokens, customProperty) + return + } else { + break + } + } else if (type === '{') { + this.rule(tokens) + return + } else if (type === '}') { + this.tokenizer.back(tokens.pop()) + end = true + break + } else if (type === ':') { + colon = true + } + } else if (type === brackets[brackets.length - 1]) { + brackets.pop() + if (brackets.length === 0) bracket = null + } + + token = this.tokenizer.nextToken() + } + + if (this.tokenizer.endOfFile()) end = true + if (brackets.length > 0) this.unclosedBracket(bracket) + + if (end && colon) { + if (!customProperty) { + while (tokens.length) { + token = tokens[tokens.length - 1][0] + if (token !== 'space' && token !== 'comment') break + this.tokenizer.back(tokens.pop()) + } + } + this.decl(tokens, customProperty) + } else { + this.unknownWord(tokens) + } + } + + parse() { + let token + while (!this.tokenizer.endOfFile()) { + token = this.tokenizer.nextToken() + + switch (token[0]) { + case 'space': + this.spaces += token[1] + break + + case ';': + this.freeSemicolon(token) + break + + case '}': + this.end(token) + break + + case 'comment': + this.comment(token) + break + + case 'at-word': + this.atrule(token) + break + + case '{': + this.emptyRule(token) + break + + default: + this.other(token) + break + } + } + this.endFile() + } + + precheckMissedSemicolon(/* tokens */) { + // Hook for Safe Parser + } + raw(node, prop, tokens, customProperty) { let token, type let length = tokens.length @@ -70931,22 +75897,35 @@ class Parser { } if (!clean) { let raw = tokens.reduce((all, i) => all + i[1], '') - node.raws[prop] = { value, raw } + node.raws[prop] = { raw, value } } node[prop] = value } - spacesAndCommentsFromEnd(tokens) { - let lastTokenType - let spaces = '' - while (tokens.length) { - lastTokenType = tokens[tokens.length - 1][0] - if (lastTokenType !== 'space' && lastTokenType !== 'comment') break + rule(tokens) { + tokens.pop() + + let node = new Rule() + this.init(node, tokens[0][2]) + + node.raws.between = this.spacesAndCommentsFromEnd(tokens) + this.raw(node, 'selector', tokens) + this.current = node + } + + spacesAndCommentsFromEnd(tokens) { + let lastTokenType + let spaces = '' + while (tokens.length) { + lastTokenType = tokens[tokens.length - 1][0] + if (lastTokenType !== 'space' && lastTokenType !== 'comment') break spaces = tokens.pop()[1] + spaces } return spaces } + // Errors + spacesAndCommentsFromStart(tokens) { let next let spaces = '' @@ -70978,36 +75957,11 @@ class Parser { return result } - colon(tokens) { - let brackets = 0 - let token, type, prev - for (let [i, element] of tokens.entries()) { - token = element - type = token[0] - - if (type === '(') { - brackets += 1 - } - if (type === ')') { - brackets -= 1 - } - if (brackets === 0 && type === ':') { - if (!prev) { - this.doubleColon(token) - } else if (prev[0] === 'word' && prev[1] === 'progid') { - continue - } else { - return i - } - } - - prev = token - } - return false + unclosedBlock() { + let pos = this.current.source.start + throw this.input.error('Unclosed block', pos.line, pos.column) } - // Errors - unclosedBracket(bracket) { throw this.input.error( 'Unclosed bracket', @@ -71016,14 +75970,6 @@ class Parser { ) } - unknownWord(tokens) { - throw this.input.error( - 'Unknown word', - { offset: tokens[0][2] }, - { offset: tokens[0][2] + tokens[0][1].length } - ) - } - unexpectedClose(token) { throw this.input.error( 'Unexpected }', @@ -71032,16 +75978,11 @@ class Parser { ) } - unclosedBlock() { - let pos = this.current.source.start - throw this.input.error('Unclosed block', pos.line, pos.column) - } - - doubleColon(token) { + unknownWord(tokens) { throw this.input.error( - 'Double colon', - { offset: token[2] }, - { offset: token[2] + token[1].length } + 'Unknown word ' + tokens[0][1], + { offset: tokens[0][2] }, + { offset: tokens[0][2] + tokens[0][1].length } ) } @@ -71052,32 +75993,6 @@ class Parser { { offset: token[2] + token[1].length } ) } - - precheckMissedSemicolon(/* tokens */) { - // Hook for Safe Parser - } - - checkMissedSemicolon(tokens) { - let colon = this.colon(tokens) - if (colon === false) return - - let founded = 0 - let token - for (let j = colon - 1; j >= 0; j--) { - token = tokens[j] - if (token[0] !== 'space') { - founded += 1 - if (founded === 2) break - } - } - // If the token is a word, e.g. `!important`, `red` or any other valid property's value. - // Then we need to return the colon after that word token. [3] is the "end" colon of that word. - // And because we need it after that one we do +1 to get the next one. - throw this.input.error( - 'Missed semicolon', - token[0] === 'word' ? token[3] + 1 : token[2] - ) - } } module.exports = Parser @@ -71085,30 +76000,30 @@ module.exports = Parser /***/ }), -/***/ 7001: +/***/ 77001: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let CssSyntaxError = __nccwpck_require__(3279) -let Declaration = __nccwpck_require__(3522) -let LazyResult = __nccwpck_require__(6310) -let Container = __nccwpck_require__(6919) -let Processor = __nccwpck_require__(9189) -let stringify = __nccwpck_require__(4793) -let fromJSON = __nccwpck_require__(1543) -let Document = __nccwpck_require__(8085) -let Warning = __nccwpck_require__(7143) -let Comment = __nccwpck_require__(7592) -let AtRule = __nccwpck_require__(4193) -let Result = __nccwpck_require__(6846) +let AtRule = __nccwpck_require__(54193) +let Comment = __nccwpck_require__(37592) +let Container = __nccwpck_require__(56919) +let CssSyntaxError = __nccwpck_require__(63279) +let Declaration = __nccwpck_require__(33522) +let Document = __nccwpck_require__(58085) +let fromJSON = __nccwpck_require__(71543) let Input = __nccwpck_require__(2690) +let LazyResult = __nccwpck_require__(46310) +let list = __nccwpck_require__(41608) +let Node = __nccwpck_require__(48557) let parse = __nccwpck_require__(2128) -let list = __nccwpck_require__(1608) -let Rule = __nccwpck_require__(2234) -let Root = __nccwpck_require__(2630) -let Node = __nccwpck_require__(8557) +let Processor = __nccwpck_require__(79189) +let Result = __nccwpck_require__(66846) +let Root = __nccwpck_require__(22630) +let Rule = __nccwpck_require__(12234) +let stringify = __nccwpck_require__(34793) +let Warning = __nccwpck_require__(87143) function postcss(...plugins) { if (plugins.length === 1 && Array.isArray(plugins[0])) { @@ -71194,15 +76109,15 @@ postcss.default = postcss /***/ }), -/***/ 1090: +/***/ 91090: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let { SourceMapConsumer, SourceMapGenerator } = __nccwpck_require__(6766) -let { existsSync, readFileSync } = __nccwpck_require__(7147) -let { dirname, join } = __nccwpck_require__(1017) +let { existsSync, readFileSync } = __nccwpck_require__(57147) +let { dirname, isAbsolute, join, relative, sep } = __nccwpck_require__(71017) +let { SourceMapConsumer, SourceMapGenerator } = __nccwpck_require__(26766) function fromBase64(str) { if (Buffer) { @@ -71216,6 +76131,7 @@ function fromBase64(str) { class PreviousMap { constructor(css, opts) { if (opts.map === false) return + if (opts.unsafeMap) this.unsafeMap = true this.loadAnnotation(css) this.inline = this.startWith(this.annotation, 'data:') @@ -71230,29 +76146,47 @@ class PreviousMap { consumer() { if (!this.consumerCache) { - this.consumerCache = new SourceMapConsumer(this.text) + this.consumerCache = new SourceMapConsumer(this.json || this.text) } return this.consumerCache } - withContent() { - return !!( - this.consumer().sourcesContent && - this.consumer().sourcesContent.length > 0 - ) - } + decodeInline(text) { + let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/ + let baseUri = /^data:application\/json;base64,/ + let charsetUri = /^data:application\/json;charset=utf-?8,/ + let uri = /^data:application\/json,/ - startWith(string, start) { - if (!string) return false - return string.substr(0, start.length) === start + let uriMatch = text.match(charsetUri) || text.match(uri) + if (uriMatch) { + return decodeURIComponent(text.substr(uriMatch[0].length)) + } + + let baseUriMatch = text.match(baseCharsetUri) || text.match(baseUri) + if (baseUriMatch) { + return fromBase64(text.substr(baseUriMatch[0].length)) + } + + let encoding = text.slice('data:application/json;'.length) + encoding = encoding.slice(0, encoding.indexOf(',')) + throw new Error('Unsupported source map encoding ' + encoding) } getAnnotationURL(sourceMapString) { return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, '').trim() } + isMap(map) { + if (typeof map !== 'object') return false + return ( + typeof map.mappings === 'string' || + typeof map._mappings === 'string' || + Array.isArray(map.sections) + ) + } + loadAnnotation(css) { - let comments = css.match(/\/\*\s*# sourceMappingURL=/gm) + let comments = css.match(/\/\*\s*# sourceMappingURL=/g) if (!comments) return // sourceMappingURLs from comments, strings, etc. @@ -71265,25 +76199,22 @@ class PreviousMap { } } - decodeInline(text) { - let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/ - let baseUri = /^data:application\/json;base64,/ - let charsetUri = /^data:application\/json;charset=utf-?8,/ - let uri = /^data:application\/json,/ - - if (charsetUri.test(text) || uri.test(text)) { - return decodeURIComponent(text.substr(RegExp.lastMatch.length)) - } - - if (baseCharsetUri.test(text) || baseUri.test(text)) { - return fromBase64(text.substr(RegExp.lastMatch.length)) + loadFile(path, cssFile, trusted) { + if (!trusted && !this.unsafeMap) { + if (!/\.map$/i.test(path)) { + return undefined + } + if (cssFile) { + let relativePath = relative(dirname(cssFile), path) + if ( + relativePath === '..' || + relativePath.startsWith('..' + sep) || + isAbsolute(relativePath) + ) { + return undefined + } + } } - - let encoding = text.match(/data:application\/json;([^,]+),/)[1] - throw new Error('Unsupported source map encoding ' + encoding) - } - - loadFile(path) { this.root = dirname(path) if (existsSync(path)) { this.mapFile = path @@ -71300,7 +76231,7 @@ class PreviousMap { } else if (typeof prev === 'function') { let prevPath = prev(file) if (prevPath) { - let map = this.loadFile(prevPath) + let map = this.loadFile(prevPath, file, true) if (!map) { throw new Error( 'Unable to load previous source map: ' + prevPath.toString() @@ -71324,16 +76255,28 @@ class PreviousMap { } else if (this.annotation) { let map = this.annotation if (file) map = join(dirname(file), map) - return this.loadFile(map) + let unknown = this.loadFile(map, file, false) + if (unknown) { + try { + /* c8 ignore next 4 */ + this.json = JSON.parse(unknown.replace(/^\)]}'[^\n]*\n/, '')) + } catch { + return undefined + } + } + return unknown } } - isMap(map) { - if (typeof map !== 'object') return false - return ( - typeof map.mappings === 'string' || - typeof map._mappings === 'string' || - Array.isArray(map.sections) + startWith(string, start) { + if (!string) return false + return string.substr(0, start.length) === start + } + + withContent() { + return !!( + this.consumer().sourcesContent && + this.consumer().sourcesContent.length > 0 ) } } @@ -71344,41 +76287,23 @@ PreviousMap.default = PreviousMap /***/ }), -/***/ 9189: +/***/ 79189: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let NoWorkResult = __nccwpck_require__(9810) -let LazyResult = __nccwpck_require__(6310) -let Document = __nccwpck_require__(8085) -let Root = __nccwpck_require__(2630) +let Document = __nccwpck_require__(58085) +let LazyResult = __nccwpck_require__(46310) +let NoWorkResult = __nccwpck_require__(69810) +let Root = __nccwpck_require__(22630) class Processor { constructor(plugins = []) { - this.version = '8.4.14' + this.version = '8.5.18' this.plugins = this.normalize(plugins) } - use(plugin) { - this.plugins = this.plugins.concat(this.normalize([plugin])) - return this - } - - process(css, opts = {}) { - if ( - this.plugins.length === 0 && - typeof opts.parser === 'undefined' && - typeof opts.stringifier === 'undefined' && - typeof opts.syntax === 'undefined' - ) { - return new NoWorkResult(this, css, opts) - } else { - return new LazyResult(this, css, opts) - } - } - normalize(plugins) { let normalized = [] for (let i of plugins) { @@ -71408,6 +76333,24 @@ class Processor { } return normalized } + + process(css, opts = {}) { + if ( + !this.plugins.length && + !opts.parser && + !opts.stringifier && + !opts.syntax + ) { + return new NoWorkResult(this, css, opts) + } else { + return new LazyResult(this, css, opts) + } + } + + use(plugin) { + this.plugins = this.plugins.concat(this.normalize([plugin])) + return this + } } module.exports = Processor @@ -71419,21 +76362,25 @@ Document.registerProcessor(Processor) /***/ }), -/***/ 6846: +/***/ 66846: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let Warning = __nccwpck_require__(7143) +let Warning = __nccwpck_require__(87143) class Result { + get content() { + return this.css + } + constructor(processor, root, opts) { this.processor = processor this.messages = [] this.root = root this.opts = opts - this.css = undefined + this.css = '' this.map = undefined } @@ -71457,10 +76404,6 @@ class Result { warnings() { return this.messages.filter(i => i.type === 'warning') } - - get content() { - return this.css - } } module.exports = Result @@ -71469,13 +76412,13 @@ Result.default = Result /***/ }), -/***/ 2630: +/***/ 22630: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let Container = __nccwpck_require__(6919) +let Container = __nccwpck_require__(56919) let LazyResult, Processor @@ -71486,16 +76429,6 @@ class Root extends Container { if (!this.nodes) this.nodes = [] } - removeChild(child, ignore) { - let index = this.index(child) - - if (!ignore && index === 0 && this.nodes.length > 1) { - this.nodes[1].raws.before = this.nodes[index].raws.before - } - - return super.removeChild(child) - } - normalize(child, sample, type) { let nodes = super.normalize(child) @@ -71516,6 +76449,16 @@ class Root extends Container { return nodes } + removeChild(child, ignore) { + let index = this.index(child) + + if (!ignore && index === 0 && this.nodes.length > 1) { + this.nodes[1].raws.before = this.nodes[index].raws.before + } + + return super.removeChild(child) + } + toResult(opts = {}) { let lazy = new LazyResult(new Processor(), this, opts) return lazy.stringify() @@ -71533,25 +76476,21 @@ Root.registerProcessor = dependant => { module.exports = Root Root.default = Root +Container.registerRoot(Root) + /***/ }), -/***/ 2234: +/***/ 12234: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -let Container = __nccwpck_require__(6919) -let list = __nccwpck_require__(1608) +let Container = __nccwpck_require__(56919) +let list = __nccwpck_require__(41608) class Rule extends Container { - constructor(defaults) { - super(defaults) - this.type = 'rule' - if (!this.nodes) this.nodes = [] - } - get selectors() { return list.comma(this.selector) } @@ -71561,6 +76500,12 @@ class Rule extends Container { let sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen') this.selector = values.join(sep) } + + constructor(defaults) { + super(defaults) + this.type = 'rule' + if (!this.nodes) this.nodes = [] + } } module.exports = Rule @@ -71571,24 +76516,36 @@ Container.registerRule(Rule) /***/ }), -/***/ 9414: +/***/ 59414: /***/ ((module) => { "use strict"; +// Escapes sequences that could break out of an HTML