UNPKG

mdclint

Version:
1,443 lines (1,351 loc) 1.22 MB
import * as fs$1 from 'node:fs'; import fs__default, { lstatSync, realpathSync as realpathSync$1, statSync, existsSync, readFileSync, promises, readFile as readFile$1, accessSync, access } from 'node:fs'; import V, { realpathSync as realpathSync$2, readlinkSync, readdirSync, readdir as readdir$1, lstatSync as lstatSync$1 } from 'fs'; import sysPath from 'path'; import require$$2 from 'os'; import require$$3 from 'crypto'; import { rm, readFile, realpath, readlink, readdir, lstat } from 'node:fs/promises'; import { fileURLToPath, pathToFileURL, URL as URL$1 } from 'node:url'; import { homedir, EOL } from 'node:os'; import path$2, { isAbsolute as isAbsolute$1, resolve as resolve$1, win32, posix } from 'node:path'; import assert from 'node:assert'; import process$1 from 'node:process'; import v8 from 'node:v8'; import { format, inspect } from 'node:util'; import { createRequire } from 'node:module'; import { EventEmitter } from 'node:events'; import Stream from 'node:stream'; import { StringDecoder } from 'node:string_decoder'; const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; function normalizeWindowsPath(input = "") { if (!input) { return input; } return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); } const _UNC_REGEX = /^[/\\]{2}/; const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; const _EXTNAME_RE = /.(\.[^./]+|\.)$/; const normalize$2 = function(path) { if (path.length === 0) { return "."; } path = normalizeWindowsPath(path); const isUNCPath = path.match(_UNC_REGEX); const isPathAbsolute = isAbsolute(path); const trailingSeparator = path[path.length - 1] === "/"; path = normalizeString(path, !isPathAbsolute); if (path.length === 0) { if (isPathAbsolute) { return "/"; } return trailingSeparator ? "./" : "."; } if (trailingSeparator) { path += "/"; } if (_DRIVE_LETTER_RE.test(path)) { path += "/"; } if (isUNCPath) { if (!isPathAbsolute) { return `//./${path}`; } return `//${path}`; } return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; }; const join = function(...segments) { let path = ""; for (const seg of segments) { if (!seg) { continue; } if (path.length > 0) { const pathTrailing = path[path.length - 1] === "/"; const segLeading = seg[0] === "/"; const both = pathTrailing && segLeading; if (both) { path += seg.slice(1); } else { path += pathTrailing || segLeading ? seg : `/${seg}`; } } else { path += seg; } } return normalize$2(path); }; function cwd() { if (typeof process !== "undefined" && typeof process.cwd === "function") { return process.cwd().replace(/\\/g, "/"); } return "/"; } const resolve = function(...arguments_) { arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); let resolvedPath = ""; let resolvedAbsolute = false; for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { const path = index >= 0 ? arguments_[index] : cwd(); if (!path || path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = isAbsolute(path); } resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); if (resolvedAbsolute && !isAbsolute(resolvedPath)) { return `/${resolvedPath}`; } return resolvedPath.length > 0 ? resolvedPath : "."; }; function normalizeString(path, allowAboveRoot) { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let char = null; for (let index = 0; index <= path.length; ++index) { if (index < path.length) { char = path[index]; } else if (char === "/") { break; } else { char = "/"; } if (char === "/") { if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf("/"); if (lastSlashIndex === -1) { res = ""; lastSegmentLength = 0; } else { res = res.slice(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); } lastSlash = index; dots = 0; continue; } else if (res.length > 0) { res = ""; lastSegmentLength = 0; lastSlash = index; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? "/.." : ".."; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `/${path.slice(lastSlash + 1, index)}`; } else { res = path.slice(lastSlash + 1, index); } lastSegmentLength = index - lastSlash - 1; } lastSlash = index; dots = 0; } else if (char === "." && dots !== -1) { ++dots; } else { dots = -1; } } return res; } const isAbsolute = function(p) { return _IS_ABSOLUTE_RE.test(p); }; const extname$1 = function(p) { if (p === "..") return ""; const match = _EXTNAME_RE.exec(normalizeWindowsPath(p)); return match && match[1] || ""; }; const dirname = function(p) { const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { segments[0] += "/"; } return segments.join("/") || (isAbsolute(p) ? "/" : "."); }; const basename = function(p, extension) { const segments = normalizeWindowsPath(p).split("/"); let lastSegment = ""; for (let i = segments.length - 1; i >= 0; i--) { const val = segments[i]; if (val) { lastSegment = val; break; } } return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment; }; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function getAugmentedNamespace(n) { if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n; var f = n.default; if (typeof f == "function") { var a = function a () { var isInstance = false; try { isInstance = this instanceof a; } catch {} if (isInstance) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } var main$1 = {exports: {}}; const name = "dotenv"; const version$1 = "17.2.3"; const description = "Loads environment variables from .env file"; const main = "lib/main.js"; const types$1 = "lib/main.d.ts"; const exports$1 = { ".": { types: "./lib/main.d.ts", require: "./lib/main.js", "default": "./lib/main.js" }, "./config": "./config.js", "./config.js": "./config.js", "./lib/env-options": "./lib/env-options.js", "./lib/env-options.js": "./lib/env-options.js", "./lib/cli-options": "./lib/cli-options.js", "./lib/cli-options.js": "./lib/cli-options.js", "./package.json": "./package.json" }; const scripts = { "dts-check": "tsc --project tests/types/tsconfig.json", lint: "standard", pretest: "npm run lint && npm run dts-check", test: "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000", "test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov", prerelease: "npm test", release: "standard-version" }; const repository = { type: "git", url: "git://github.com/motdotla/dotenv.git" }; const homepage$1 = "https://github.com/motdotla/dotenv#readme"; const funding = "https://dotenvx.com"; const keywords = [ "dotenv", "env", ".env", "environment", "variables", "config", "settings" ]; const readmeFilename = "README.md"; const license = "BSD-2-Clause"; const devDependencies = { "@types/node": "^18.11.3", decache: "^4.6.2", sinon: "^14.0.1", standard: "^17.0.0", "standard-version": "^9.5.0", tap: "^19.2.0", typescript: "^4.8.4" }; const engines = { node: ">=12" }; const browser = { fs: false }; const _package = { name: name, version: version$1, description: description, main: main, types: types$1, exports: exports$1, scripts: scripts, repository: repository, homepage: homepage$1, funding: funding, keywords: keywords, readmeFilename: readmeFilename, license: license, devDependencies: devDependencies, engines: engines, browser: browser }; const _package$1 = { __proto__: null, browser: browser, default: _package, description: description, devDependencies: devDependencies, engines: engines, exports: exports$1, funding: funding, homepage: homepage$1, keywords: keywords, license: license, main: main, name: name, readmeFilename: readmeFilename, repository: repository, scripts: scripts, types: types$1, version: version$1 }; const require$$4 = /*@__PURE__*/getAugmentedNamespace(_package$1); var hasRequiredMain; function requireMain () { if (hasRequiredMain) return main$1.exports; hasRequiredMain = 1; const fs = V; const path = sysPath; const os = require$$2; const crypto = require$$3; const packageJson = require$$4; const version = packageJson.version; // Array of tips to display randomly const TIPS = [ '🔐 encrypt with Dotenvx: https://dotenvx.com', '🔐 prevent committing .env to code: https://dotenvx.com/precommit', '🔐 prevent building .env in docker: https://dotenvx.com/prebuild', '📡 add observability to secrets: https://dotenvx.com/ops', '👥 sync secrets across teammates & machines: https://dotenvx.com/ops', '🗂️ backup and recover secrets: https://dotenvx.com/ops', '✅ audit secrets and track compliance: https://dotenvx.com/ops', '🔄 add secrets lifecycle management: https://dotenvx.com/ops', '🔑 add access controls to secrets: https://dotenvx.com/ops', '🛠️ run anywhere with `dotenvx run -- yourcommand`', '⚙️ specify custom .env file path with { path: \'/custom/path/.env\' }', '⚙️ enable debug logging with { debug: true }', '⚙️ override existing env vars with { override: true }', '⚙️ suppress all logs with { quiet: true }', '⚙️ write to custom object with { processEnv: myObject }', '⚙️ load multiple .env files with { path: [\'.env.local\', \'.env\'] }' ]; // Get a random tip from the tips array function _getRandomTip () { return TIPS[Math.floor(Math.random() * TIPS.length)] } function parseBoolean (value) { if (typeof value === 'string') { return !['false', '0', 'no', 'off', ''].includes(value.toLowerCase()) } return Boolean(value) } function supportsAnsi () { return process.stdout.isTTY // && process.env.TERM !== 'dumb' } function dim (text) { return supportsAnsi() ? `\x1b[2m${text}\x1b[0m` : text } const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; // Parse src into an Object function parse (src) { const obj = {}; // Convert buffer to string let lines = src.toString(); // Convert line breaks to same format lines = lines.replace(/\r\n?/mg, '\n'); let match; while ((match = LINE.exec(lines)) != null) { const key = match[1]; // Default undefined or null to empty string let value = (match[2] || ''); // Remove whitespace value = value.trim(); // Check if double quoted const maybeQuote = value[0]; // Remove surrounding quotes value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2'); // Expand newlines if double quoted if (maybeQuote === '"') { value = value.replace(/\\n/g, '\n'); value = value.replace(/\\r/g, '\r'); } // Add to object obj[key] = value; } return obj } function _parseVault (options) { options = options || {}; const vaultPath = _vaultPath(options); options.path = vaultPath; // parse .env.vault const result = DotenvModule.configDotenv(options); if (!result.parsed) { const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`); err.code = 'MISSING_DATA'; throw err } // handle scenario for comma separated keys - for use with key rotation // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod" const keys = _dotenvKey(options).split(','); const length = keys.length; let decrypted; for (let i = 0; i < length; i++) { try { // Get full key const key = keys[i].trim(); // Get instructions for decrypt const attrs = _instructions(result, key); // Decrypt decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key); break } catch (error) { // last key if (i + 1 >= length) { throw error } // try next key } } // Parse decrypted .env string return DotenvModule.parse(decrypted) } function _warn (message) { console.error(`[dotenv@${version}][WARN] ${message}`); } function _debug (message) { console.log(`[dotenv@${version}][DEBUG] ${message}`); } function _log (message) { console.log(`[dotenv@${version}] ${message}`); } function _dotenvKey (options) { // prioritize developer directly setting options.DOTENV_KEY if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) { return options.DOTENV_KEY } // secondary infra already contains a DOTENV_KEY environment variable if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) { return process.env.DOTENV_KEY } // fallback to empty string return '' } function _instructions (result, dotenvKey) { // Parse DOTENV_KEY. Format is a URI let uri; try { uri = new URL(dotenvKey); } catch (error) { if (error.code === 'ERR_INVALID_URL') { const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development'); err.code = 'INVALID_DOTENV_KEY'; throw err } throw error } // Get decrypt key const key = uri.password; if (!key) { const err = new Error('INVALID_DOTENV_KEY: Missing key part'); err.code = 'INVALID_DOTENV_KEY'; throw err } // Get environment const environment = uri.searchParams.get('environment'); if (!environment) { const err = new Error('INVALID_DOTENV_KEY: Missing environment part'); err.code = 'INVALID_DOTENV_KEY'; throw err } // Get ciphertext payload const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`; const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION if (!ciphertext) { const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`); err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'; throw err } return { ciphertext, key } } function _vaultPath (options) { let possibleVaultPath = null; if (options && options.path && options.path.length > 0) { if (Array.isArray(options.path)) { for (const filepath of options.path) { if (fs.existsSync(filepath)) { possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`; } } } else { possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`; } } else { possibleVaultPath = path.resolve(process.cwd(), '.env.vault'); } if (fs.existsSync(possibleVaultPath)) { return possibleVaultPath } return null } function _resolveHome (envPath) { return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath } function _configVault (options) { const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || (options && options.debug)); const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || (options && options.quiet)); if (debug || !quiet) { _log('Loading env from encrypted .env.vault'); } const parsed = DotenvModule._parseVault(options); let processEnv = process.env; if (options && options.processEnv != null) { processEnv = options.processEnv; } DotenvModule.populate(processEnv, parsed, options); return { parsed } } function configDotenv (options) { const dotenvPath = path.resolve(process.cwd(), '.env'); let encoding = 'utf8'; let processEnv = process.env; if (options && options.processEnv != null) { processEnv = options.processEnv; } let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || (options && options.debug)); let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || (options && options.quiet)); if (options && options.encoding) { encoding = options.encoding; } else { if (debug) { _debug('No encoding is specified. UTF-8 is used by default'); } } let optionPaths = [dotenvPath]; // default, look for .env if (options && options.path) { if (!Array.isArray(options.path)) { optionPaths = [_resolveHome(options.path)]; } else { optionPaths = []; // reset default for (const filepath of options.path) { optionPaths.push(_resolveHome(filepath)); } } } // Build the parsed data in a temporary object (because we need to return it). Once we have the final // parsed data, we will combine it with process.env (or options.processEnv if provided). let lastError; const parsedAll = {}; for (const path of optionPaths) { try { // Specifying an encoding returns a string instead of a buffer const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding })); DotenvModule.populate(parsedAll, parsed, options); } catch (e) { if (debug) { _debug(`Failed to load ${path} ${e.message}`); } lastError = e; } } const populated = DotenvModule.populate(processEnv, parsedAll, options); // handle user settings DOTENV_CONFIG_ options inside .env file(s) debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug); quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet); if (debug || !quiet) { const keysCount = Object.keys(populated).length; const shortPaths = []; for (const filePath of optionPaths) { try { const relative = path.relative(process.cwd(), filePath); shortPaths.push(relative); } catch (e) { if (debug) { _debug(`Failed to load ${filePath} ${e.message}`); } lastError = e; } } _log(`injecting env (${keysCount}) from ${shortPaths.join(',')} ${dim(`-- tip: ${_getRandomTip()}`)}`); } if (lastError) { return { parsed: parsedAll, error: lastError } } else { return { parsed: parsedAll } } } // Populates process.env from .env file function config (options) { // fallback to original dotenv if DOTENV_KEY is not set if (_dotenvKey(options).length === 0) { return DotenvModule.configDotenv(options) } const vaultPath = _vaultPath(options); // dotenvKey exists but .env.vault file does not exist if (!vaultPath) { _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`); return DotenvModule.configDotenv(options) } return DotenvModule._configVault(options) } function decrypt (encrypted, keyStr) { const key = Buffer.from(keyStr.slice(-64), 'hex'); let ciphertext = Buffer.from(encrypted, 'base64'); const nonce = ciphertext.subarray(0, 12); const authTag = ciphertext.subarray(-16); ciphertext = ciphertext.subarray(12, -16); try { const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce); aesgcm.setAuthTag(authTag); return `${aesgcm.update(ciphertext)}${aesgcm.final()}` } catch (error) { const isRange = error instanceof RangeError; const invalidKeyLength = error.message === 'Invalid key length'; const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'; if (isRange || invalidKeyLength) { const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)'); err.code = 'INVALID_DOTENV_KEY'; throw err } else if (decryptionFailed) { const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY'); err.code = 'DECRYPTION_FAILED'; throw err } else { throw error } } } // Populate process.env with parsed values function populate (processEnv, parsed, options = {}) { const debug = Boolean(options && options.debug); const override = Boolean(options && options.override); const populated = {}; if (typeof parsed !== 'object') { const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate'); err.code = 'OBJECT_REQUIRED'; throw err } // Set process.env for (const key of Object.keys(parsed)) { if (Object.prototype.hasOwnProperty.call(processEnv, key)) { if (override === true) { processEnv[key] = parsed[key]; populated[key] = parsed[key]; } if (debug) { if (override === true) { _debug(`"${key}" is already defined and WAS overwritten`); } else { _debug(`"${key}" is already defined and was NOT overwritten`); } } } else { processEnv[key] = parsed[key]; populated[key] = parsed[key]; } } return populated } const DotenvModule = { configDotenv, _configVault, _parseVault, config, decrypt, parse, populate }; main$1.exports.configDotenv = DotenvModule.configDotenv; main$1.exports._configVault = DotenvModule._configVault; main$1.exports._parseVault = DotenvModule._parseVault; main$1.exports.config = DotenvModule.config; main$1.exports.decrypt = DotenvModule.decrypt; main$1.exports.parse = DotenvModule.parse; main$1.exports.populate = DotenvModule.populate; main$1.exports = DotenvModule; return main$1.exports; } var mainExports = requireMain(); //#region src/internal/builtins.ts const nodeBuiltins = [ "_http_agent", "_http_client", "_http_common", "_http_incoming", "_http_outgoing", "_http_server", "_stream_duplex", "_stream_passthrough", "_stream_readable", "_stream_transform", "_stream_wrap", "_stream_writable", "_tls_common", "_tls_wrap", "assert", "assert/strict", "async_hooks", "buffer", "child_process", "cluster", "console", "constants", "crypto", "dgram", "diagnostics_channel", "dns", "dns/promises", "domain", "events", "fs", "fs/promises", "http", "http2", "https", "inspector", "inspector/promises", "module", "net", "os", "path", "path/posix", "path/win32", "perf_hooks", "process", "punycode", "querystring", "readline", "readline/promises", "repl", "stream", "stream/consumers", "stream/promises", "stream/web", "string_decoder", "sys", "timers", "timers/promises", "tls", "trace_events", "tty", "url", "util", "util/types", "v8", "vm", "wasi", "worker_threads", "zlib" ]; //#endregion //#region src/internal/errors.ts const own$1 = {}.hasOwnProperty; const classRegExp = /^([A-Z][a-z\d]*)+$/; const kTypes = new Set([ "string", "function", "number", "object", "Function", "Object", "boolean", "bigint", "symbol" ]); const messages = /* @__PURE__ */ new Map(); const nodeInternalPrefix = "__node_internal_"; let userStackTraceLimit; /** * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'. * We cannot use Intl.ListFormat because it's not available in * --without-intl builds. * * @param {Array<string>} array * An array of strings. * @param {string} [type] * The list type to be inserted before the last element. * @returns {string} */ function formatList(array, type = "and") { return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array.at(-1)}`; } /** * Utility function for registering the error codes. */ function createError(sym, value, constructor) { messages.set(sym, value); return makeNodeErrorWithCode(constructor, sym); } function makeNodeErrorWithCode(Base, key) { return function NodeError(...parameters) { const limit = Error.stackTraceLimit; if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; const error = new Base(); if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; const message = getMessage(key, parameters, error); Object.defineProperties(error, { message: { value: message, enumerable: false, writable: true, configurable: true }, toString: { value() { return `${this.name} [${key}]: ${this.message}`; }, enumerable: false, writable: true, configurable: true } }); captureLargerStackTrace(error); error.code = key; return error; }; } function isErrorStackTraceLimitWritable() { try { if (v8.startupSnapshot.isBuildingSnapshot()) return false; } catch {} const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); if (desc === void 0) return Object.isExtensible(Error); return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0; } /** * This function removes unnecessary frames from Node.js core errors. */ function hideStackFrames(wrappedFunction) { const hidden = nodeInternalPrefix + wrappedFunction.name; Object.defineProperty(wrappedFunction, "name", { value: hidden }); return wrappedFunction; } const captureLargerStackTrace = hideStackFrames(function(error) { const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); if (stackTraceLimitIsWritable) { userStackTraceLimit = Error.stackTraceLimit; Error.stackTraceLimit = Number.POSITIVE_INFINITY; } Error.captureStackTrace(error); if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; return error; }); function getMessage(key, parameters, self) { const message = messages.get(key); assert.ok(message !== void 0, "expected `message` to be found"); if (typeof message === "function") { assert.ok(message.length <= parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`); return Reflect.apply(message, self, parameters); } const regex = /%[dfijoOs]/g; let expectedLength = 0; while (regex.exec(message) !== null) expectedLength++; assert.ok(expectedLength === parameters.length, `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`); if (parameters.length === 0) return message; parameters.unshift(message); return Reflect.apply(format, null, parameters); } /** * Determine the specific type of a value for type-mismatch errors. */ function determineSpecificType(value) { if (value === null || value === void 0) return String(value); if (typeof value === "function" && value.name) return `function ${value.name}`; if (typeof value === "object") { if (value.constructor && value.constructor.name) return `an instance of ${value.constructor.name}`; return `${inspect(value, { depth: -1 })}`; } let inspected = inspect(value, { colors: false }); if (inspected.length > 28) inspected = `${inspected.slice(0, 25)}...`; return `type ${typeof value} (${inspected})`; } createError("ERR_INVALID_ARG_TYPE", (name, expected, actual) => { assert.ok(typeof name === "string", "'name' must be a string"); if (!Array.isArray(expected)) expected = [expected]; let message = "The "; if (name.endsWith(" argument")) message += `${name} `; else { const type = name.includes(".") ? "property" : "argument"; message += `"${name}" ${type} `; } message += "must be "; const types = []; const instances = []; const other = []; for (const value of expected) { assert.ok(typeof value === "string", "All expected entries have to be of type string"); if (kTypes.has(value)) types.push(value.toLowerCase()); else if (classRegExp.exec(value) === null) { assert.ok(value !== "object", "The value \"object\" should be written as \"Object\""); other.push(value); } else instances.push(value); } if (instances.length > 0) { const pos = types.indexOf("object"); if (pos !== -1) { types.slice(pos, 1); instances.push("Object"); } } if (types.length > 0) { message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(types, "or")}`; if (instances.length > 0 || other.length > 0) message += " or "; } if (instances.length > 0) { message += `an instance of ${formatList(instances, "or")}`; if (other.length > 0) message += " or "; } if (other.length > 0) if (other.length > 1) message += `one of ${formatList(other, "or")}`; else { if (other[0]?.toLowerCase() !== other[0]) message += "an "; message += `${other[0]}`; } message += `. Received ${determineSpecificType(actual)}`; return message; }, TypeError); const ERR_INVALID_MODULE_SPECIFIER = createError( "ERR_INVALID_MODULE_SPECIFIER", /** * @param {string} request * @param {string} reason * @param {string} [base] */ (request, reason, base) => { return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`; }, TypeError ); const ERR_INVALID_PACKAGE_CONFIG = createError("ERR_INVALID_PACKAGE_CONFIG", (path$1, base, message) => { return `Invalid package config ${path$1}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`; }, Error); const ERR_INVALID_PACKAGE_TARGET = createError("ERR_INVALID_PACKAGE_TARGET", (packagePath, key, target, isImport = false, base) => { const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./"); if (key === ".") { assert.ok(isImport === false); return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`; } return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? "; targets must start with \"./\"" : ""}`; }, Error); const ERR_MODULE_NOT_FOUND = createError("ERR_MODULE_NOT_FOUND", (path$1, base, exactUrl = false) => { return `Cannot find ${exactUrl ? "module" : "package"} '${path$1}' imported from ${base}`; }, Error); createError("ERR_NETWORK_IMPORT_DISALLOWED", "import of '%s' by %s is not supported: %s", Error); const ERR_PACKAGE_IMPORT_NOT_DEFINED = createError("ERR_PACKAGE_IMPORT_NOT_DEFINED", (specifier, packagePath, base) => { return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath || ""}package.json` : ""} imported from ${base}`; }, TypeError); const ERR_PACKAGE_PATH_NOT_EXPORTED = createError( "ERR_PACKAGE_PATH_NOT_EXPORTED", /** * @param {string} packagePath * @param {string} subpath * @param {string} [base] */ (packagePath, subpath, base) => { if (subpath === ".") return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`; return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`; }, Error ); const ERR_UNSUPPORTED_DIR_IMPORT = createError("ERR_UNSUPPORTED_DIR_IMPORT", "Directory import '%s' is not supported resolving ES modules imported from %s", Error); const ERR_UNSUPPORTED_RESOLVE_REQUEST = createError("ERR_UNSUPPORTED_RESOLVE_REQUEST", "Failed to resolve module specifier \"%s\" from \"%s\": Invalid relative URL or base scheme is not hierarchical.", TypeError); const ERR_UNKNOWN_FILE_EXTENSION = createError("ERR_UNKNOWN_FILE_EXTENSION", (extension, path$1) => { return `Unknown file extension "${extension}" for ${path$1}`; }, TypeError); createError("ERR_INVALID_ARG_VALUE", (name, value, reason = "is invalid") => { let inspected = inspect(value); if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`; return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`; }, TypeError); //#endregion //#region src/internal/package-json-reader.ts const hasOwnProperty$1 = {}.hasOwnProperty; const cache = /* @__PURE__ */ new Map(); function read$1(jsonPath, { base, specifier }) { const existing = cache.get(jsonPath); if (existing) return existing; let string; try { string = fs__default.readFileSync(path$2.toNamespacedPath(jsonPath), "utf8"); } catch (error) { const exception = error; if (exception.code !== "ENOENT") throw exception; } const result = { exists: false, pjsonPath: jsonPath, main: void 0, name: void 0, type: "none", exports: void 0, imports: void 0 }; if (string !== void 0) { let parsed; try { parsed = JSON.parse(string); } catch (error_) { const error = new ERR_INVALID_PACKAGE_CONFIG(jsonPath, (base ? `"${specifier}" from ` : "") + fileURLToPath(base || specifier), error_.message); error.cause = error_; throw error; } result.exists = true; if (hasOwnProperty$1.call(parsed, "name") && typeof parsed.name === "string") result.name = parsed.name; if (hasOwnProperty$1.call(parsed, "main") && typeof parsed.main === "string") result.main = parsed.main; if (hasOwnProperty$1.call(parsed, "exports")) result.exports = parsed.exports; if (hasOwnProperty$1.call(parsed, "imports")) result.imports = parsed.imports; if (hasOwnProperty$1.call(parsed, "type") && (parsed.type === "commonjs" || parsed.type === "module")) result.type = parsed.type; } cache.set(jsonPath, result); return result; } function getPackageScopeConfig(resolved) { let packageJSONUrl = new URL("package.json", resolved); while (true) { if (packageJSONUrl.pathname.endsWith("node_modules/package.json")) break; const packageConfig = read$1(fileURLToPath(packageJSONUrl), { specifier: resolved }); if (packageConfig.exists) return packageConfig; const lastPackageJSONUrl = packageJSONUrl; packageJSONUrl = new URL("../package.json", packageJSONUrl); if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) break; } return { pjsonPath: fileURLToPath(packageJSONUrl), exists: false, type: "none" }; } //#endregion //#region src/internal/get-format.ts const hasOwnProperty$2 = {}.hasOwnProperty; const extensionFormatMap = { __proto__: null, ".json": "json", ".cjs": "commonjs", ".cts": "commonjs", ".js": "module", ".ts": "module", ".mts": "module", ".mjs": "module" }; const protocolHandlers = { __proto__: null, "data:": getDataProtocolModuleFormat, "file:": getFileProtocolModuleFormat, "node:": () => "builtin" }; function mimeToFormat(mime) { if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)) return "module"; if (mime === "application/json") return "json"; return null; } function getDataProtocolModuleFormat(parsed) { const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [ null, null, null ]; return mimeToFormat(mime); } /** * Returns the file extension from a URL. * * Should give similar result to * `require('node:path').extname(require('node:url').fileURLToPath(url))` * when used with a `file:` URL. * */ function extname(url) { const pathname = url.pathname; let index = pathname.length; while (index--) { const code = pathname.codePointAt(index); if (code === 47) return ""; if (code === 46) return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index); } return ""; } function getFileProtocolModuleFormat(url, _context, ignoreErrors) { const ext = extname(url); if (ext === ".js") { const { type: packageType } = getPackageScopeConfig(url); if (packageType !== "none") return packageType; return "commonjs"; } if (ext === "") { const { type: packageType } = getPackageScopeConfig(url); if (packageType === "none" || packageType === "commonjs") return "commonjs"; return "module"; } const format$1 = extensionFormatMap[ext]; if (format$1) return format$1; if (ignoreErrors) return; throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url)); } function defaultGetFormatWithoutErrors(url, context) { const protocol = url.protocol; if (!hasOwnProperty$2.call(protocolHandlers, protocol)) return null; return protocolHandlers[protocol](url, context, true) || null; } //#endregion //#region src/internal/resolve.ts const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace]; const own$2 = {}.hasOwnProperty; 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; 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 invalidPackageNameRegEx = /^\.|%|\\/; const patternRegEx = /\*/g; const encodedSeparatorRegEx = /%2f|%5c/i; const emittedPackageWarnings = /* @__PURE__ */ new Set(); const doubleSlashRegEx = /[/\\]{2}/; function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) { if (process$1.noDeprecation) return; const pjsonPath = fileURLToPath(packageJsonUrl); const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null; process$1.emitWarning(`Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}.`, "DeprecationWarning", "DEP0166"); } function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) { if (process$1.noDeprecation) return; if (defaultGetFormatWithoutErrors(url, { parentURL: base.href }) !== "module") return; const urlPath = fileURLToPath(url.href); const packagePath = fileURLToPath(new URL$1(".", packageJsonUrl)); const basePath = fileURLToPath(base); if (!main) process$1.emitWarning(`No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, "DeprecationWarning", "DEP0151"); else if (path$2.resolve(packagePath, main) !== urlPath) process$1.emitWarning(`Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(packagePath.length)}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is deprecated for ES modules.`, "DeprecationWarning", "DEP0151"); } function tryStatSync(path$1) { try { return statSync(path$1); } catch {} } /** * Legacy CommonJS main resolution: * 1. let M = pkg_url + (json main field) * 2. TRY(M, M.js, M.json, M.node) * 3. TRY(M/index.js, M/index.json, M/index.node) * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node) * 5. NOT_FOUND */ function fileExists(url) { const stats = statSync(url, { throwIfNoEntry: false }); const isFile = stats ? stats.isFile() : void 0; return isFile === null || isFile === void 0 ? false : isFile; } function legacyMainResolve(packageJsonUrl, packageConfig, base) { let guess; if (packageConfig.main !== void 0) { guess = new URL$1(packageConfig.main, packageJsonUrl); if (fileExists(guess)) return guess; const tries$1 = [ `./${packageConfig.main}.js`, `./${packageConfig.main}.json`, `./${packageConfig.main}.node`, `./${packageConfig.main}/index.js`, `./${packageConfig.main}/index.json`, `./${packageConfig.main}/index.node` ]; let i$1 = -1; while (++i$1 < tries$1.length) { guess = new URL$1(tries$1[i$1], packageJsonUrl); if (fileExists(guess)) break; guess = void 0; } if (guess) { emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); return guess; } } const tries = [ "./index.js", "./index.json", "./index.node" ]; let i = -1; while (++i < tries.length) { guess = new URL$1(tries[i], packageJsonUrl); if (fileExists(guess)) break; guess = void 0; } if (guess) { emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); return guess; } throw new ERR_MODULE_NOT_FOUND(fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base)); } function finalizeResolution(resolved, base, preserveSymlinks) { if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, String.raw`must not include encoded "/" or "\" characters`, fileURLToPath(base)); let filePath; try { filePath = fileURLToPath(resolved); } catch (error) { Object.defineProperty(error, "input", { value: String(resolved) }); Object.defineProperty(error, "module", { value: String(base) }); throw error; } const stats = tryStatSync(filePath.endsWith("/") ? filePath.slice(-1) : filePath); if (stats && stats.isDirectory()) { const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath(base)); error.url = String(resolved); throw error; } if (!stats || !stats.isFile()) { const error = new ERR_MODULE_NOT_FOUND(filePath || resolved.pathname, base && fileURLToPath(base), true); error.url = String(resolved); throw error; } { const real = realpathSync$1(filePath); const { search, hash } = resolved; resolved = pathToFileURL(real + (filePath.endsWith(path$2.sep) ? "/" : "")); resolved.search = search; resolved.hash = hash; } return resolved; } function importNotDefined(specifier, packageJsonUrl, base) { return new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && fileURLToPath(new URL$1(".", packageJsonUrl)), fileURLToPath(base)); } function exportsNotFound(subpath, packageJsonUrl, base) { return new ERR_PACKAGE_PATH_NOT_EXPORTED(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, base && fileURLToPath(base)); } function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) { throw new ERR_INVALID_MODULE_SPECIFIER(request, `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath(packageJsonUrl)}`, base && fileURLToPath(base)); } function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) { target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`; return new ERR_INVALID_PACKAGE_TARGET(fileURLToPath(new URL$1(".", packageJsonUrl)), subpath, target, internal, base && fileURLToPath(base)); } function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) { if (subpath !== "" && !pattern && target.at(-1) !== "/") throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); if (!target.startsWith("./")) { if (internal && !target.startsWith("../") && !target.startsWith("/")) { let isURL = false; try { new URL$1(target); isURL = true; } catch {} if (!isURL) return packageResolve(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target + subpath, packageJsonUrl, conditions); } throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); } if (invalidSegmentRegEx.exec(target.slice(2)) !== null) if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) { if (!isPathMap) { const request = pattern ? match.replace("*", () => subpath) : match + subpath; emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target, request, match, packageJsonUrl, internal, base, true); } } else throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); const resolved = new URL$1(target, packageJsonUrl); const resolvedPath = resolved.pathname; const packagePath = new URL$1(".", packageJsonUrl).pathname; if (!resolvedPath.startsWith(packagePath)) throw invalidPackageTarget(match, target, packageJsonUrl, internal, base); if (subpath === "") return resolved; if (invalidSegmentRegEx.exec(subpath) !== null) { const request = pattern ? match.replace("*", () => subpath) : match + subpath; if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) { if (!isPathMap) emitInvalidSegmentDeprecation(pattern ? RegExpPrototypeSymbolReplace.call(patternRegEx, target, () => subpath) : target, request, match, packageJsonUrl, internal, base, false); } else throwInvalidSubpath(request, match, packageJsonUrl, internal, base); } if (pattern) return new URL$1(RegExpPrototypeSymbolReplace.call(patternRegEx, resolved.href, () => subpath)); return new URL$1(subpath, resolved); } function isArrayIndex(key) { const keyNumber = Number(key); if (`${keyNumber}` !== key) return false; return keyNumber >= 0 && keyNumber < 4294967295; } function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) { if (typeof target === "string") return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, isPathMap, conditions); if (Array.isArray(target)) { const targetList = target; if (targetList.length === 0) return null; let lastException; let i = -1; while (++i < targetList.length) { const targetItem = targetList[i]; let resolveResult; try { resolveResult = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions); } catch (error) { const exception = error; lastException = exception; if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue; throw error; } if (resolveResult === void 0) continue; if (resolveResult === null) { lastException = null; continue; } return resolveResult; } if (lastException === void 0 || lastException === null) return null; throw lastException; } if (typeof target === "object" && target !== null) { const keys = Object.getOwnPropertyNames(target); let i = -1; while (++i < keys.length) { const key = keys[i]; if (isArrayIndex(key)) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), fileURLToPath(base), "\"exports\" cannot contain numeric property keys."); } i = -1; while (++i < keys.length) { const key = keys[i]; if (key === "default" || conditions && conditions.has(key)) { const conditionalTarget = target[key]; const resolveResult = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions); if (resolveResult === void 0) continue; return resolveResult; } } return null; } if (target === null) return null; throw invalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base); } function isConditionalExportsMainSugar(exports$1, packageJsonUrl, base) { if (typeof exports$1 === "string" || Array.isArray(exports$1)) return true; if (typeof exports$1 !== "object" || exports$1 === null) return false; const keys = Object.getOwnPropertyNames(exports$1); let isConditionalSugar = false; let i = 0; let keyIndex = -1; while (++keyIndex < keys.length) { const key = keys[keyIndex]; const currentIsConditionalSugar = key === "" || key[0] !== "."; if (i++ === 0) isConditionalSugar = currentIsConditionalSugar; else if (isConditionalSugar !== currentIsConditionalSugar) throw new ERR_INVALID_PACKAGE_CONFIG(fileURLToPath(packageJsonUrl), fileURLToPath(base), "\"exports\" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only."); } return isConditionalSugar; } function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) { if (process$1.noDeprecation) return; const pjsonPath = fileURLToPath(pjsonUrl); if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return; emittedPackageWarnings.add(pjsonPath + "|" + match); process$1.emitWarning(`Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${fileURLToPath(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`, "DeprecationWarning", "DEP0155"); } function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) { let exports$1 = packageConfig.exports; if (isConditionalExportsMainSugar(exports$1, packageJsonUrl, base)) exports$1 = { ".": exports$1 }; if (own$2.call(exports$1, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) { const target = exports$1[packageSubpath]; const resolveResult = resolvePackageTarget(packageJsonUrl, target, "", packageSubpath, base, false, false, false, conditions); if (resolveResult === null || resolveResult === void 0) throw exportsNotFound(packageSubpath, packageJsonUrl, base); re