@mherod/get-cookie 4.1.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +5 -0
- package/.husky/commit-msg +6 -2
- package/.husky/pre-commit +6 -4
- package/.husky/pre-push +6 -4
- package/dist/chunk-GVQTX3C5.js +2 -0
- package/dist/chunk-GVQTX3C5.js.map +1 -0
- package/dist/cli.cjs +1 -3
- package/dist/cli.cjs.map +1 -1
- package/dist/getChromePassword-6XZINNNO.js +2 -0
- package/dist/{getChromePassword-O452VQWI.js.map → getChromePassword-6XZINNNO.js.map} +1 -1
- package/dist/index.cjs +1 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +216 -37
- package/dist/index.d.ts +216 -37
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/eslint.config.js +2 -17
- package/examples/README.md +37 -0
- package/examples/advanced-usage.ts +56 -0
- package/examples/basic-usage.ts +44 -0
- package/examples/cli-examples.sh +51 -0
- package/package.json +22 -23
- package/tsconfig.build.json +2 -2
- package/tsconfig.cli.json +12 -0
- package/tsconfig.tsup.json +12 -0
- package/tsup.cli.ts +1 -0
- package/tsup.lib.ts +1 -0
- package/dist/chunk-3FVH4L25.js +0 -2
- package/dist/chunk-3FVH4L25.js.map +0 -1
- package/dist/chunk-56Z35D5R.js +0 -2
- package/dist/chunk-56Z35D5R.js.map +0 -1
- package/dist/chunk-7XZ7PCDJ.js +0 -2
- package/dist/chunk-7XZ7PCDJ.js.map +0 -1
- package/dist/chunk-DVWQBWUF.js +0 -4
- package/dist/chunk-DVWQBWUF.js.map +0 -1
- package/dist/chunk-I6AYGFSQ.js +0 -2
- package/dist/chunk-I6AYGFSQ.js.map +0 -1
- package/dist/chunk-U27I5BLR.js +0 -2
- package/dist/chunk-U27I5BLR.js.map +0 -1
- package/dist/chunk-YOZOS2YM.js +0 -2
- package/dist/chunk-YOZOS2YM.js.map +0 -1
- package/dist/getChromeCookie-2ROVM47V.js +0 -2
- package/dist/getChromeCookie-2ROVM47V.js.map +0 -1
- package/dist/getChromePassword-O452VQWI.js +0 -2
- package/dist/getCookie-CRE6M3GI.js +0 -2
- package/dist/getCookie-CRE6M3GI.js.map +0 -1
- package/dist/getFirefoxCookie-5P74VDC7.js +0 -2
- package/dist/getFirefoxCookie-5P74VDC7.js.map +0 -1
- package/dist/getGroupedRenderedCookies-DFEJTTC6.js +0 -2
- package/dist/getGroupedRenderedCookies-DFEJTTC6.js.map +0 -1
- package/dist/getMergedRenderedCookies-W5GSSHQQ.js +0 -2
- package/dist/getMergedRenderedCookies-W5GSSHQQ.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/logger.ts","../src/utils/logHelpers.ts","../src/global.ts","../src/core/browsers/chrome/ChromeApplicationSupport.ts","../src/core/browsers/QuerySqliteThenTransform.ts","../src/core/browsers/getEncryptedChromeCookie.ts","../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js","../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js","../node_modules/.pnpm/minimatch@9.0.5/node_modules/minimatch/src/assert-valid-pattern.ts","../node_modules/.pnpm/minimatch@9.0.5/node_modules/minimatch/src/brace-expressions.ts","../node_modules/.pnpm/minimatch@9.0.5/node_modules/minimatch/src/unescape.ts","../node_modules/.pnpm/minimatch@9.0.5/node_modules/minimatch/src/ast.ts","../node_modules/.pnpm/minimatch@9.0.5/node_modules/minimatch/src/escape.ts","../node_modules/.pnpm/minimatch@9.0.5/node_modules/minimatch/src/index.ts","../node_modules/.pnpm/lru-cache@10.4.3/node_modules/lru-cache/src/index.ts","../node_modules/.pnpm/minipass@7.1.2/node_modules/minipass/src/index.ts","../node_modules/.pnpm/path-scurry@1.11.1/node_modules/path-scurry/src/index.ts","../node_modules/.pnpm/glob@10.4.5/node_modules/glob/src/pattern.ts","../node_modules/.pnpm/glob@10.4.5/node_modules/glob/src/ignore.ts","../node_modules/.pnpm/glob@10.4.5/node_modules/glob/src/processor.ts","../node_modules/.pnpm/glob@10.4.5/node_modules/glob/src/walker.ts","../node_modules/.pnpm/glob@10.4.5/node_modules/glob/src/glob.ts","../node_modules/.pnpm/glob@10.4.5/node_modules/glob/src/has-magic.ts","../node_modules/.pnpm/glob@10.4.5/node_modules/glob/src/index.ts","../src/core/browsers/listChromeProfiles.ts","../src/core/browsers/chrome/decrypt.ts","../src/utils/execSimple.ts","../src/core/browsers/chrome/macos/getChromePassword.ts","../src/core/browsers/chrome/getChromePassword.ts","../src/core/browsers/chrome/ChromeCookieQueryStrategy.ts","../src/core/browsers/firefox/FirefoxCookieQueryStrategy.ts","../src/types/schemas.ts","../src/core/browsers/decodeBinaryCookies.ts","../src/core/browsers/safari/SafariCookieQueryStrategy.ts","../src/core/cookies/queryCookies.ts","../src/core/cookies/getCookie.ts","../src/core/cookies/getChromeCookie.ts","../src/core/cookies/getFirefoxCookie.ts","../src/core/cookies/renderCookies.ts","../src/core/cookies/getGroupedRenderedCookies.ts","../src/core/cookies/getMergedRenderedCookies.ts","../src/index.ts","../src/core/cookies/dynamicImports.ts"],"sourcesContent":["import { createConsola } from \"consola\";\n\n/**\n * Standard log levels and their usage:\n * - debug: Detailed information for debugging\n * - info: General operational information\n * - success: Successful operations\n * - warn: Warning conditions\n * - error: Error conditions that might still allow the app to continue\n * - fatal: Critical errors that prevent the app from continuing\n */\nconst consola = createConsola({\n fancy: true,\n formatOptions: {\n showLogLevel: false,\n colors: true,\n date: false,\n compact: true,\n columns:\n typeof process.stdout.columns === \"number\" ? process.stdout.columns : 80,\n },\n level:\n typeof process.env.LOG_LEVEL === \"string\" &&\n process.env.LOG_LEVEL === \"debug\"\n ? 5\n : 2,\n});\n\n/**\n * Configured consola logger instance with standardized formatting and colored output.\n * Used for consistent logging throughout the application.\n * @example\n * // Basic usage\n * logger.info('Operation started');\n * logger.success('Task completed');\n * logger.error('Failed to process', error);\n *\n * // Tagged logging for module context\n * const moduleLogger = logger.withTag('ModuleName');\n * moduleLogger.info('Module specific log');\n *\n * // Structured logging\n * logger.info('User action', {\n * userId: '123',\n * action: 'login',\n * timestamp: new Date()\n * });\n *\n * // Error logging with full context\n * logger.error('Operation failed', {\n * error: error,\n * context: 'operation name',\n * input: data\n * });\n */\nexport default consola;\n","import logger from \"./logger\";\n\n/**\n * Helper functions for common logging patterns.\n * @module\n * @example\n * ```typescript\n * import { logOperationResult, logError } from './logHelpers';\n *\n * try {\n * const result = await someOperation();\n * logOperationResult('Operation', true, { data: result });\n * } catch (error) {\n * logError('Operation failed', error);\n * }\n * ```\n */\n\ninterface OperationContext {\n [key: string]: unknown;\n}\n\n/**\n * Logs the result of an operation with consistent formatting.\n * @param operation - Name of the operation.\n * @param success - Whether the operation succeeded.\n * @param [context] - Additional context about the operation.\n * @example\n * ```typescript\n * logOperationResult('Database Backup', true, { size: '1.2GB' });\n * // ✅ Database Backup succeeded\n *\n * logOperationResult('File Upload', false, { error: 'Network timeout' });\n * // ❌ File Upload failed\n * ```\n */\nexport function logOperationResult(\n operation: string,\n success: boolean,\n context?: OperationContext,\n): void {\n const icon = success ? \"✅\" : \"❌\";\n const message = `${icon} ${operation} ${success ? \"succeeded\" : \"failed\"}`;\n\n if (success) {\n logger.success(message, context);\n } else {\n logger.error(message, context);\n }\n}\n\n/**\n * Logs an error with consistent formatting and context.\n * @param message - Error message to display.\n * @param error - Error object or error information.\n * @param [context] - Additional context about the error.\n * @example\n * ```typescript\n * try {\n * throw new Error('Connection failed');\n * } catch (error) {\n * logError('Database error', error, { retries: 3 });\n * }\n * ```\n */\nexport function logError(\n message: string,\n error: unknown,\n context?: OperationContext,\n): void {\n const errorContext = {\n ...(context ?? {}),\n error:\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : error,\n };\n\n logger.error(message, errorContext);\n}\n\n/**\n * Logs debug information with consistent formatting.\n * @param component - Component or module name.\n * @param message - Debug message to log.\n * @param [data] - Optional debug data to include.\n * @example\n * ```typescript\n * logDebug('AuthService', 'Token refresh started', { userId: '123' });\n * ```\n */\nexport function logDebug(\n component: string,\n message: string,\n data?: unknown,\n): void {\n const componentLogger = logger.withTag(component);\n componentLogger.debug(message, data);\n}\n\n/**\n * Creates a tagged logger with consistent naming.\n * @param component - Component or module name.\n * @returns A tagged logger instance.\n * @example\n * ```typescript\n * const dbLogger = createTaggedLogger('Database');\n * dbLogger.info('Connection established');\n * ```\n */\nexport function createTaggedLogger(\n component: string,\n): ReturnType<typeof logger.withTag> {\n return logger.withTag(component);\n}\n\n/**\n * Logs a warning with consistent formatting.\n * @param component - Component or module name.\n * @param message - Warning message to display.\n * @param [context] - Additional context about the warning.\n * @example\n * ```typescript\n * logWarn('Cache', 'Cache miss', { key: 'user-123' });\n * ```\n */\nexport function logWarn(\n component: string,\n message: string,\n context?: OperationContext,\n): void {\n const componentLogger = logger.withTag(component);\n componentLogger.warn(message, context);\n}\n\n// Re-export the base logger for direct usage\n/**\n * Re-export of the base logger for direct usage.\n */\nexport { default as logger } from \"./logger\";\n","import { merge } from \"lodash-es\";\n\n/**\n * Global environment variables object that merges with process.env\n * @example\n * // Access environment variables\n * const nodeEnv = env.NODE_ENV; // 'development'\n * const apiKey = env.API_KEY; // 'abc123'\n *\n * // Check if variable exists\n * if (env.DATABASE_URL) {\n * // Use database URL\n * }\n *\n * // Add new environment variables\n * env.CUSTOM_VAR = 'my-value';\n */\nexport const env: { [key: string]: string | undefined } = {};\nmerge(env, process.env);\n\n/**\n * User's home directory path from environment variables\n * @throws Error if HOME environment variable is not set\n * @example\n * // Access home directory path\n * const homePath = HOME; // '/home/username' or 'C:\\Users\\username'\n *\n * // Use in file path construction\n * const configPath = `${homePath}/.config/app`;\n *\n * // Error handling\n * if (typeof homePath === 'string' && homePath.length > 0) {\n * // Use home path\n * } else {\n * throw new Error('HOME environment variable is not set or empty');\n * }\n */\nexport const HOME: string | undefined = env[\"HOME\"];\nif (typeof HOME !== \"string\" || HOME.length === 0) {\n throw new Error(\"HOME environment variable is not set or empty\");\n}\n","import { join } from \"path\";\n\nimport { HOME } from \"../../../global\";\n\n/**\n * The path to Chrome's application support directory on macOS\n * This constant is used to locate Chrome's profile and cookie storage directories\n * @example\n */\nexport const chromeApplicationSupport = join(\n HOME ?? \"\",\n \"Library\",\n \"Application Support\",\n \"Google\",\n \"Chrome\",\n);\n","// External imports\nimport BetterSqlite3, { Database } from \"better-sqlite3\";\nimport { memoize } from \"lodash-es\";\n\n// Internal imports\nimport { logError } from \"@utils/logHelpers\";\n\ninterface QuerySqliteThenTransformOptions<TRow, TResult> {\n file: string;\n sql: string;\n params?: unknown[];\n rowFilter?: (row: TRow) => boolean;\n rowTransform?: (row: TRow) => TResult;\n}\n\nconst openDatabase = memoize((file: string): Promise<Database> => {\n try {\n return Promise.resolve(new BetterSqlite3(file, { readonly: true }));\n } catch (error) {\n logError(\"Database open failed\", error, { file });\n throw error;\n }\n});\n\nfunction closeDatabase(db: Database): Promise<void> {\n try {\n db.close();\n return Promise.resolve();\n } catch (error) {\n logError(\"Database close failed\", error);\n return Promise.reject(\n error instanceof Error\n ? error\n : new Error(\"Failed to close database: Unknown error\"),\n );\n }\n}\n\n/**\n * Executes a SQL query on a SQLite database file and transforms the results\n * @param root0 - The options object containing query parameters\n * @param root0.file - The path to the SQLite database file\n * @param root0.sql - The SQL query to execute\n * @param root0.params - Optional parameters for the SQL query\n * @param root0.rowFilter - Optional function to filter rows from the result set\n * @param root0.rowTransform - Optional function to transform each row before returning\n * @returns A promise that resolves to an array of transformed results\n * @example\n */\nexport async function querySqliteThenTransform<TRow, TResult>({\n file,\n sql,\n params,\n rowFilter,\n rowTransform,\n}: QuerySqliteThenTransformOptions<TRow, TResult>): Promise<TResult[]> {\n let db: Database | undefined;\n\n try {\n db = await openDatabase(file);\n const stmt = db.prepare(sql);\n const rows = stmt.all(params) as TRow[];\n\n const filteredRows = rowFilter ? rows.filter(rowFilter) : rows;\n const transformedRows = rowTransform\n ? filteredRows.map(rowTransform)\n : (filteredRows as unknown as TResult[]);\n\n return transformedRows;\n } catch (error) {\n logError(\"Database query failed\", error, { file, sql });\n throw error;\n } finally {\n if (db) {\n await closeDatabase(db);\n }\n }\n}\n","import { existsSync } from \"fs\";\nimport { join } from \"path\";\n\nimport glob from \"fast-glob\";\n\nimport { logError, logDebug, logOperationResult } from \"@utils/logHelpers\";\n\nimport type { CookieRow } from \"../../types/schemas\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\nimport { querySqliteThenTransform } from \"./QuerySqliteThenTransform\";\n\ninterface ChromeCookieRow {\n encrypted_value: Buffer;\n name: string;\n host_key: string;\n expires_utc: number;\n}\n\ninterface GetEncryptedCookieOptions {\n name: string;\n domain: string;\n file?: string;\n}\n\ninterface SqlQuery {\n sql: string;\n params: string[];\n}\n\n/**\n * Validates if a path is a valid, existing file\n * @param path - Path to validate\n * @returns true if path is valid and file exists, false otherwise\n */\nfunction isValidFilePath(path: unknown): path is string {\n if (typeof path !== \"string\") {\n return false;\n }\n\n const trimmedPath = path.trim();\n if (trimmedPath.length === 0) {\n return false;\n }\n\n return existsSync(trimmedPath);\n}\n\n/**\n * Get paths to Chrome cookie files\n * @returns A promise that resolves to an array of file paths\n */\nasync function getCookieFiles(): Promise<string[]> {\n const patterns = [\n join(chromeApplicationSupport, \"Default/Cookies\"),\n join(chromeApplicationSupport, \"Profile */Cookies\"),\n join(chromeApplicationSupport, \"Profile Default/Cookies\"),\n ];\n\n const files: string[] = [];\n for (const pattern of patterns) {\n const matches = await glob(pattern);\n files.push(...matches);\n }\n\n logDebug(\"ChromeCookies\", \"Found cookie files\", {\n count: files.length,\n files,\n });\n return files;\n}\n\n/**\n * Builds the SQL query for retrieving cookies\n * @param name - Cookie name to search for\n * @param domain - Domain to filter by\n * @returns SQL query and parameters\n */\nfunction buildSqlQuery(name: string, domain: string): SqlQuery {\n const isWildcard = name === \"%\";\n const sql = isWildcard\n ? `SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE host_key LIKE ?`\n : `SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE name = ? AND host_key LIKE ?`;\n const params = isWildcard ? [`%${domain}%`] : [name, `%${domain}%`];\n\n return { sql, params };\n}\n\n/**\n * Processes a single cookie file to extract matching cookies\n * @param cookieFile - Path to the cookie file\n * @param name - Cookie name to search for\n * @param domain - Domain to filter by\n * @returns Array of matching cookies\n */\nasync function processCookieFile(\n cookieFile: string,\n name: string,\n domain: string,\n): Promise<CookieRow[]> {\n try {\n const { sql, params } = buildSqlQuery(name, domain);\n logDebug(\"ChromeCookies\", \"Executing query\", { sql, params });\n\n const rows = await querySqliteThenTransform<ChromeCookieRow, CookieRow>({\n file: cookieFile,\n sql,\n params,\n rowTransform: (row: ChromeCookieRow): CookieRow => ({\n name: row.name,\n domain: row.host_key,\n value: row.encrypted_value,\n expiry: row.expires_utc,\n }),\n });\n\n logOperationResult(\"QueryCookies\", true, {\n file: cookieFile,\n count: rows.length,\n });\n return rows;\n } catch (error) {\n logError(\"Failed to read cookie file\", error, { file: cookieFile });\n return [];\n }\n}\n\n/**\n * Retrieve encrypted cookies from Chrome's cookie store\n * @param options - Options for querying Chrome cookies\n * @param options.name - The name of the cookie to retrieve\n * @param options.domain - The domain to retrieve cookies from\n * @param options.file - Optional specific cookie file to query\n * @returns Promise resolving to array of encrypted cookies\n */\nexport async function getEncryptedChromeCookie({\n name,\n domain,\n file,\n}: GetEncryptedCookieOptions): Promise<CookieRow[]> {\n const cookieFiles =\n typeof file === \"string\" && file.length > 0\n ? [file]\n : await getCookieFiles();\n\n if (cookieFiles.length === 0) {\n logDebug(\"ChromeCookies\", \"No cookie files found\");\n return [];\n }\n\n const results: CookieRow[] = [];\n for (const cookieFile of cookieFiles) {\n if (!isValidFilePath(cookieFile)) {\n logDebug(\"ChromeCookies\", \"Cookie file missing or invalid\", {\n file: cookieFile,\n });\n continue;\n }\n\n const cookies = await processCookieFile(cookieFile, name, domain);\n results.push(...cookies);\n }\n\n logDebug(\"ChromeCookies\", \"Query complete\", { totalCookies: results.length });\n return results;\n}\n","'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n","var balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str) {\n if (!str)\n return [];\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), true).map(unescapeBraces);\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m) return [str];\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n\n if (/\\$$/.test(m.pre)) { \n for (var k = 0; k < post.length; k++) {\n var expansion = pre+ '{' + m.body + '}' + post[k];\n expansions.push(expansion);\n }\n } else {\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,.*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], false).map(embrace);\n if (n.length === 1) {\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.abs(numeric(n[2]))\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = [];\n\n for (var j = 0; j < n.length; j++) {\n N.push.apply(N, expand(n[j], false));\n }\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n }\n\n return expansions;\n}\n\n","const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n pattern: any\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n","// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { <posix class>: [<translation>, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n '[:cntrl:]': ['\\\\p{Cc}', true],\n '[:digit:]': ['\\\\p{Nd}', true],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n '[:lower:]': ['\\\\p{Ll}', true],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}', true],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n '[:upper:]': ['\\\\p{Lu}', true],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n '[:xdigit:]': ['A-Fa-f0-9', false],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n src: string,\n uFlag: boolean,\n consumed: number,\n hasMagic: boolean\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n glob: string,\n position: number\n): ParseClassResult => {\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let uflag = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return ['$.', false, glob.length - pos, true]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n uflag = uflag || u\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c))\n }\n rangeStart = ''\n i++\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c<more...>] or c] at this point\n if (glob.startsWith('-]', i + 1)) {\n ranges.push(braceEscape(c + '-'))\n i += 2\n continue\n }\n if (glob.startsWith('-', i + 1)) {\n rangeStart = c\n i += 2\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(c))\n i++\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return ['', false, 0, false]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return ['$.', false, glob.length - pos, true]\n }\n\n // if we got one positive range, and it's a single character, then that's\n // not actually a magic pattern, it's just that one literal character.\n // we should not treat that as \"magic\", we should just return the literal\n // character. [_] is a perfectly valid way to escape glob magic chars.\n if (\n negs.length === 0 &&\n ranges.length === 1 &&\n /^\\\\?.$/.test(ranges[0]) &&\n !negate\n ) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n return [regexpEscape(r), false, endPos - pos, false]\n }\n\n const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n const comb =\n ranges.length && negs.length\n ? '(' + sranges + '|' + snegs + ')'\n : ranges.length\n ? sranges\n : snegs\n\n return [comb, uflag, endPos - pos, true]\n}\n","import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes. For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n return windowsPathsNoEscape\n ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n","// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n// 1 2 3 4 5 6 1 2 3 46 5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n// v----- .* because there's more following,\n// v v otherwise, .+ because it must be\n// v v *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n// copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set<ExtglobType>(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string): c is ExtglobType =>\n types.has(c as ExtglobType)\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n type: ExtglobType | null\n readonly #root: AST\n\n #hasMagic?: boolean\n #uflag: boolean = false\n #parts: (string | AST)[] = []\n readonly #parent?: AST\n readonly #parentIndex: number\n #negs: AST[]\n #filledNegs: boolean = false\n #options: MinimatchOptions\n #toString?: string\n // set to true if it's an extglob with no children\n // (which really means one child of '')\n #emptyExt: boolean = false\n\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n this.type = type\n // extglobs are inherently magical\n if (type) this.#hasMagic = true\n this.#parent = parent\n this.#root = this.#parent ? this.#parent.#root : this\n this.#options = this.#root === this ? options : this.#root.#options\n this.#negs = this.#root === this ? [] : this.#root.#negs\n if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n }\n\n get hasMagic(): boolean | undefined {\n /* c8 ignore start */\n if (this.#hasMagic !== undefined) return this.#hasMagic\n /* c8 ignore stop */\n for (const p of this.#parts) {\n if (typeof p === 'string') continue\n if (p.type || p.hasMagic) return (this.#hasMagic = true)\n }\n // note: will be undefined until we generate the regexp src and find out\n return this.#hasMagic\n }\n\n // reconstructs the pattern\n toString(): string {\n if (this.#toString !== undefined) return this.#toString\n if (!this.type) {\n return (this.#toString = this.#parts.map(p => String(p)).join(''))\n } else {\n return (this.#toString =\n this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n }\n }\n\n #fillNegs() {\n /* c8 ignore start */\n if (this !== this.#root) throw new Error('should only call on root')\n if (this.#filledNegs) return this\n /* c8 ignore stop */\n\n // call toString() once to fill this out\n this.toString()\n this.#filledNegs = true\n let n: AST | undefined\n while ((n = this.#negs.pop())) {\n if (n.type !== '!') continue\n // walk up the tree, appending everthing that comes AFTER parentIndex\n let p: AST | undefined = n\n let pp = p.#parent\n while (pp) {\n for (\n let i = p.#parentIndex + 1;\n !pp.type && i < pp.#parts.length;\n i++\n ) {\n for (const part of n.#parts) {\n /* c8 ignore start */\n if (typeof part === 'string') {\n throw new Error('string part in extglob AST??')\n }\n /* c8 ignore stop */\n part.copyIn(pp.#parts[i])\n }\n }\n p = pp\n pp = p.#parent\n }\n }\n return this\n }\n\n push(...parts: (string | AST)[]) {\n for (const p of parts) {\n if (p === '') continue\n /* c8 ignore start */\n if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {\n throw new Error('invalid part: ' + p)\n }\n /* c8 ignore stop */\n this.#parts.push(p)\n }\n }\n\n toJSON() {\n const ret: any[] =\n this.type === null\n ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))\n : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n if (this.isStart() && !this.type) ret.unshift([])\n if (\n this.isEnd() &&\n (this === this.#root ||\n (this.#root.#filledNegs && this.#parent?.type === '!'))\n ) {\n ret.push({})\n }\n return ret\n }\n\n isStart(): boolean {\n if (this.#root === this) return true\n // if (this.type) return !!this.#parent?.isStart()\n if (!this.#parent?.isStart()) return false\n if (this.#parentIndex === 0) return true\n // if everything AHEAD of this is a negation, then it's still the \"start\"\n const p = this.#parent\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i]\n if (!(pp instanceof AST && pp.type === '!')) {\n return false\n }\n }\n return true\n }\n\n isEnd(): boolean {\n if (this.#root === this) return true\n if (this.#parent?.type === '!') return true\n if (!this.#parent?.isEnd()) return false\n if (!this.type) return this.#parent?.isEnd()\n // if not root, it'll always have a parent\n /* c8 ignore start */\n const pl = this.#parent ? this.#parent.#parts.length : 0\n /* c8 ignore stop */\n return this.#parentIndex === pl - 1\n }\n\n copyIn(part: AST | string) {\n if (typeof part === 'string') this.push(part)\n else this.push(part.clone(this))\n }\n\n clone(parent: AST) {\n const c = new AST(this.type, parent)\n for (const p of this.#parts) {\n c.copyIn(p)\n }\n return c\n }\n\n static #parseAST(\n str: string,\n ast: AST,\n pos: number,\n opt: MinimatchOptions\n ): number {\n let escaping = false\n let inBrace = false\n let braceStart = -1\n let braceNeg = false\n if (ast.type === null) {\n // outside of a extglob, append until we find a start\n let i = pos\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {\n ast.push(acc)\n acc = ''\n const ext = new AST(c, ast)\n i = AST.#parseAST(str, ext, i, opt)\n ast.push(ext)\n continue\n }\n acc += c\n }\n ast.push(acc)\n return i\n }\n\n // some kind of extglob, pos is at the (\n // find the next | or )\n let i = pos + 1\n let part = new AST(null, ast)\n const parts: AST[] = []\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n if (isExtglobType(c) && str.charAt(i) === '(') {\n part.push(acc)\n acc = ''\n const ext = new AST(c, part)\n part.push(ext)\n i = AST.#parseAST(str, ext, i, opt)\n continue\n }\n if (c === '|') {\n part.push(acc)\n acc = ''\n parts.push(part)\n part = new AST(null, ast)\n continue\n }\n if (c === ')') {\n if (acc === '' && ast.#parts.length === 0) {\n ast.#emptyExt = true\n }\n part.push(acc)\n acc = ''\n ast.push(...parts, part)\n return i\n }\n acc += c\n }\n\n // unfinished extglob\n // if we got here, it was a malformed extglob! not an extglob, but\n // maybe something else in there.\n ast.type = null\n ast.#hasMagic = undefined\n ast.#parts = [str.substring(pos - 1)]\n return i\n }\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n const ast = new AST(null, undefined, options)\n AST.#parseAST(pattern, ast, 0, options)\n return ast\n }\n\n // returns the regular expression if there's magic, or the unescaped\n // string if not.\n toMMPattern(): MMRegExp | string {\n // should only be called on root\n /* c8 ignore start */\n if (this !== this.#root) return this.#root.toMMPattern()\n /* c8 ignore stop */\n const glob = this.toString()\n const [re, body, hasMagic, uflag] = this.toRegExpSource()\n // if we're in nocase mode, and not nocaseMagicOnly, then we do\n // still need a regular expression if we have to case-insensitively\n // match capital/lowercase characters.\n const anyMagic =\n hasMagic ||\n this.#hasMagic ||\n (this.#options.nocase &&\n !this.#options.nocaseMagicOnly &&\n glob.toUpperCase() !== glob.toLowerCase())\n if (!anyMagic) {\n return body\n }\n\n const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob,\n })\n }\n\n get options() {\n return this.#options\n }\n\n // returns the string match, the regexp source, whether there's magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it's easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it's going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it's better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it's not the first pattern,\n // and the start always gets applied.\n //\n // But that's always going to be $ if it's the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it's #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(\n allowDot?: boolean\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n const dot = allowDot ?? !!this.#options.dot\n if (this.#root === this) this.#fillNegs()\n if (!this.type) {\n const noEmpty = this.isStart() && this.isEnd()\n const src = this.#parts\n .map(p => {\n const [re, _, hasMagic, uflag] =\n typeof p === 'string'\n ? AST.#parseGlob(p, this.#hasMagic, noEmpty)\n : p.toRegExpSource(allowDot)\n this.#hasMagic = this.#hasMagic || hasMagic\n this.#uflag = this.#uflag || uflag\n return re\n })\n .join('')\n\n let start = ''\n if (this.isStart()) {\n if (typeof this.#parts[0] === 'string') {\n // this is the string that will match the start of the pattern,\n // so we need to protect against dots and such.\n\n // '.' and '..' cannot match unless the pattern is that exactly,\n // even if it starts with . or dot:true is set.\n const dotTravAllowed =\n this.#parts.length === 1 && justDots.has(this.#parts[0])\n if (!dotTravAllowed) {\n const aps = addPatternStart\n // check if we have a possibility of matching . or ..,\n // and prevent that.\n const needNoTrav =\n // dots are allowed, and the pattern starts with [ or .\n (dot && aps.has(src.charAt(0))) ||\n // the pattern starts with \\., and then [ or .\n (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n // the pattern starts with \\.\\., and then [ or .\n (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n // no need to prevent dots if it can't match a dot, or if a\n // sub-pattern will be preventing it anyway.\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''\n }\n }\n }\n\n // append the \"end of path portion\" pattern to negation tails\n let end = ''\n if (\n this.isEnd() &&\n this.#root.#filledNegs &&\n this.#parent?.type === '!'\n ) {\n end = '(?:$|\\\\/)'\n }\n const final = start + src + end\n return [\n final,\n unescape(src),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n // We need to calculate the body *twice* if it's a repeat pattern\n // at the start, once in nodot mode, then again in dot mode, so a\n // pattern like *(?) can match 'x.y'\n\n const repeated = this.type === '*' || this.type === '+'\n // some kind of extglob\n const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n let body = this.#partsToRegExp(dot)\n\n if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n // invalid extglob, has to at least be *something* present, if it's\n // the entire path portion.\n const s = this.toString()\n this.#parts = [s]\n this.type = null\n this.#hasMagic = undefined\n return [s, unescape(this.toString()), false, false]\n }\n\n // XXX abstract out this map method\n let bodyDotAllowed =\n !repeated || allowDot || dot || !startNoDot\n ? ''\n : this.#partsToRegExp(true)\n if (bodyDotAllowed === body) {\n bodyDotAllowed = ''\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`\n }\n\n // an empty !() is exactly equivalent to a starNoEmpty\n let final = ''\n if (this.type === '!' && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n } else {\n const close =\n this.type === '!'\n ? // !() must match something,but !(x) can match ''\n '))' +\n (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n star +\n ')'\n : this.type === '@'\n ? ')'\n : this.type === '?'\n ? ')?'\n : this.type === '+' && bodyDotAllowed\n ? ')'\n : this.type === '*' && bodyDotAllowed\n ? `)?`\n : `)${this.type}`\n final = start + body + close\n }\n return [\n final,\n unescape(body),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n #partsToRegExp(dot: boolean) {\n return this.#parts\n .map(p => {\n // extglob ASTs should only contain parent ASTs\n /* c8 ignore start */\n if (typeof p === 'string') {\n throw new Error('string type in extglob ast??')\n }\n /* c8 ignore stop */\n // can ignore hasMagic, because extglobs are already always magic\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n this.#uflag = this.#uflag || uflag\n return re\n })\n .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n .join('|')\n }\n\n static #parseGlob(\n glob: string,\n hasMagic: boolean | undefined,\n noEmpty: boolean = false\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n let escaping = false\n let re = ''\n let uflag = false\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i)\n if (escaping) {\n escaping = false\n re += (reSpecials.has(c) ? '\\\\' : '') + c\n continue\n }\n if (c === '\\\\') {\n if (i === glob.length - 1) {\n re += '\\\\\\\\'\n } else {\n escaping = true\n }\n continue\n }\n if (c === '[') {\n const [src, needUflag, consumed, magic] = parseClass(glob, i)\n if (consumed) {\n re += src\n uflag = uflag || needUflag\n i += consumed - 1\n hasMagic = hasMagic || magic\n continue\n }\n }\n if (c === '*') {\n if (noEmpty && glob === '*') re += starNoEmpty\n else re += star\n hasMagic = true\n continue\n }\n if (c === '?') {\n re += qmark\n hasMagic = true\n continue\n }\n re += regExpEscape(c)\n }\n return [re, unescape(glob), !!hasMagic, uflag]\n }\n}\n","import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n return windowsPathsNoEscape\n ? s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n","import expand from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\ntype Platform =\n | 'aix'\n | 'android'\n | 'darwin'\n | 'freebsd'\n | 'haiku'\n | 'linux'\n | 'openbsd'\n | 'sunos'\n | 'win32'\n | 'cygwin'\n | 'netbsd'\n\nexport interface MinimatchOptions {\n nobrace?: boolean\n nocomment?: boolean\n nonegate?: boolean\n debug?: boolean\n noglobstar?: boolean\n noext?: boolean\n nonull?: boolean\n windowsPathsNoEscape?: boolean\n allowWindowsEscape?: boolean\n partial?: boolean\n dot?: boolean\n nocase?: boolean\n nocaseMagicOnly?: boolean\n magicalBraces?: boolean\n matchBase?: boolean\n flipNegate?: boolean\n preserveMultipleSlashes?: boolean\n optimizationLevel?: number\n platform?: Platform\n windowsNoMagicRoot?: boolean\n}\n\nexport const minimatch = (\n p: string,\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) => !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) => f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) => f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n typeof process === 'object' && process\n ? (typeof process.env === 'object' &&\n process.env &&\n process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n process.platform\n : 'posix'\n) as Platform\ntype Sep = '\\\\' | '/'\nconst path: { [k: string]: { sep: Sep } } = {\n win32: { sep: '\\\\' },\n posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n (pattern: string, options: MinimatchOptions = {}) =>\n (p: string) =>\n minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch\n }\n\n const orig = minimatch\n\n const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n orig(p, pattern, ext(def, options))\n\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern: string, options: MinimatchOptions = {}) {\n super(pattern, ext(def, options))\n }\n static defaults(options: MinimatchOptions) {\n return orig.defaults(ext(def, options)).Minimatch\n }\n },\n\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n super(type, parent, ext(def, options))\n }\n /* c8 ignore stop */\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options))\n }\n },\n\n unescape: (\n s: string,\n options: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n ) => orig.unescape(s, ext(def, options)),\n\n escape: (\n s: string,\n options: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n ) => orig.escape(s, ext(def, options)),\n\n filter: (pattern: string, options: MinimatchOptions = {}) =>\n orig.filter(pattern, ext(def, options)),\n\n defaults: (options: MinimatchOptions) => orig.defaults(ext(def, options)),\n\n makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n orig.makeRe(pattern, ext(def, options)),\n\n braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n orig.braceExpand(pattern, ext(def, options)),\n\n match: (list: string[], pattern: string, options: MinimatchOptions = {}) =>\n orig.match(list, pattern, ext(def, options)),\n\n sep: orig.sep,\n GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // Thanks to Yeting Li <https://github.com/yetingli> for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern)\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n list: string[],\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n const mm = new Minimatch(pattern, options)\n list = list.filter(f => mm.match(f))\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n _src?: string\n _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n options: MinimatchOptions\n set: ParseReturnFiltered[][]\n pattern: string\n\n windowsPathsNoEscape: boolean\n nonegate: boolean\n negate: boolean\n comment: boolean\n empty: boolean\n preserveMultipleSlashes: boolean\n partial: boolean\n globSet: string[]\n globParts: string[][]\n nocase: boolean\n\n isWindows: boolean\n platform: Platform\n windowsNoMagicRoot: boolean\n\n regexp: false | null | MMRegExp\n constructor(pattern: string, options: MinimatchOptions = {}) {\n assertValidPattern(pattern)\n\n options = options || {}\n this.options = options\n this.pattern = pattern\n this.platform = options.platform || defaultPlatform\n this.isWindows = this.platform === 'win32'\n this.windowsPathsNoEscape =\n !!options.windowsPathsNoEscape || options.allowWindowsEscape === false\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/')\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n this.regexp = null\n this.negate = false\n this.nonegate = !!options.nonegate\n this.comment = false\n this.empty = false\n this.partial = !!options.partial\n this.nocase = !!this.options.nocase\n this.windowsNoMagicRoot =\n options.windowsNoMagicRoot !== undefined\n ? options.windowsNoMagicRoot\n : !!(this.isWindows && this.nocase)\n\n this.globSet = []\n this.globParts = []\n this.set = []\n\n // make the set of regexps etc.\n this.make()\n }\n\n hasMagic(): boolean {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== 'string') return true\n }\n }\n return false\n }\n\n debug(..._: any[]) {}\n\n make() {\n const pattern = this.pattern\n const options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n this.globSet = [...new Set(this.braceExpand())]\n\n if (options.debug) {\n this.debug = (...args: any[]) => console.error(...args)\n }\n\n this.debug(this.pattern, this.globSet)\n\n // step 3: now we have a set, so turn each one into a series of\n // path-portion matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n //\n // First, we preprocess to make the glob pattern sets a bit simpler\n // and deduped. There are some perf-killing patterns that can cause\n // problems with a glob walk, but we can simplify them down a bit.\n const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n this.globParts = this.preprocess(rawGlobParts)\n this.debug(this.pattern, this.globParts)\n\n // glob --> regexps\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n // check if it's a drive or unc path.\n const isUNC =\n s[0] === '' &&\n s[1] === '' &&\n (s[2] === '?' || !globMagic.test(s[2])) &&\n !globMagic.test(s[3])\n const isDrive = /^[a-z]:/i.test(s[0])\n if (isUNC) {\n return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n }\n }\n return s.map(ss => this.parse(ss))\n })\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n this.set = set.filter(\n s => s.indexOf(false) === -1\n ) as ParseReturnFiltered[][]\n\n // do not treat the ? in UNC paths as magic\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i]\n if (\n p[0] === '' &&\n p[1] === '' &&\n this.globParts[i][2] === '?' &&\n typeof p[3] === 'string' &&\n /^[a-z]:$/i.test(p[3])\n ) {\n p[2] = '?'\n }\n }\n }\n\n this.debug(this.pattern, this.set)\n }\n\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts: string[][]) {\n // if we're not in globstar mode, then turn all ** into *\n if (this.options.noglobstar) {\n for (let i = 0; i < globParts.length; i++) {\n for (let j = 0; j < globParts[i].length; j++) {\n if (globParts[i][j] === '**') {\n globParts[i][j] = '*'\n }\n }\n }\n }\n\n const { optimizationLevel = 1 } = this.options\n\n if (optimizationLevel >= 2) {\n // aggressive optimization for the purpose of fs walking\n globParts = this.firstPhasePreProcess(globParts)\n globParts = this.secondPhasePreProcess(globParts)\n } else if (optimizationLevel >= 1) {\n // just basic optimizations to remove some .. parts\n globParts = this.levelOneOptimize(globParts)\n } else {\n // just collapse multiple ** portions into one\n globParts = this.adjascentGlobstarOptimize(globParts)\n }\n\n return globParts\n }\n\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let i = gs\n while (parts[i + 1] === '**') {\n i++\n }\n if (i !== gs) {\n parts.splice(gs, i - gs)\n }\n }\n return parts\n })\n }\n\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n parts = parts.reduce((set: string[], part) => {\n const prev = set[set.length - 1]\n if (part === '**' && prev === '**') {\n return set\n }\n if (part === '..') {\n if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n set.pop()\n return set\n }\n }\n set.push(part)\n return set\n }, [])\n return parts.length === 0 ? [''] : parts\n })\n }\n\n levelTwoFileOptimize(parts: string | string[]) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts)\n }\n let didSomething: boolean = false\n do {\n didSomething = false\n // <pre>/<e>/<rest> -> <pre>/<rest>\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i]\n // don't squeeze out UNC patterns\n if (i === 1 && p === '' && parts[0] === '') continue\n if (p === '.' || p === '') {\n didSomething = true\n parts.splice(i, 1)\n i--\n }\n }\n if (\n parts[0] === '.' &&\n parts.length === 2 &&\n (parts[1] === '.' || parts[1] === '')\n ) {\n didSomething = true\n parts.pop()\n }\n }\n\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n let dd: number = 0\n while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n const p = parts[dd - 1]\n if (p && p !== '.' && p !== '..' && p !== '**') {\n didSomething = true\n parts.splice(dd - 1, 2)\n dd -= 2\n }\n }\n } while (didSomething)\n return parts.length === 0 ? [''] : parts\n }\n\n // First phase: single-pattern processing\n // <pre> is 1 or more portions\n // <rest> is 1 or more portions\n // <p> is any portion other than ., .., '', or **\n // <e> is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}\n // <pre>/<e>/<rest> -> <pre>/<rest>\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n // **/**/<rest> -> **/<rest>\n //\n // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow\n // this WOULD be allowed if ** did follow symlinks, or * didn't\n firstPhasePreProcess(globParts: string[][]) {\n let didSomething = false\n do {\n didSomething = false\n // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n // <pre>/**/**/<rest> -> <pre>/**/<rest>\n gss++\n }\n // eg, if gs is 2 and gss is 4, that means we have 3 **\n // parts, and can remove 2 of them.\n if (gss > gs) {\n parts.splice(gs + 1, gss - gs)\n }\n\n let next = parts[gs + 1]\n const p = parts[gs + 2]\n const p2 = parts[gs + 3]\n if (next !== '..') continue\n if (\n !p ||\n p === '.' ||\n p === '..' ||\n !p2 ||\n p2 === '.' ||\n p2 === '..'\n ) {\n continue\n }\n didSomething = true\n // edit parts in place, and push the new one\n parts.splice(gs, 1)\n const other = parts.slice(0)\n other[gs] = '**'\n globParts.push(other)\n gs--\n }\n\n // <pre>/<e>/<rest> -> <pre>/<rest>\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i]\n // don't squeeze out UNC patterns\n if (i === 1 && p === '' && parts[0] === '') continue\n if (p === '.' || p === '') {\n didSomething = true\n parts.splice(i, 1)\n i--\n }\n }\n if (\n parts[0] === '.' &&\n parts.length === 2 &&\n (parts[1] === '.' || parts[1] === '')\n ) {\n didSomething = true\n parts.pop()\n }\n }\n\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n let dd: number = 0\n while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n const p = parts[dd - 1]\n if (p && p !== '.' && p !== '..' && p !== '**') {\n didSomething = true\n const needDot = dd === 1 && parts[dd + 1] === '**'\n const splin = needDot ? ['.'] : []\n parts.splice(dd - 1, 2, ...splin)\n if (parts.length === 0) parts.push('')\n dd -= 2\n }\n }\n }\n } while (didSomething)\n\n return globParts\n }\n\n // second phase: multi-pattern dedupes\n // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>\n // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>\n // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>\n //\n // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>\n // ^-- not valid because ** doens't follow symlinks\n secondPhasePreProcess(globParts: string[][]): string[][] {\n for (let i = 0; i < globParts.length - 1; i++) {\n for (let j = i + 1; j < globParts.length; j++) {\n const matched = this.partsMatch(\n globParts[i],\n globParts[j],\n !this.preserveMultipleSlashes\n )\n if (matched) {\n globParts[i] = []\n globParts[j] = matched\n break\n }\n }\n }\n return globParts.filter(gs => gs.length)\n }\n\n partsMatch(\n a: string[],\n b: string[],\n emptyGSMatch: boolean = false\n ): false | string[] {\n let ai = 0\n let bi = 0\n let result: string[] = []\n let which: string = ''\n while (ai < a.length && bi < b.length) {\n if (a[ai] === b[bi]) {\n result.push(which === 'b' ? b[bi] : a[ai])\n ai++\n bi++\n } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n result.push(a[ai])\n ai++\n } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n result.push(b[bi])\n bi++\n } else if (\n a[ai] === '*' &&\n b[bi] &&\n (this.options.dot || !b[bi].startsWith('.')) &&\n b[bi] !== '**'\n ) {\n if (which === 'b') return false\n which = 'a'\n result.push(a[ai])\n ai++\n bi++\n } else if (\n b[bi] === '*' &&\n a[ai] &&\n (this.options.dot || !a[ai].startsWith('.')) &&\n a[ai] !== '**'\n ) {\n if (which === 'a') return false\n which = 'b'\n result.push(b[bi])\n ai++\n bi++\n } else {\n return false\n }\n }\n // if we fall out of the loop, it means they two are identical\n // as long as their lengths match\n return a.length === b.length && result\n }\n\n parseNegate() {\n if (this.nonegate) return\n\n const pattern = this.pattern\n let negate = false\n let negateOffset = 0\n\n for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n negate = !negate\n negateOffset++\n }\n\n if (negateOffset) this.pattern = pattern.slice(negateOffset)\n this.negate = negate\n }\n\n // set partial to true to test if, for example,\n // \"/a/b\" matches the start of \"/*/b/*/d\"\n // Partial means, if you run out of file before you run\n // out of pattern, then that's fine, as long as all\n // the parts match.\n matchOne(file: string[], pattern: ParseReturn[], partial: boolean = false) {\n const options = this.options\n\n // UNC paths like //?/X:/... can match X:/... and vice versa\n // Drive letters in absolute drive or unc paths are always compared\n // case-insensitively.\n if (this.isWindows) {\n const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n const fileUNC =\n !fileDrive &&\n file[0] === '' &&\n file[1] === '' &&\n file[2] === '?' &&\n /^[a-z]:$/i.test(file[3])\n\n const patternDrive =\n typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n const patternUNC =\n !patternDrive &&\n pattern[0] === '' &&\n pattern[1] === '' &&\n pattern[2] === '?' &&\n typeof pattern[3] === 'string' &&\n /^[a-z]:$/i.test(pattern[3])\n\n const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined\n const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined\n if (typeof fdi === 'number' && typeof pdi === 'number') {\n const [fd, pd]: [string, string] = [file[fdi], pattern[pdi] as string]\n if (fd.toLowerCase() === pd.toLowerCase()) {\n pattern[pdi] = fd\n if (pdi > fdi) {\n pattern = pattern.slice(pdi)\n } else if (fdi > pdi) {\n file = file.slice(fdi)\n }\n }\n }\n }\n\n // resolve and reduce . and .. portions in the file as well.\n // dont' need to do the second phase, because it's only one string[]\n const { optimizationLevel = 1 } = this.options\n if (optimizationLevel >= 2) {\n file = this.levelTwoFileOptimize(file)\n }\n\n this.debug('matchOne', this, { file, pattern })\n this.debug('matchOne', file.length, pattern.length)\n\n for (\n var fi = 0, pi = 0, fl = file.length, pl = pattern.length;\n fi < fl && pi < pl;\n fi++, pi++\n ) {\n this.debug('matchOne loop')\n var p = pattern[pi]\n var f = file[fi]\n\n this.debug(pattern, p, f)\n\n // should be impossible.\n // some invalid regexp stuff in the set.\n /* c8 ignore start */\n if (p === false) {\n return false\n }\n /* c8 ignore stop */\n\n if (p === GLOBSTAR) {\n this.debug('GLOBSTAR', [pattern, p, f])\n\n // \"**\"\n // a/**/b/**/c would match the following:\n // a/b/x/y/z/c\n // a/x/y/z/b/c\n // a/b/x/b/x/c\n // a/b/c\n // To do this, take the rest of the pattern after\n // the **, and see if it would match the file remainder.\n // If so, return success.\n // If not, the ** \"swallows\" a segment, and try again.\n // This is recursively awful.\n //\n // a/**/b/**/c matching a/b/x/y/z/c\n // - a matches a\n // - doublestar\n // - matchOne(b/x/y/z/c, b/**/c)\n // - b matches b\n // - doublestar\n // - matchOne(x/y/z/c, c) -> no\n // - matchOne(y/z/c, c) -> no\n // - matchOne(z/c, c) -> no\n // - matchOne(c, c) yes, hit\n var fr = fi\n var pr = pi + 1\n if (pr === pl) {\n this.debug('** at the end')\n // a ** at the end will just swallow the rest.\n // We have found a match.\n // however, it will not swallow /.x, unless\n // options.dot is set.\n // . and .. are *never* matched by **, for explosively\n // exponential reasons.\n for (; fi < fl; fi++) {\n if (\n file[fi] === '.' ||\n file[fi] === '..' ||\n (!options.dot && file[fi].charAt(0) === '.')\n )\n return false\n }\n return true\n }\n\n // ok, let's see if we can swallow whatever we can.\n while (fr < fl) {\n var swallowee = file[fr]\n\n this.debug('\\nglobstar while', file, fr, pattern, pr, swallowee)\n\n // XXX remove this slice. Just pass the start index.\n if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {\n this.debug('globstar found match!', fr, fl, swallowee)\n // found a match.\n return true\n } else {\n // can't swallow \".\" or \"..\" ever.\n // can only swallow \".foo\" when explicitly asked.\n if (\n swallowee === '.' ||\n swallowee === '..' ||\n (!options.dot && swallowee.charAt(0) === '.')\n ) {\n this.debug('dot detected!', file, fr, pattern, pr)\n break\n }\n\n // ** swallows a segment, and continue.\n this.debug('globstar swallow a segment, and continue')\n fr++\n }\n }\n\n // no match was found.\n // However, in partial mode, we can't say this is necessarily over.\n /* c8 ignore start */\n if (partial) {\n // ran out of file\n this.debug('\\n>>> no match, partial?', file, fr, pattern, pr)\n if (fr === fl) {\n return true\n }\n }\n /* c8 ignore stop */\n return false\n }\n\n // something other than **\n // non-magic patterns just have to match exactly\n // patterns with magic have been turned into regexps.\n let hit: boolean\n if (typeof p === 'string') {\n hit = f === p\n this.debug('string match', p, f, hit)\n } else {\n hit = p.test(f)\n this.debug('pattern match', p, f, hit)\n }\n\n if (!hit) return false\n }\n\n // Note: ending in / means that we'll get a final \"\"\n // at the end of the pattern. This can only match a\n // corresponding \"\" at the end of the file.\n // If the file ends in /, then it can only match a\n // a pattern that ends in /, unless the pattern just\n // doesn't have any more for it. But, a/b/ should *not*\n // match \"a/b/*\", even though \"\" matches against the\n // [^/]*? pattern, except in partial mode, where it might\n // simply not be reached yet.\n // However, a/b/ should still satisfy a/*\n\n // now either we fell off the end of the pattern, or we're done.\n if (fi === fl && pi === pl) {\n // ran out of pattern and filename at the same time.\n // an exact hit!\n return true\n } else if (fi === fl) {\n // ran out of file, but still had pattern left.\n // this is ok if we're doing the match as part of\n // a glob fs traversal.\n return partial\n } else if (pi === pl) {\n // ran out of pattern, still have file left.\n // this is only acceptable if we're on the very last\n // empty segment of a file with a trailing slash.\n // a/* should match a/b/\n return fi === fl - 1 && file[fi] === ''\n\n /* c8 ignore start */\n } else {\n // should be unreachable.\n throw new Error('wtf?')\n }\n /* c8 ignore stop */\n }\n\n braceExpand() {\n return braceExpand(this.pattern, this.options)\n }\n\n parse(pattern: string): ParseReturn {\n assertValidPattern(pattern)\n\n const options = this.options\n\n // shortcuts\n if (pattern === '**') return GLOBSTAR\n if (pattern === '') return ''\n\n // far and away, the most common glob pattern parts are\n // *, *.*, and *.<ext> Add a fast check method for those.\n let m: RegExpMatchArray | null\n let fastTest: null | ((f: string) => boolean) = null\n if ((m = pattern.match(starRE))) {\n fastTest = options.dot ? starTestDot : starTest\n } else if ((m = pattern.match(starDotExtRE))) {\n fastTest = (\n options.nocase\n ? options.dot\n ? starDotExtTestNocaseDot\n : starDotExtTestNocase\n : options.dot\n ? starDotExtTestDot\n : starDotExtTest\n )(m[1])\n } else if ((m = pattern.match(qmarksRE))) {\n fastTest = (\n options.nocase\n ? options.dot\n ? qmarksTestNocaseDot\n : qmarksTestNocase\n : options.dot\n ? qmarksTestDot\n : qmarksTest\n )(m)\n } else if ((m = pattern.match(starDotStarRE))) {\n fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n } else if ((m = pattern.match(dotStarRE))) {\n fastTest = dotStarTest\n }\n\n const re = AST.fromGlob(pattern, this.options).toMMPattern()\n if (fastTest && typeof re === 'object') {\n // Avoids overriding in frozen environments\n Reflect.defineProperty(re, 'test', { value: fastTest })\n }\n return re\n }\n\n makeRe() {\n if (this.regexp || this.regexp === false) return this.regexp\n\n // at this point, this.set is a 2d array of partial\n // pattern strings, or \"**\".\n //\n // It's better to use .match(). This function shouldn't\n // be used, really, but it's pretty convenient sometimes,\n // when you just want to work with a regex.\n const set = this.set\n\n if (!set.length) {\n this.regexp = false\n return this.regexp\n }\n const options = this.options\n\n const twoStar = options.noglobstar\n ? star\n : options.dot\n ? twoStarDot\n : twoStarNoDot\n const flags = new Set(options.nocase ? ['i'] : [])\n\n // regexpify non-globstar patterns\n // if ** is only item, then we just do one twoStar\n // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n // if ** is last, append (\\/twoStar|) to previous\n // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n // then filter out GLOBSTAR symbols\n let re = set\n .map(pattern => {\n const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n if (p instanceof RegExp) {\n for (const f of p.flags.split('')) flags.add(f)\n }\n return typeof p === 'string'\n ? regExpEscape(p)\n : p === GLOBSTAR\n ? GLOBSTAR\n : p._src\n }) as (string | typeof GLOBSTAR)[]\n pp.forEach((p, i) => {\n const next = pp[i + 1]\n const prev = pp[i - 1]\n if (p !== GLOBSTAR || prev === GLOBSTAR) {\n return\n }\n if (prev === undefined) {\n if (next !== undefined && next !== GLOBSTAR) {\n pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n } else {\n pp[i] = twoStar\n }\n } else if (next === undefined) {\n pp[i - 1] = prev + '(?:\\\\/|' + twoStar + ')?'\n } else if (next !== GLOBSTAR) {\n pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n pp[i + 1] = GLOBSTAR\n }\n })\n return pp.filter(p => p !== GLOBSTAR).join('/')\n })\n .join('|')\n\n // need to wrap in parens if we had more than one thing with |,\n // otherwise only the first will be anchored to ^ and the last to $\n const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n // must match entire pattern\n // ending in a * or ** will make it less strict.\n re = '^' + open + re + close + '$'\n\n // can match anything, as long as it's not this.\n if (this.negate) re = '^(?!' + re + ').+$'\n\n try {\n this.regexp = new RegExp(re, [...flags].join(''))\n /* c8 ignore start */\n } catch (ex) {\n // should be impossible\n this.regexp = false\n }\n /* c8 ignore stop */\n return this.regexp\n }\n\n slashSplit(p: string) {\n // if p starts with // on windows, we preserve that\n // so that UNC paths aren't broken. Otherwise, any number of\n // / characters are coalesced into one, unless\n // preserveMultipleSlashes is set to true.\n if (this.preserveMultipleSlashes) {\n return p.split('/')\n } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n // add an extra '' for the one we lose\n return ['', ...p.split(/\\/+/)]\n } else {\n return p.split(/\\/+/)\n }\n }\n\n match(f: string, partial = this.partial) {\n this.debug('match', f, this.pattern)\n // short-circuit in the case of busted things.\n // comments, etc.\n if (this.comment) {\n return false\n }\n if (this.empty) {\n return f === ''\n }\n\n if (f === '/' && partial) {\n return true\n }\n\n const options = this.options\n\n // windows: need to use /, not \\\n if (this.isWindows) {\n f = f.split('\\\\').join('/')\n }\n\n // treat the test path as a set of pathparts.\n const ff = this.slashSplit(f)\n this.debug(this.pattern, 'split', ff)\n\n // just ONE of the pattern sets in this.set needs to match\n // in order for it to be valid. If negating, then just one\n // match means that we have failed.\n // Either way, return on the first hit.\n\n const set = this.set\n this.debug(this.pattern, 'set', set)\n\n // Find the basename of the path by looking for the last non-empty segment\n let filename: string = ff[ff.length - 1]\n if (!filename) {\n for (let i = ff.length - 2; !filename && i >= 0; i--) {\n filename = ff[i]\n }\n }\n\n for (let i = 0; i < set.length; i++) {\n const pattern = set[i]\n let file = ff\n if (options.matchBase && pattern.length === 1) {\n file = [filename]\n }\n const hit = this.matchOne(file, pattern, partial)\n if (hit) {\n if (options.flipNegate) {\n return true\n }\n return !this.negate\n }\n }\n\n // didn't get any hits. this is success if it's a negative\n // pattern, failure otherwise.\n if (options.flipNegate) {\n return false\n }\n return this.negate\n }\n\n static defaults(def: MinimatchOptions) {\n return minimatch.defaults(def).Minimatch\n }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n","/**\n * @module LRUCache\n */\n\n// module-private names and types\ntype Perf = { now: () => number }\nconst perf: Perf =\n typeof performance === 'object' &&\n performance &&\n typeof performance.now === 'function'\n ? performance\n : Date\n\nconst warned = new Set<string>()\n\n// either a function or a class\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n typeof process === 'object' && !!process ? process : {}\n) as { [k: string]: any }\n/* c8 ignore start */\n\nconst emitWarning = (\n msg: string,\n type: string,\n code: string,\n fn: ForC\n) => {\n typeof PROCESS.emitWarning === 'function'\n ? PROCESS.emitWarning(msg, type, code, fn)\n : console.error(`[${code}] ${type}: ${msg}`)\n}\n\nlet AC = globalThis.AbortController\nlet AS = globalThis.AbortSignal\n\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n //@ts-ignore\n AS = class AbortSignal {\n onabort?: (...a: any[]) => any\n _onabort: ((...a: any[]) => any)[] = []\n reason?: any\n aborted: boolean = false\n addEventListener(_: string, fn: (...a: any[]) => any) {\n this._onabort.push(fn)\n }\n }\n //@ts-ignore\n AC = class AbortController {\n constructor() {\n warnACPolyfill()\n }\n signal = new AS()\n abort(reason: any) {\n if (this.signal.aborted) return\n //@ts-ignore\n this.signal.reason = reason\n //@ts-ignore\n this.signal.aborted = true\n //@ts-ignore\n for (const fn of this.signal._onabort) {\n fn(reason)\n }\n this.signal.onabort?.(reason)\n }\n }\n let printACPolyfillWarning =\n PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'\n const warnACPolyfill = () => {\n if (!printACPolyfillWarning) return\n printACPolyfillWarning = false\n emitWarning(\n 'AbortController is not defined. If using lru-cache in ' +\n 'node 14, load an AbortController polyfill from the ' +\n '`node-abort-controller` package. A minimal polyfill is ' +\n 'provided for use by LRUCache.fetch(), but it should not be ' +\n 'relied upon in other contexts (eg, passing it to other APIs that ' +\n 'use AbortController/AbortSignal might have undesirable effects). ' +\n 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',\n 'NO_ABORT_CONTROLLER',\n 'ENOTSUP',\n warnACPolyfill\n )\n }\n}\n/* c8 ignore stop */\n\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: any): n is PosInt =>\n n && n === Math.floor(n) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values. Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max: number) =>\n !isPosInt(max)\n ? null\n : max <= Math.pow(2, 8)\n ? Uint8Array\n : max <= Math.pow(2, 16)\n ? Uint16Array\n : max <= Math.pow(2, 32)\n ? Uint32Array\n : max <= Number.MAX_SAFE_INTEGER\n ? ZeroArray\n : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array<number> {\n constructor(size: number) {\n super(size)\n this.fill(0)\n }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n heap: NumberArray\n length: number\n // private constructor\n static #constructing: boolean = false\n static create(max: number): StackLike {\n const HeapCls = getUintArray(max)\n if (!HeapCls) return []\n Stack.#constructing = true\n const s = new Stack(max, HeapCls)\n Stack.#constructing = false\n return s\n }\n constructor(\n max: number,\n HeapCls: { new (n: number): NumberArray }\n ) {\n /* c8 ignore start */\n if (!Stack.#constructing) {\n throw new TypeError('instantiate Stack using Stack.create(n)')\n }\n /* c8 ignore stop */\n this.heap = new HeapCls(max)\n this.length = 0\n }\n push(n: Index) {\n this.heap[this.length++] = n\n }\n pop(): Index {\n return this.heap[--this.length] as Index\n }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch<V> = Promise<V | undefined> & {\n __returned: BackgroundFetch<V> | undefined\n __abortController: AbortController\n __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask<K, V> = [\n value: V,\n key: K,\n reason: LRUCache.DisposeReason\n]\n\nexport namespace LRUCache {\n /**\n * An integer greater than 0, reflecting the calculated size of items\n */\n export type Size = number\n\n /**\n * Integer greater than 0, representing some number of milliseconds, or the\n * time at which a TTL started counting from.\n */\n export type Milliseconds = number\n\n /**\n * An integer greater than 0, reflecting a number of items\n */\n export type Count = number\n\n /**\n * The reason why an item was removed from the cache, passed\n * to the {@link Disposer} methods.\n *\n * - `evict`: The item was evicted because it is the least recently used,\n * and the cache is full.\n * - `set`: A new value was set, overwriting the old value being disposed.\n * - `delete`: The item was explicitly deleted, either by calling\n * {@link LRUCache#delete}, {@link LRUCache#clear}, or\n * {@link LRUCache#set} with an undefined value.\n * - `expire`: The item was removed due to exceeding its TTL.\n * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n * `undefined` or was aborted, causing the item to be deleted.\n */\n export type DisposeReason =\n | 'evict'\n | 'set'\n | 'delete'\n | 'expire'\n | 'fetch'\n /**\n * A method called upon item removal, passed as the\n * {@link OptionsBase.dispose} and/or\n * {@link OptionsBase.disposeAfter} options.\n */\n export type Disposer<K, V> = (\n value: V,\n key: K,\n reason: DisposeReason\n ) => void\n\n /**\n * A function that returns the effective calculated size\n * of an entry in the cache.\n */\n export type SizeCalculator<K, V> = (value: V, key: K) => Size\n\n /**\n * Options provided to the\n * {@link OptionsBase.fetchMethod} function.\n */\n export interface FetcherOptions<K, V, FC = unknown> {\n signal: AbortSignal\n options: FetcherFetchOptions<K, V, FC>\n /**\n * Object provided in the {@link FetchOptions.context} option to\n * {@link LRUCache#fetch}\n */\n context: FC\n }\n\n /**\n * Occasionally, it may be useful to track the internal behavior of the\n * cache, particularly for logging, debugging, or for behavior within the\n * `fetchMethod`. To do this, you can pass a `status` object to the\n * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n *\n * The `status` option should be a plain JavaScript object. The following\n * fields will be set on it appropriately, depending on the situation.\n */\n export interface Status<V> {\n /**\n * The status of a set() operation.\n *\n * - add: the item was not found in the cache, and was added\n * - update: the item was in the cache, with the same value provided\n * - replace: the item was in the cache, and replaced\n * - miss: the item was not added to the cache for some reason\n */\n set?: 'add' | 'update' | 'replace' | 'miss'\n\n /**\n * the ttl stored for the item, or undefined if ttls are not used.\n */\n ttl?: Milliseconds\n\n /**\n * the start time for the item, or undefined if ttls are not used.\n */\n start?: Milliseconds\n\n /**\n * The timestamp used for TTL calculation\n */\n now?: Milliseconds\n\n /**\n * the remaining ttl for the item, or undefined if ttls are not used.\n */\n remainingTTL?: Milliseconds\n\n /**\n * The calculated size for the item, if sizes are used.\n */\n entrySize?: Size\n\n /**\n * The total calculated size of the cache, if sizes are used.\n */\n totalCalculatedSize?: Size\n\n /**\n * A flag indicating that the item was not stored, due to exceeding the\n * {@link OptionsBase.maxEntrySize}\n */\n maxEntrySizeExceeded?: true\n\n /**\n * The old value, specified in the case of `set:'update'` or\n * `set:'replace'`\n */\n oldValue?: V\n\n /**\n * The results of a {@link LRUCache#has} operation\n *\n * - hit: the item was found in the cache\n * - stale: the item was found in the cache, but is stale\n * - miss: the item was not found in the cache\n */\n has?: 'hit' | 'stale' | 'miss'\n\n /**\n * The status of a {@link LRUCache#fetch} operation.\n * Note that this can change as the underlying fetch() moves through\n * various states.\n *\n * - inflight: there is another fetch() for this key which is in process\n * - get: there is no {@link OptionsBase.fetchMethod}, so\n * {@link LRUCache#get} was called.\n * - miss: the item is not in cache, and will be fetched.\n * - hit: the item is in the cache, and was resolved immediately.\n * - stale: the item is in the cache, but stale.\n * - refresh: the item is in the cache, and not stale, but\n * {@link FetchOptions.forceRefresh} was specified.\n */\n fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n /**\n * The {@link OptionsBase.fetchMethod} was called\n */\n fetchDispatched?: true\n\n /**\n * The cached value was updated after a successful call to\n * {@link OptionsBase.fetchMethod}\n */\n fetchUpdated?: true\n\n /**\n * The reason for a fetch() rejection. Either the error raised by the\n * {@link OptionsBase.fetchMethod}, or the reason for an\n * AbortSignal.\n */\n fetchError?: Error\n\n /**\n * The fetch received an abort signal\n */\n fetchAborted?: true\n\n /**\n * The abort signal received was ignored, and the fetch was allowed to\n * continue.\n */\n fetchAbortIgnored?: true\n\n /**\n * The fetchMethod promise resolved successfully\n */\n fetchResolved?: true\n\n /**\n * The fetchMethod promise was rejected\n */\n fetchRejected?: true\n\n /**\n * The status of a {@link LRUCache#get} operation.\n *\n * - fetching: The item is currently being fetched. If a previous value\n * is present and allowed, that will be returned.\n * - stale: The item is in the cache, and is stale.\n * - hit: the item is in the cache\n * - miss: the item is not in the cache\n */\n get?: 'stale' | 'hit' | 'miss'\n\n /**\n * A fetch or get operation returned a stale value.\n */\n returnedStale?: true\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#fetch}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link OptionsBase.noDeleteOnFetchRejection},\n * {@link OptionsBase.allowStaleOnFetchRejection},\n * {@link FetchOptions.forceRefresh}, and\n * {@link FetcherOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n * function, but the {@link GetOptions} fields will of course have no\n * effect, as the {@link LRUCache#get} call already happened by the time\n * the fetchMethod is called.\n */\n export interface FetcherFetchOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n | 'noDeleteOnFetchRejection'\n | 'allowStaleOnFetchRejection'\n | 'ignoreFetchAbort'\n | 'allowStaleOnFetchAbort'\n > {\n status?: Status<V>\n size?: Size\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#fetch} method.\n */\n export interface FetchOptions<K, V, FC>\n extends FetcherFetchOptions<K, V, FC> {\n /**\n * Set to true to force a re-load of the existing data, even if it\n * is not yet stale.\n */\n forceRefresh?: boolean\n /**\n * Context provided to the {@link OptionsBase.fetchMethod} as\n * the {@link FetcherOptions.context} param.\n *\n * If the FC type is specified as unknown (the default),\n * undefined or void, then this is optional. Otherwise, it will\n * be required.\n */\n context?: FC\n signal?: AbortSignal\n status?: Status<V>\n }\n /**\n * Options provided to {@link LRUCache#fetch} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface FetchOptionsWithContext<K, V, FC>\n extends FetchOptions<K, V, FC> {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#fetch} when the FC type is\n * `undefined` or `void`\n */\n export interface FetchOptionsNoContext<K, V>\n extends FetchOptions<K, V, undefined> {\n context?: undefined\n }\n\n export interface MemoOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n | 'noDeleteOnFetchRejection'\n | 'allowStaleOnFetchRejection'\n | 'ignoreFetchAbort'\n | 'allowStaleOnFetchAbort'\n > {\n /**\n * Set to true to force a re-load of the existing data, even if it\n * is not yet stale.\n */\n forceRefresh?: boolean\n /**\n * Context provided to the {@link OptionsBase.memoMethod} as\n * the {@link MemoizerOptions.context} param.\n *\n * If the FC type is specified as unknown (the default),\n * undefined or void, then this is optional. Otherwise, it will\n * be required.\n */\n context?: FC\n status?: Status<V>\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is something\n * other than `unknown`, `undefined`, or `void`\n */\n export interface MemoOptionsWithContext<K, V, FC>\n extends MemoOptions<K, V, FC> {\n context: FC\n }\n /**\n * Options provided to {@link LRUCache#memo} when the FC type is\n * `undefined` or `void`\n */\n export interface MemoOptionsNoContext<K, V>\n extends MemoOptions<K, V, undefined> {\n context?: undefined\n }\n\n /**\n * Options provided to the\n * {@link OptionsBase.memoMethod} function.\n */\n export interface MemoizerOptions<K, V, FC = unknown> {\n options: MemoizerMemoOptions<K, V, FC>\n /**\n * Object provided in the {@link MemoOptions.context} option to\n * {@link LRUCache#memo}\n */\n context: FC\n }\n\n /**\n * options which override the options set in the LRUCache constructor\n * when calling {@link LRUCache#memo}.\n *\n * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n * {@link MemoOptions.forceRefresh}, and\n * {@link MemoerOptions.context}\n *\n * Any of these may be modified in the {@link OptionsBase.memoMethod}\n * function, but the {@link GetOptions} fields will of course have no\n * effect, as the {@link LRUCache#get} call already happened by the time\n * the memoMethod is called.\n */\n export interface MemoizerMemoOptions<K, V, FC = unknown>\n extends Pick<\n OptionsBase<K, V, FC>,\n | 'allowStale'\n | 'updateAgeOnGet'\n | 'noDeleteOnStaleGet'\n | 'sizeCalculation'\n | 'ttl'\n | 'noDisposeOnSet'\n | 'noUpdateTTL'\n > {\n status?: Status<V>\n size?: Size\n start?: Milliseconds\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#has} method.\n */\n export interface HasOptions<K, V, FC>\n extends Pick<OptionsBase<K, V, FC>, 'updateAgeOnHas'> {\n status?: Status<V>\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#get} method.\n */\n export interface GetOptions<K, V, FC>\n extends Pick<\n OptionsBase<K, V, FC>,\n 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n > {\n status?: Status<V>\n }\n\n /**\n * Options that may be passed to the {@link LRUCache#peek} method.\n */\n export interface PeekOptions<K, V, FC>\n extends Pick<OptionsBase<K, V, FC>, 'allowStale'> {}\n\n /**\n * Options that may be passed to the {@link LRUCache#set} method.\n */\n export interface SetOptions<K, V, FC>\n extends Pick<\n OptionsBase<K, V, FC>,\n 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n > {\n /**\n * If size tracking is enabled, then setting an explicit size\n * in the {@link LRUCache#set} call will prevent calling the\n * {@link OptionsBase.sizeCalculation} function.\n */\n size?: Size\n /**\n * If TTL tracking is enabled, then setting an explicit start\n * time in the {@link LRUCache#set} call will override the\n * default time from `performance.now()` or `Date.now()`.\n *\n * Note that it must be a valid value for whichever time-tracking\n * method is in use.\n */\n start?: Milliseconds\n status?: Status<V>\n }\n\n /**\n * The type signature for the {@link OptionsBase.fetchMethod} option.\n */\n export type Fetcher<K, V, FC = unknown> = (\n key: K,\n staleValue: V | undefined,\n options: FetcherOptions<K, V, FC>\n ) => Promise<V | undefined | void> | V | undefined | void\n\n /**\n * the type signature for the {@link OptionsBase.memoMethod} option.\n */\n export type Memoizer<K, V, FC = unknown> = (\n key: K,\n staleValue: V | undefined,\n options: MemoizerOptions<K, V, FC>\n ) => V\n\n /**\n * Options which may be passed to the {@link LRUCache} constructor.\n *\n * Most of these may be overridden in the various options that use\n * them.\n *\n * Despite all being technically optional, the constructor requires that\n * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n *\n * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n * (and in fact required by the type definitions here) that the cache\n * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n * unbounded storage.\n *\n * All options are also available on the {@link LRUCache} instance, making\n * it safe to pass an LRUCache instance as the options argumemnt to\n * make another empty cache of the same type.\n *\n * Some options are marked as read-only, because changing them after\n * instantiation is not safe. Changing any of the other options will of\n * course only have an effect on subsequent method calls.\n */\n export interface OptionsBase<K, V, FC> {\n /**\n * The maximum number of items to store in the cache before evicting\n * old entries. This is read-only on the {@link LRUCache} instance,\n * and may not be overridden.\n *\n * If set, then storage space will be pre-allocated at construction\n * time, and the cache will perform significantly faster.\n *\n * Note that significantly fewer items may be stored, if\n * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n * set.\n *\n * **It is strongly recommended to set a `max` to prevent unbounded growth\n * of the cache.**\n */\n max?: Count\n\n /**\n * Max time in milliseconds for items to live in cache before they are\n * considered stale. Note that stale items are NOT preemptively removed by\n * default, and MAY live in the cache, contributing to its LRU max, long\n * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n * set.\n *\n * If set to `0` (the default value), then that means \"do not track\n * TTL\", not \"expire immediately\".\n *\n * Also, as this cache is optimized for LRU/MRU operations, some of\n * the staleness/TTL checks will reduce performance, as they will incur\n * overhead by deleting items.\n *\n * This is not primarily a TTL cache, and does not make strong TTL\n * guarantees. There is no pre-emptive pruning of expired items, but you\n * _may_ set a TTL on the cache, and it will treat expired items as missing\n * when they are fetched, and delete them.\n *\n * Optional, but must be a non-negative integer in ms if specified.\n *\n * This may be overridden by passing an options object to `cache.set()`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if ttl tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n * and `ttlAutopurge` is not set, then a warning will be emitted\n * cautioning about the potential for unbounded memory consumption.\n * (The TypeScript definitions will also discourage this.)\n */\n ttl?: Milliseconds\n\n /**\n * Minimum amount of time in ms in which to check for staleness.\n * Defaults to 1, which means that the current time is checked\n * at most once per millisecond.\n *\n * Set to 0 to check the current time every time staleness is tested.\n * (This reduces performance, and is theoretically unnecessary.)\n *\n * Setting this to a higher value will improve performance somewhat\n * while using ttl tracking, albeit at the expense of keeping stale\n * items around a bit longer than their TTLs would indicate.\n *\n * @default 1\n */\n ttlResolution?: Milliseconds\n\n /**\n * Preemptively remove stale items from the cache.\n *\n * Note that this may *significantly* degrade performance, especially if\n * the cache is storing a large number of items. It is almost always best\n * to just leave the stale items in the cache, and let them fall out as new\n * items are added.\n *\n * Note that this means that {@link OptionsBase.allowStale} is a bit\n * pointless, as stale items will be deleted almost as soon as they\n * expire.\n *\n * Use with caution!\n */\n ttlAutopurge?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever it is retrieved from cache with\n * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n * of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n */\n updateAgeOnGet?: boolean\n\n /**\n * When using time-expiring entries with `ttl`, setting this to `true` will\n * make each item's age reset to 0 whenever its presence in the cache is\n * checked with {@link LRUCache#has}, causing it to not expire. (It can\n * still fall out of cache based on recency of use, of course.)\n *\n * Has no effect if {@link OptionsBase.ttl} is not set.\n */\n updateAgeOnHas?: boolean\n\n /**\n * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n * stale data, if available.\n *\n * By default, if you set `ttl`, stale items will only be deleted from the\n * cache when you `get(key)`. That is, it's not preemptively pruning items,\n * unless {@link OptionsBase.ttlAutopurge} is set.\n *\n * If you set `allowStale:true`, it'll return the stale value *as well as*\n * deleting it. If you don't set this, then it'll return `undefined` when\n * you try to get a stale entry.\n *\n * Note that when a stale entry is fetched, _even if it is returned due to\n * `allowStale` being set_, it is removed from the cache immediately. You\n * can suppress this behavior by setting\n * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n * the options provided to {@link LRUCache#get}.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n * The `cache.has()` method will always return `false` for stale items.\n *\n * Only relevant if a ttl is set.\n */\n allowStale?: boolean\n\n /**\n * Function that is called on items when they are dropped from the\n * cache, as `dispose(value, key, reason)`.\n *\n * This can be handy if you want to close file descriptors or do\n * other cleanup tasks when items are no longer stored in the cache.\n *\n * **NOTE**: It is called _before_ the item has been fully removed\n * from the cache, so if you want to put it right back in, you need\n * to wait until the next tick. If you try to add it back in during\n * the `dispose()` function call, it will break things in subtle and\n * weird ways.\n *\n * Unlike several other options, this may _not_ be overridden by\n * passing an option to `set()`, for performance reasons.\n *\n * The `reason` will be one of the following strings, corresponding\n * to the reason for the item's deletion:\n *\n * - `evict` Item was evicted to make space for a new addition\n * - `set` Item was overwritten by a new value\n * - `expire` Item expired its TTL\n * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n * fetchMethod returning `undefined.\n * - `delete` Item was removed by explicit `cache.delete(key)`,\n * `cache.clear()`, or `cache.set(key, undefined)`.\n */\n dispose?: Disposer<K, V>\n\n /**\n * The same as {@link OptionsBase.dispose}, but called *after* the entry\n * is completely removed and the cache is once again in a clean state.\n *\n * It is safe to add an item right back into the cache at this point.\n * However, note that it is *very* easy to inadvertently create infinite\n * recursion this way.\n */\n disposeAfter?: Disposer<K, V>\n\n /**\n * Set to true to suppress calling the\n * {@link OptionsBase.dispose} function if the entry key is\n * still accessible within the cache.\n *\n * This may be overridden by passing an options object to\n * {@link LRUCache#set}.\n *\n * Only relevant if `dispose` or `disposeAfter` are set.\n */\n noDisposeOnSet?: boolean\n\n /**\n * Boolean flag to tell the cache to not update the TTL when setting a new\n * value for an existing key (ie, when updating a value rather than\n * inserting a new value). Note that the TTL value is _always_ set (if\n * provided) when adding a new entry into the cache.\n *\n * Has no effect if a {@link OptionsBase.ttl} is not set.\n *\n * May be passed as an option to {@link LRUCache#set}.\n */\n noUpdateTTL?: boolean\n\n /**\n * Set to a positive integer to track the sizes of items added to the\n * cache, and automatically evict items in order to stay below this size.\n * Note that this may result in fewer than `max` items being stored.\n *\n * Attempting to add an item to the cache whose calculated size is greater\n * that this amount will be a no-op. The item will not be cached, and no\n * other items will be evicted.\n *\n * Optional, must be a positive integer if provided.\n *\n * Sets `maxEntrySize` to the same value, unless a different value is\n * provided for `maxEntrySize`.\n *\n * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n * positive integer if set.\n *\n * Even if size tracking is enabled, **it is strongly recommended to set a\n * `max` to prevent unbounded growth of the cache.**\n *\n * Note also that size tracking can negatively impact performance,\n * though for most cases, only minimally.\n */\n maxSize?: Size\n\n /**\n * The maximum allowed size for any single item in the cache.\n *\n * If a larger item is passed to {@link LRUCache#set} or returned by a\n * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then\n * it will not be stored in the cache.\n *\n * Attempting to add an item whose calculated size is greater than\n * this amount will not cache the item or evict any old items, but\n * WILL delete an existing value if one is already present.\n *\n * Optional, must be a positive integer if provided. Defaults to\n * the value of `maxSize` if provided.\n */\n maxEntrySize?: Size\n\n /**\n * A function that returns a number indicating the item's size.\n *\n * Requires {@link OptionsBase.maxSize} to be set.\n *\n * If not provided, and {@link OptionsBase.maxSize} or\n * {@link OptionsBase.maxEntrySize} are set, then all\n * {@link LRUCache#set} calls **must** provide an explicit\n * {@link SetOptions.size} or sizeCalculation param.\n */\n sizeCalculation?: SizeCalculator<K, V>\n\n /**\n * Method that provides the implementation for {@link LRUCache#fetch}\n *\n * ```ts\n * fetchMethod(key, staleValue, { signal, options, context })\n * ```\n *\n * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n * to `Promise.resolve(cache.get(key))`.\n *\n * If at any time, `signal.aborted` is set to `true`, or if the\n * `signal.onabort` method is called, or if it emits an `'abort'` event\n * which you can listen to with `addEventListener`, then that means that\n * the fetch should be abandoned. This may be passed along to async\n * functions aware of AbortController/AbortSignal behavior.\n *\n * The `fetchMethod` should **only** return `undefined` or a Promise\n * resolving to `undefined` if the AbortController signaled an `abort`\n * event. In all other cases, it should return or resolve to a value\n * suitable for adding to the cache.\n *\n * The `options` object is a union of the options that may be provided to\n * `set()` and `get()`. If they are modified, then that will result in\n * modifying the settings to `cache.set()` when the value is resolved, and\n * in the case of\n * {@link OptionsBase.noDeleteOnFetchRejection} and\n * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n * `fetchMethod` failures.\n *\n * For example, a DNS cache may update the TTL based on the value returned\n * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n */\n fetchMethod?: Fetcher<K, V, FC>\n\n /**\n * Method that provides the implementation for {@link LRUCache#memo}\n */\n memoMethod?: Memoizer<K, V, FC>\n\n /**\n * Set to true to suppress the deletion of stale data when a\n * {@link OptionsBase.fetchMethod} returns a rejected promise.\n */\n noDeleteOnFetchRejection?: boolean\n\n /**\n * Do not delete stale items when they are retrieved with\n * {@link LRUCache#get}.\n *\n * Note that the `get` return value will still be `undefined`\n * unless {@link OptionsBase.allowStale} is true.\n *\n * When using time-expiring entries with `ttl`, by default stale\n * items will be removed from the cache when the key is accessed\n * with `cache.get()`.\n *\n * Setting this option will cause stale items to remain in the cache, until\n * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n * `noDeleteOnStaleGet` set to `false`.\n *\n * This may be overridden by passing an options object to `cache.get()`.\n *\n * Only relevant if a ttl is used.\n */\n noDeleteOnStaleGet?: boolean\n\n /**\n * Set to true to allow returning stale data when a\n * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n * promise.\n *\n * This differs from using {@link OptionsBase.allowStale} in that stale\n * data will ONLY be returned in the case that the {@link LRUCache#fetch}\n * fails, not any other times.\n *\n * If a `fetchMethod` fails, and there is no stale value available, the\n * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n * suppressed.\n *\n * Implies `noDeleteOnFetchRejection`.\n *\n * This may be set in calls to `fetch()`, or defaulted on the constructor,\n * or overridden by modifying the options object in the `fetchMethod`.\n */\n allowStaleOnFetchRejection?: boolean\n\n /**\n * Set to true to return a stale value from the cache when the\n * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches\n * an `'abort'` event, whether user-triggered, or due to internal cache\n * behavior.\n *\n * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n * any value it returns will be ignored and not cached.\n *\n * Caveat: since fetches are aborted when a new value is explicitly\n * set in the cache, this can lead to fetch returning a stale value,\n * since that was the fallback value _at the moment the `fetch()` was\n * initiated_, even though the new updated value is now present in\n * the cache.\n *\n * For example:\n *\n * ```ts\n * const cache = new LRUCache<string, any>({\n * ttl: 100,\n * fetchMethod: async (url, oldValue, { signal }) => {\n * const res = await fetch(url, { signal })\n * return await res.json()\n * }\n * })\n * cache.set('https://example.com/', { some: 'data' })\n * // 100ms go by...\n * const result = cache.fetch('https://example.com/')\n * cache.set('https://example.com/', { other: 'thing' })\n * console.log(await result) // { some: 'data' }\n * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n * ```\n */\n allowStaleOnFetchAbort?: boolean\n\n /**\n * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n * resulting resolution value, as long as it is not `undefined`.\n *\n * When used on its own, this means aborted {@link LRUCache#fetch} calls\n * are not immediately resolved or rejected when they are aborted, and\n * instead take the full time to await.\n *\n * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n * {@link LRUCache#fetch} calls will resolve immediately to their stale\n * cached value or `undefined`, and will continue to process and eventually\n * update the cache when they resolve, as long as the resulting value is\n * not `undefined`, thus supporting a \"return stale on timeout while\n * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n *\n * For example:\n *\n * ```ts\n * const c = new LRUCache({\n * ttl: 100,\n * ignoreFetchAbort: true,\n * allowStaleOnFetchAbort: true,\n * fetchMethod: async (key, oldValue, { signal }) => {\n * // note: do NOT pass the signal to fetch()!\n * // let's say this fetch can take a long time.\n * const res = await fetch(`https://slow-backend-server/${key}`)\n * return await res.json()\n * },\n * })\n *\n * // this will return the stale value after 100ms, while still\n * // updating in the background for next time.\n * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n * ```\n *\n * **Note**: regardless of this setting, an `abort` event _is still\n * emitted on the `AbortSignal` object_, so may result in invalid results\n * when passed to other underlying APIs that use AbortSignals.\n *\n * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n * call to {@link LRUCache#fetch}.\n */\n ignoreFetchAbort?: boolean\n }\n\n export interface OptionsMaxLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n max: Count\n }\n export interface OptionsTTLLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n ttl: Milliseconds\n ttlAutopurge: boolean\n }\n export interface OptionsSizeLimit<K, V, FC>\n extends OptionsBase<K, V, FC> {\n maxSize: Size\n }\n\n /**\n * The valid safe options for the {@link LRUCache} constructor\n */\n export type Options<K, V, FC> =\n | OptionsMaxLimit<K, V, FC>\n | OptionsSizeLimit<K, V, FC>\n | OptionsTTLLimit<K, V, FC>\n\n /**\n * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n * and returned by {@link LRUCache#info}.\n */\n export interface Entry<V> {\n value: V\n ttl?: Milliseconds\n size?: Size\n start?: Milliseconds\n }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache<K extends {}, V extends {}, FC = unknown>\n implements Map<K, V>\n{\n // options that cannot be changed without disaster\n readonly #max: LRUCache.Count\n readonly #maxSize: LRUCache.Size\n readonly #dispose?: LRUCache.Disposer<K, V>\n readonly #disposeAfter?: LRUCache.Disposer<K, V>\n readonly #fetchMethod?: LRUCache.Fetcher<K, V, FC>\n readonly #memoMethod?: LRUCache.Memoizer<K, V, FC>\n\n /**\n * {@link LRUCache.OptionsBase.ttl}\n */\n ttl: LRUCache.Milliseconds\n\n /**\n * {@link LRUCache.OptionsBase.ttlResolution}\n */\n ttlResolution: LRUCache.Milliseconds\n /**\n * {@link LRUCache.OptionsBase.ttlAutopurge}\n */\n ttlAutopurge: boolean\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnGet}\n */\n updateAgeOnGet: boolean\n /**\n * {@link LRUCache.OptionsBase.updateAgeOnHas}\n */\n updateAgeOnHas: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStale}\n */\n allowStale: boolean\n\n /**\n * {@link LRUCache.OptionsBase.noDisposeOnSet}\n */\n noDisposeOnSet: boolean\n /**\n * {@link LRUCache.OptionsBase.noUpdateTTL}\n */\n noUpdateTTL: boolean\n /**\n * {@link LRUCache.OptionsBase.maxEntrySize}\n */\n maxEntrySize: LRUCache.Size\n /**\n * {@link LRUCache.OptionsBase.sizeCalculation}\n */\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n */\n noDeleteOnFetchRejection: boolean\n /**\n * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n */\n noDeleteOnStaleGet: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n */\n allowStaleOnFetchAbort: boolean\n /**\n * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n */\n allowStaleOnFetchRejection: boolean\n /**\n * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n */\n ignoreFetchAbort: boolean\n\n // computed properties\n #size: LRUCache.Count\n #calculatedSize: LRUCache.Size\n #keyMap: Map<K, Index>\n #keyList: (K | undefined)[]\n #valList: (V | BackgroundFetch<V> | undefined)[]\n #next: NumberArray\n #prev: NumberArray\n #head: Index\n #tail: Index\n #free: StackLike\n #disposed?: DisposeTask<K, V>[]\n #sizes?: ZeroArray\n #starts?: ZeroArray\n #ttls?: ZeroArray\n\n #hasDispose: boolean\n #hasFetchMethod: boolean\n #hasDisposeAfter: boolean\n\n /**\n * Do not call this method unless you need to inspect the\n * inner workings of the cache. If anything returned by this\n * object is modified in any way, strange breakage may occur.\n *\n * These fields are private for a reason!\n *\n * @internal\n */\n static unsafeExposeInternals<\n K extends {},\n V extends {},\n FC extends unknown = unknown\n >(c: LRUCache<K, V, FC>) {\n return {\n // properties\n starts: c.#starts,\n ttls: c.#ttls,\n sizes: c.#sizes,\n keyMap: c.#keyMap as Map<K, number>,\n keyList: c.#keyList,\n valList: c.#valList,\n next: c.#next,\n prev: c.#prev,\n get head() {\n return c.#head\n },\n get tail() {\n return c.#tail\n },\n free: c.#free,\n // methods\n isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),\n backgroundFetch: (\n k: K,\n index: number | undefined,\n options: LRUCache.FetchOptions<K, V, FC>,\n context: any\n ): BackgroundFetch<V> =>\n c.#backgroundFetch(\n k,\n index as Index | undefined,\n options,\n context\n ),\n moveToTail: (index: number): void =>\n c.#moveToTail(index as Index),\n indexes: (options?: { allowStale: boolean }) =>\n c.#indexes(options),\n rindexes: (options?: { allowStale: boolean }) =>\n c.#rindexes(options),\n isStale: (index: number | undefined) =>\n c.#isStale(index as Index),\n }\n }\n\n // Protected read-only members\n\n /**\n * {@link LRUCache.OptionsBase.max} (read-only)\n */\n get max(): LRUCache.Count {\n return this.#max\n }\n /**\n * {@link LRUCache.OptionsBase.maxSize} (read-only)\n */\n get maxSize(): LRUCache.Count {\n return this.#maxSize\n }\n /**\n * The total computed size of items in the cache (read-only)\n */\n get calculatedSize(): LRUCache.Size {\n return this.#calculatedSize\n }\n /**\n * The number of items stored in the cache (read-only)\n */\n get size(): LRUCache.Count {\n return this.#size\n }\n /**\n * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n */\n get fetchMethod(): LRUCache.Fetcher<K, V, FC> | undefined {\n return this.#fetchMethod\n }\n get memoMethod(): LRUCache.Memoizer<K, V, FC> | undefined {\n return this.#memoMethod\n }\n /**\n * {@link LRUCache.OptionsBase.dispose} (read-only)\n */\n get dispose() {\n return this.#dispose\n }\n /**\n * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n */\n get disposeAfter() {\n return this.#disposeAfter\n }\n\n constructor(\n options: LRUCache.Options<K, V, FC> | LRUCache<K, V, FC>\n ) {\n const {\n max = 0,\n ttl,\n ttlResolution = 1,\n ttlAutopurge,\n updateAgeOnGet,\n updateAgeOnHas,\n allowStale,\n dispose,\n disposeAfter,\n noDisposeOnSet,\n noUpdateTTL,\n maxSize = 0,\n maxEntrySize = 0,\n sizeCalculation,\n fetchMethod,\n memoMethod,\n noDeleteOnFetchRejection,\n noDeleteOnStaleGet,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n } = options\n\n if (max !== 0 && !isPosInt(max)) {\n throw new TypeError('max option must be a nonnegative integer')\n }\n\n const UintArray = max ? getUintArray(max) : Array\n if (!UintArray) {\n throw new Error('invalid max value: ' + max)\n }\n\n this.#max = max\n this.#maxSize = maxSize\n this.maxEntrySize = maxEntrySize || this.#maxSize\n this.sizeCalculation = sizeCalculation\n if (this.sizeCalculation) {\n if (!this.#maxSize && !this.maxEntrySize) {\n throw new TypeError(\n 'cannot set sizeCalculation without setting maxSize or maxEntrySize'\n )\n }\n if (typeof this.sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation set to non-function')\n }\n }\n\n if (\n memoMethod !== undefined &&\n typeof memoMethod !== 'function'\n ) {\n throw new TypeError('memoMethod must be a function if defined')\n }\n this.#memoMethod = memoMethod\n\n if (\n fetchMethod !== undefined &&\n typeof fetchMethod !== 'function'\n ) {\n throw new TypeError(\n 'fetchMethod must be a function if specified'\n )\n }\n this.#fetchMethod = fetchMethod\n this.#hasFetchMethod = !!fetchMethod\n\n this.#keyMap = new Map()\n this.#keyList = new Array(max).fill(undefined)\n this.#valList = new Array(max).fill(undefined)\n this.#next = new UintArray(max)\n this.#prev = new UintArray(max)\n this.#head = 0 as Index\n this.#tail = 0 as Index\n this.#free = Stack.create(max)\n this.#size = 0\n this.#calculatedSize = 0\n\n if (typeof dispose === 'function') {\n this.#dispose = dispose\n }\n if (typeof disposeAfter === 'function') {\n this.#disposeAfter = disposeAfter\n this.#disposed = []\n } else {\n this.#disposeAfter = undefined\n this.#disposed = undefined\n }\n this.#hasDispose = !!this.#dispose\n this.#hasDisposeAfter = !!this.#disposeAfter\n\n this.noDisposeOnSet = !!noDisposeOnSet\n this.noUpdateTTL = !!noUpdateTTL\n this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n this.ignoreFetchAbort = !!ignoreFetchAbort\n\n // NB: maxEntrySize is set to maxSize if it's set\n if (this.maxEntrySize !== 0) {\n if (this.#maxSize !== 0) {\n if (!isPosInt(this.#maxSize)) {\n throw new TypeError(\n 'maxSize must be a positive integer if specified'\n )\n }\n }\n if (!isPosInt(this.maxEntrySize)) {\n throw new TypeError(\n 'maxEntrySize must be a positive integer if specified'\n )\n }\n this.#initializeSizeTracking()\n }\n\n this.allowStale = !!allowStale\n this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n this.updateAgeOnGet = !!updateAgeOnGet\n this.updateAgeOnHas = !!updateAgeOnHas\n this.ttlResolution =\n isPosInt(ttlResolution) || ttlResolution === 0\n ? ttlResolution\n : 1\n this.ttlAutopurge = !!ttlAutopurge\n this.ttl = ttl || 0\n if (this.ttl) {\n if (!isPosInt(this.ttl)) {\n throw new TypeError(\n 'ttl must be a positive integer if specified'\n )\n }\n this.#initializeTTLTracking()\n }\n\n // do not allow completely unbounded caches\n if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n throw new TypeError(\n 'At least one of max, maxSize, or ttl is required'\n )\n }\n if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n const code = 'LRU_CACHE_UNBOUNDED'\n if (shouldWarn(code)) {\n warned.add(code)\n const msg =\n 'TTL caching without ttlAutopurge, max, or maxSize can ' +\n 'result in unbounded memory consumption.'\n emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n }\n }\n }\n\n /**\n * Return the number of ms left in the item's TTL. If item is not in cache,\n * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n */\n getRemainingTTL(key: K) {\n return this.#keyMap.has(key) ? Infinity : 0\n }\n\n #initializeTTLTracking() {\n const ttls = new ZeroArray(this.#max)\n const starts = new ZeroArray(this.#max)\n this.#ttls = ttls\n this.#starts = starts\n\n this.#setItemTTL = (index, ttl, start = perf.now()) => {\n starts[index] = ttl !== 0 ? start : 0\n ttls[index] = ttl\n if (ttl !== 0 && this.ttlAutopurge) {\n const t = setTimeout(() => {\n if (this.#isStale(index)) {\n this.#delete(this.#keyList[index] as K, 'expire')\n }\n }, ttl + 1)\n // unref() not supported on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref()\n }\n /* c8 ignore stop */\n }\n }\n\n this.#updateItemAge = index => {\n starts[index] = ttls[index] !== 0 ? perf.now() : 0\n }\n\n this.#statusTTL = (status, index) => {\n if (ttls[index]) {\n const ttl = ttls[index]\n const start = starts[index]\n /* c8 ignore next */\n if (!ttl || !start) return\n status.ttl = ttl\n status.start = start\n status.now = cachedNow || getNow()\n const age = status.now - start\n status.remainingTTL = ttl - age\n }\n }\n\n // debounce calls to perf.now() to 1s so we're not hitting\n // that costly call repeatedly.\n let cachedNow = 0\n const getNow = () => {\n const n = perf.now()\n if (this.ttlResolution > 0) {\n cachedNow = n\n const t = setTimeout(\n () => (cachedNow = 0),\n this.ttlResolution\n )\n // not available on all platforms\n /* c8 ignore start */\n if (t.unref) {\n t.unref()\n }\n /* c8 ignore stop */\n }\n return n\n }\n\n this.getRemainingTTL = key => {\n const index = this.#keyMap.get(key)\n if (index === undefined) {\n return 0\n }\n const ttl = ttls[index]\n const start = starts[index]\n if (!ttl || !start) {\n return Infinity\n }\n const age = (cachedNow || getNow()) - start\n return ttl - age\n }\n\n this.#isStale = index => {\n const s = starts[index]\n const t = ttls[index]\n return !!t && !!s && (cachedNow || getNow()) - s > t\n }\n }\n\n // conditionally set private methods related to TTL\n #updateItemAge: (index: Index) => void = () => {}\n #statusTTL: (status: LRUCache.Status<V>, index: Index) => void =\n () => {}\n #setItemTTL: (\n index: Index,\n ttl: LRUCache.Milliseconds,\n start?: LRUCache.Milliseconds\n // ignore because we never call this if we're not already in TTL mode\n /* c8 ignore start */\n ) => void = () => {}\n /* c8 ignore stop */\n\n #isStale: (index: Index) => boolean = () => false\n\n #initializeSizeTracking() {\n const sizes = new ZeroArray(this.#max)\n this.#calculatedSize = 0\n this.#sizes = sizes\n this.#removeItemSize = index => {\n this.#calculatedSize -= sizes[index] as number\n sizes[index] = 0\n }\n this.#requireSize = (k, v, size, sizeCalculation) => {\n // provisionally accept background fetches.\n // actual value size will be checked when they return.\n if (this.#isBackgroundFetch(v)) {\n return 0\n }\n if (!isPosInt(size)) {\n if (sizeCalculation) {\n if (typeof sizeCalculation !== 'function') {\n throw new TypeError('sizeCalculation must be a function')\n }\n size = sizeCalculation(v, k)\n if (!isPosInt(size)) {\n throw new TypeError(\n 'sizeCalculation return invalid (expect positive integer)'\n )\n }\n } else {\n throw new TypeError(\n 'invalid size value (must be positive integer). ' +\n 'When maxSize or maxEntrySize is used, sizeCalculation ' +\n 'or size must be set.'\n )\n }\n }\n return size\n }\n this.#addItemSize = (\n index: Index,\n size: LRUCache.Size,\n status?: LRUCache.Status<V>\n ) => {\n sizes[index] = size\n if (this.#maxSize) {\n const maxSize = this.#maxSize - (sizes[index] as number)\n while (this.#calculatedSize > maxSize) {\n this.#evict(true)\n }\n }\n this.#calculatedSize += sizes[index] as number\n if (status) {\n status.entrySize = size\n status.totalCalculatedSize = this.#calculatedSize\n }\n }\n }\n\n #removeItemSize: (index: Index) => void = _i => {}\n #addItemSize: (\n index: Index,\n size: LRUCache.Size,\n status?: LRUCache.Status<V>\n ) => void = (_i, _s, _st) => {}\n #requireSize: (\n k: K,\n v: V | BackgroundFetch<V>,\n size?: LRUCache.Size,\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n ) => LRUCache.Size = (\n _k: K,\n _v: V | BackgroundFetch<V>,\n size?: LRUCache.Size,\n sizeCalculation?: LRUCache.SizeCalculator<K, V>\n ) => {\n if (size || sizeCalculation) {\n throw new TypeError(\n 'cannot set size without setting maxSize or maxEntrySize on cache'\n )\n }\n return 0\n };\n\n *#indexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#tail; true; ) {\n if (!this.#isValidIndex(i)) {\n break\n }\n if (allowStale || !this.#isStale(i)) {\n yield i\n }\n if (i === this.#head) {\n break\n } else {\n i = this.#prev[i] as Index\n }\n }\n }\n }\n\n *#rindexes({ allowStale = this.allowStale } = {}) {\n if (this.#size) {\n for (let i = this.#head; true; ) {\n if (!this.#isValidIndex(i)) {\n break\n }\n if (allowStale || !this.#isStale(i)) {\n yield i\n }\n if (i === this.#tail) {\n break\n } else {\n i = this.#next[i] as Index\n }\n }\n }\n }\n\n #isValidIndex(index: Index) {\n return (\n index !== undefined &&\n this.#keyMap.get(this.#keyList[index] as K) === index\n )\n }\n\n /**\n * Return a generator yielding `[key, value]` pairs,\n * in order from most recently used to least recently used.\n */\n *entries() {\n for (const i of this.#indexes()) {\n if (\n this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield [this.#keyList[i], this.#valList[i]] as [K, V]\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.entries}\n *\n * Return a generator yielding `[key, value]` pairs,\n * in order from least recently used to most recently used.\n */\n *rentries() {\n for (const i of this.#rindexes()) {\n if (\n this.#valList[i] !== undefined &&\n this.#keyList[i] !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield [this.#keyList[i], this.#valList[i]]\n }\n }\n }\n\n /**\n * Return a generator yielding the keys in the cache,\n * in order from most recently used to least recently used.\n */\n *keys() {\n for (const i of this.#indexes()) {\n const k = this.#keyList[i]\n if (\n k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield k\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.keys}\n *\n * Return a generator yielding the keys in the cache,\n * in order from least recently used to most recently used.\n */\n *rkeys() {\n for (const i of this.#rindexes()) {\n const k = this.#keyList[i]\n if (\n k !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield k\n }\n }\n }\n\n /**\n * Return a generator yielding the values in the cache,\n * in order from most recently used to least recently used.\n */\n *values() {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n if (\n v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield this.#valList[i] as V\n }\n }\n }\n\n /**\n * Inverse order version of {@link LRUCache.values}\n *\n * Return a generator yielding the values in the cache,\n * in order from least recently used to most recently used.\n */\n *rvalues() {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i]\n if (\n v !== undefined &&\n !this.#isBackgroundFetch(this.#valList[i])\n ) {\n yield this.#valList[i]\n }\n }\n }\n\n /**\n * Iterating over the cache itself yields the same results as\n * {@link LRUCache.entries}\n */\n [Symbol.iterator]() {\n return this.entries()\n }\n\n /**\n * A String value that is used in the creation of the default string\n * description of an object. Called by the built-in method\n * `Object.prototype.toString`.\n */\n [Symbol.toStringTag] = 'LRUCache'\n\n /**\n * Find a value for which the supplied fn method returns a truthy value,\n * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n */\n find(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => boolean,\n getOptions: LRUCache.GetOptions<K, V, FC> = {}\n ) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n if (fn(value, this.#keyList[i] as K, this)) {\n return this.get(this.#keyList[i] as K, getOptions)\n }\n }\n }\n\n /**\n * Call the supplied function on each item in the cache, in order from most\n * recently used to least recently used.\n *\n * `fn` is called as `fn(value, key, cache)`.\n *\n * If `thisp` is provided, function will be called in the `this`-context of\n * the provided object, or the cache if no `thisp` object is provided.\n *\n * Does not update age or recenty of use, or iterate over stale values.\n */\n forEach(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any,\n thisp: any = this\n ) {\n for (const i of this.#indexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n fn.call(thisp, value, this.#keyList[i] as K, this)\n }\n }\n\n /**\n * The same as {@link LRUCache.forEach} but items are iterated over in\n * reverse order. (ie, less recently used items are iterated over first.)\n */\n rforEach(\n fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any,\n thisp: any = this\n ) {\n for (const i of this.#rindexes()) {\n const v = this.#valList[i]\n const value = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) continue\n fn.call(thisp, value, this.#keyList[i] as K, this)\n }\n }\n\n /**\n * Delete any stale entries. Returns true if anything was removed,\n * false otherwise.\n */\n purgeStale() {\n let deleted = false\n for (const i of this.#rindexes({ allowStale: true })) {\n if (this.#isStale(i)) {\n this.#delete(this.#keyList[i] as K, 'expire')\n deleted = true\n }\n }\n return deleted\n }\n\n /**\n * Get the extended info about a given entry, to get its value, size, and\n * TTL info simultaneously. Returns `undefined` if the key is not present.\n *\n * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n * serialization, the `start` value is always the current timestamp, and the\n * `ttl` is a calculated remaining time to live (negative if expired).\n *\n * Always returns stale values, if their info is found in the cache, so be\n * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n * if relevant.\n */\n info(key: K): LRUCache.Entry<V> | undefined {\n const i = this.#keyMap.get(key)\n if (i === undefined) return undefined\n const v = this.#valList[i]\n const value: V | undefined = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined) return undefined\n const entry: LRUCache.Entry<V> = { value }\n if (this.#ttls && this.#starts) {\n const ttl = this.#ttls[i]\n const start = this.#starts[i]\n if (ttl && start) {\n const remain = ttl - (perf.now() - start)\n entry.ttl = remain\n entry.start = Date.now()\n }\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i]\n }\n return entry\n }\n\n /**\n * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n * passed to {@link LRLUCache#load}.\n *\n * The `start` fields are calculated relative to a portable `Date.now()`\n * timestamp, even if `performance.now()` is available.\n *\n * Stale entries are always included in the `dump`, even if\n * {@link LRUCache.OptionsBase.allowStale} is false.\n *\n * Note: this returns an actual array, not a generator, so it can be more\n * easily passed around.\n */\n dump() {\n const arr: [K, LRUCache.Entry<V>][] = []\n for (const i of this.#indexes({ allowStale: true })) {\n const key = this.#keyList[i]\n const v = this.#valList[i]\n const value: V | undefined = this.#isBackgroundFetch(v)\n ? v.__staleWhileFetching\n : v\n if (value === undefined || key === undefined) continue\n const entry: LRUCache.Entry<V> = { value }\n if (this.#ttls && this.#starts) {\n entry.ttl = this.#ttls[i]\n // always dump the start relative to a portable timestamp\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = perf.now() - (this.#starts[i] as number)\n entry.start = Math.floor(Date.now() - age)\n }\n if (this.#sizes) {\n entry.size = this.#sizes[i]\n }\n arr.unshift([key, entry])\n }\n return arr\n }\n\n /**\n * Reset the cache and load in the items in entries in the order listed.\n *\n * The shape of the resulting cache may be different if the same options are\n * not used in both caches.\n *\n * The `start` fields are assumed to be calculated relative to a portable\n * `Date.now()` timestamp, even if `performance.now()` is available.\n */\n load(arr: [K, LRUCache.Entry<V>][]) {\n this.clear()\n for (const [key, entry] of arr) {\n if (entry.start) {\n // entry.start is a portable timestamp, but we may be using\n // node's performance.now(), so calculate the offset, so that\n // we get the intended remaining TTL, no matter how long it's\n // been on ice.\n //\n // it's ok for this to be a bit slow, it's a rare operation.\n const age = Date.now() - entry.start\n entry.start = perf.now() - age\n }\n this.set(key, entry.value, entry)\n }\n }\n\n /**\n * Add a value to the cache.\n *\n * Note: if `undefined` is specified as a value, this is an alias for\n * {@link LRUCache#delete}\n *\n * Fields on the {@link LRUCache.SetOptions} options param will override\n * their corresponding values in the constructor options for the scope\n * of this single `set()` operation.\n *\n * If `start` is provided, then that will set the effective start\n * time for the TTL calculation. Note that this must be a previous\n * value of `performance.now()` if supported, or a previous value of\n * `Date.now()` if not.\n *\n * Options object may also include `size`, which will prevent\n * calling the `sizeCalculation` function and just use the specified\n * number if it is a positive integer, and `noDisposeOnSet` which\n * will prevent calling a `dispose` function in the case of\n * overwrites.\n *\n * If the `size` (or return value of `sizeCalculation`) for a given\n * entry is greater than `maxEntrySize`, then the item will not be\n * added to the cache.\n *\n * Will update the recency of the entry.\n *\n * If the value is `undefined`, then this is an alias for\n * `cache.delete(key)`. `undefined` is never stored in the cache.\n */\n set(\n k: K,\n v: V | BackgroundFetch<V> | undefined,\n setOptions: LRUCache.SetOptions<K, V, FC> = {}\n ) {\n if (v === undefined) {\n this.delete(k)\n return this\n }\n const {\n ttl = this.ttl,\n start,\n noDisposeOnSet = this.noDisposeOnSet,\n sizeCalculation = this.sizeCalculation,\n status,\n } = setOptions\n let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n const size = this.#requireSize(\n k,\n v,\n setOptions.size || 0,\n sizeCalculation\n )\n // if the item doesn't fit, don't do anything\n // NB: maxEntrySize set to maxSize by default\n if (this.maxEntrySize && size > this.maxEntrySize) {\n if (status) {\n status.set = 'miss'\n status.maxEntrySizeExceeded = true\n }\n // have to delete, in case something is there already.\n this.#delete(k, 'set')\n return this\n }\n let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n if (index === undefined) {\n // addition\n index = (\n this.#size === 0\n ? this.#tail\n : this.#free.length !== 0\n ? this.#free.pop()\n : this.#size === this.#max\n ? this.#evict(false)\n : this.#size\n ) as Index\n this.#keyList[index] = k\n this.#valList[index] = v\n this.#keyMap.set(k, index)\n this.#next[this.#tail] = index\n this.#prev[index] = this.#tail\n this.#tail = index\n this.#size++\n this.#addItemSize(index, size, status)\n if (status) status.set = 'add'\n noUpdateTTL = false\n } else {\n // update\n this.#moveToTail(index)\n const oldVal = this.#valList[index] as V | BackgroundFetch<V>\n if (v !== oldVal) {\n if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n oldVal.__abortController.abort(new Error('replaced'))\n const { __staleWhileFetching: s } = oldVal\n if (s !== undefined && !noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(s as V, k, 'set')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([s as V, k, 'set'])\n }\n }\n } else if (!noDisposeOnSet) {\n if (this.#hasDispose) {\n this.#dispose?.(oldVal as V, k, 'set')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([oldVal as V, k, 'set'])\n }\n }\n this.#removeItemSize(index)\n this.#addItemSize(index, size, status)\n this.#valList[index] = v\n if (status) {\n status.set = 'replace'\n const oldValue =\n oldVal && this.#isBackgroundFetch(oldVal)\n ? oldVal.__staleWhileFetching\n : oldVal\n if (oldValue !== undefined) status.oldValue = oldValue\n }\n } else if (status) {\n status.set = 'update'\n }\n }\n if (ttl !== 0 && !this.#ttls) {\n this.#initializeTTLTracking()\n }\n if (this.#ttls) {\n if (!noUpdateTTL) {\n this.#setItemTTL(index, ttl, start)\n }\n if (status) this.#statusTTL(status, index)\n }\n if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n return this\n }\n\n /**\n * Evict the least recently used item, returning its value or\n * `undefined` if cache is empty.\n */\n pop(): V | undefined {\n try {\n while (this.#size) {\n const val = this.#valList[this.#head]\n this.#evict(true)\n if (this.#isBackgroundFetch(val)) {\n if (val.__staleWhileFetching) {\n return val.__staleWhileFetching\n }\n } else if (val !== undefined) {\n return val\n }\n }\n } finally {\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n }\n }\n\n #evict(free: boolean) {\n const head = this.#head\n const k = this.#keyList[head] as K\n const v = this.#valList[head] as V\n if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('evicted'))\n } else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v, k, 'evict')\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v, k, 'evict'])\n }\n }\n this.#removeItemSize(head)\n // if we aren't about to use the index, then null these out\n if (free) {\n this.#keyList[head] = undefined\n this.#valList[head] = undefined\n this.#free.push(head)\n }\n if (this.#size === 1) {\n this.#head = this.#tail = 0 as Index\n this.#free.length = 0\n } else {\n this.#head = this.#next[head] as Index\n }\n this.#keyMap.delete(k)\n this.#size--\n return head\n }\n\n /**\n * Check if a key is in the cache, without updating the recency of use.\n * Will return false if the item is stale, even though it is technically\n * in the cache.\n *\n * Check if a key is in the cache, without updating the recency of\n * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n * to `true` in either the options or the constructor.\n *\n * Will return `false` if the item is stale, even though it is technically in\n * the cache. The difference can be determined (if it matters) by using a\n * `status` argument, and inspecting the `has` field.\n *\n * Will not update item age unless\n * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n */\n has(k: K, hasOptions: LRUCache.HasOptions<K, V, FC> = {}) {\n const { updateAgeOnHas = this.updateAgeOnHas, status } =\n hasOptions\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n const v = this.#valList[index]\n if (\n this.#isBackgroundFetch(v) &&\n v.__staleWhileFetching === undefined\n ) {\n return false\n }\n if (!this.#isStale(index)) {\n if (updateAgeOnHas) {\n this.#updateItemAge(index)\n }\n if (status) {\n status.has = 'hit'\n this.#statusTTL(status, index)\n }\n return true\n } else if (status) {\n status.has = 'stale'\n this.#statusTTL(status, index)\n }\n } else if (status) {\n status.has = 'miss'\n }\n return false\n }\n\n /**\n * Like {@link LRUCache#get} but doesn't update recency or delete stale\n * items.\n *\n * Returns `undefined` if the item is stale, unless\n * {@link LRUCache.OptionsBase.allowStale} is set.\n */\n peek(k: K, peekOptions: LRUCache.PeekOptions<K, V, FC> = {}) {\n const { allowStale = this.allowStale } = peekOptions\n const index = this.#keyMap.get(k)\n if (\n index === undefined ||\n (!allowStale && this.#isStale(index))\n ) {\n return\n }\n const v = this.#valList[index]\n // either stale and allowed, or forcing a refresh of non-stale value\n return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n }\n\n #backgroundFetch(\n k: K,\n index: Index | undefined,\n options: LRUCache.FetchOptions<K, V, FC>,\n context: any\n ): BackgroundFetch<V> {\n const v = index === undefined ? undefined : this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n return v\n }\n\n const ac = new AC()\n const { signal } = options\n // when/if our AC signals, then stop listening to theirs.\n signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n signal: ac.signal,\n })\n\n const fetchOpts = {\n signal: ac.signal,\n options,\n context,\n }\n\n const cb = (\n v: V | undefined,\n updateCache = false\n ): V | undefined => {\n const { aborted } = ac.signal\n const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n if (options.status) {\n if (aborted && !updateCache) {\n options.status.fetchAborted = true\n options.status.fetchError = ac.signal.reason\n if (ignoreAbort) options.status.fetchAbortIgnored = true\n } else {\n options.status.fetchResolved = true\n }\n }\n if (aborted && !ignoreAbort && !updateCache) {\n return fetchFail(ac.signal.reason)\n }\n // either we didn't abort, and are still here, or we did, and ignored\n const bf = p as BackgroundFetch<V>\n if (this.#valList[index as Index] === p) {\n if (v === undefined) {\n if (bf.__staleWhileFetching) {\n this.#valList[index as Index] = bf.__staleWhileFetching\n } else {\n this.#delete(k, 'fetch')\n }\n } else {\n if (options.status) options.status.fetchUpdated = true\n this.set(k, v, fetchOpts.options)\n }\n }\n return v\n }\n\n const eb = (er: any) => {\n if (options.status) {\n options.status.fetchRejected = true\n options.status.fetchError = er\n }\n return fetchFail(er)\n }\n\n const fetchFail = (er: any): V | undefined => {\n const { aborted } = ac.signal\n const allowStaleAborted =\n aborted && options.allowStaleOnFetchAbort\n const allowStale =\n allowStaleAborted || options.allowStaleOnFetchRejection\n const noDelete = allowStale || options.noDeleteOnFetchRejection\n const bf = p as BackgroundFetch<V>\n if (this.#valList[index as Index] === p) {\n // if we allow stale on fetch rejections, then we need to ensure that\n // the stale value is not removed from the cache when the fetch fails.\n const del = !noDelete || bf.__staleWhileFetching === undefined\n if (del) {\n this.#delete(k, 'fetch')\n } else if (!allowStaleAborted) {\n // still replace the *promise* with the stale value,\n // since we are done with the promise at this point.\n // leave it untouched if we're still waiting for an\n // aborted background fetch that hasn't yet returned.\n this.#valList[index as Index] = bf.__staleWhileFetching\n }\n }\n if (allowStale) {\n if (options.status && bf.__staleWhileFetching !== undefined) {\n options.status.returnedStale = true\n }\n return bf.__staleWhileFetching\n } else if (bf.__returned === bf) {\n throw er\n }\n }\n\n const pcall = (\n res: (v: V | undefined) => void,\n rej: (e: any) => void\n ) => {\n const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n if (fmp && fmp instanceof Promise) {\n fmp.then(v => res(v === undefined ? undefined : v), rej)\n }\n // ignored, we go until we finish, regardless.\n // defer check until we are actually aborting,\n // so fetchMethod can override.\n ac.signal.addEventListener('abort', () => {\n if (\n !options.ignoreFetchAbort ||\n options.allowStaleOnFetchAbort\n ) {\n res(undefined)\n // when it eventually resolves, update the cache.\n if (options.allowStaleOnFetchAbort) {\n res = v => cb(v, true)\n }\n }\n })\n }\n\n if (options.status) options.status.fetchDispatched = true\n const p = new Promise(pcall).then(cb, eb)\n const bf: BackgroundFetch<V> = Object.assign(p, {\n __abortController: ac,\n __staleWhileFetching: v,\n __returned: undefined,\n })\n\n if (index === undefined) {\n // internal, don't expose status.\n this.set(k, bf, { ...fetchOpts.options, status: undefined })\n index = this.#keyMap.get(k)\n } else {\n this.#valList[index] = bf\n }\n return bf\n }\n\n #isBackgroundFetch(p: any): p is BackgroundFetch<V> {\n if (!this.#hasFetchMethod) return false\n const b = p as BackgroundFetch<V>\n return (\n !!b &&\n b instanceof Promise &&\n b.hasOwnProperty('__staleWhileFetching') &&\n b.__abortController instanceof AC\n )\n }\n\n /**\n * Make an asynchronous cached fetch using the\n * {@link LRUCache.OptionsBase.fetchMethod} function.\n *\n * If the value is in the cache and not stale, then the returned\n * Promise resolves to the value.\n *\n * If not in the cache, or beyond its TTL staleness, then\n * `fetchMethod(key, staleValue, { options, signal, context })` is\n * called, and the value returned will be added to the cache once\n * resolved.\n *\n * If called with `allowStale`, and an asynchronous fetch is\n * currently in progress to reload a stale value, then the former\n * stale value will be returned.\n *\n * If called with `forceRefresh`, then the cached item will be\n * re-fetched, even if it is not stale. However, if `allowStale` is also\n * set, then the old value will still be returned. This is useful\n * in cases where you want to force a reload of a cached value. If\n * a background fetch is already in progress, then `forceRefresh`\n * has no effect.\n *\n * If multiple fetches for the same key are issued, then they will all be\n * coalesced into a single call to fetchMethod.\n *\n * Note that this means that handling options such as\n * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n * {@link LRUCache.FetchOptions.signal},\n * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n * determined by the FIRST fetch() call for a given key.\n *\n * This is a known (fixable) shortcoming which will be addresed on when\n * someone complains about it, as the fix would involve added complexity and\n * may not be worth the costs for this edge case.\n *\n * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n * effectively an alias for `Promise.resolve(cache.get(key))`.\n *\n * When the fetch method resolves to a value, if the fetch has not\n * been aborted due to deletion, eviction, or being overwritten,\n * then it is added to the cache using the options provided.\n *\n * If the key is evicted or deleted before the `fetchMethod`\n * resolves, then the AbortSignal passed to the `fetchMethod` will\n * receive an `abort` event, and the promise returned by `fetch()`\n * will reject with the reason for the abort.\n *\n * If a `signal` is passed to the `fetch()` call, then aborting the\n * signal will abort the fetch and cause the `fetch()` promise to\n * reject with the reason provided.\n *\n * **Setting `context`**\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the {@link LRUCache} constructor, then all\n * calls to `cache.fetch()` _must_ provide a `context` option. If\n * set to `undefined` or `void`, then calls to fetch _must not_\n * provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that\n * might be relevant in the course of fetching the data. It is only\n * relevant for the course of a single `fetch()` operation, and\n * discarded afterwards.\n *\n * **Note: `fetch()` calls are inflight-unique**\n *\n * If you call `fetch()` multiple times with the same key value,\n * then every call after the first will resolve on the same\n * promise<sup>1</sup>,\n * _even if they have different settings that would otherwise change\n * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n * or `ignoreFetchAbort`.\n *\n * In most cases, this is not a problem (in fact, only fetching\n * something once is what you probably want, if you're caching in\n * the first place). If you are changing the fetch() options\n * dramatically between runs, there's a good chance that you might\n * be trying to fit divergent semantics into a single object, and\n * would be better off with multiple cache instances.\n *\n * **1**: Ie, they're not the \"same Promise\", but they resolve at\n * the same time, because they're both waiting on the same\n * underlying fetchMethod response.\n */\n\n fetch(\n k: K,\n fetchOptions: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n ): Promise<undefined | V>\n\n // this overload not allowed if context is required\n fetch(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n fetchOptions?: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : never\n ): Promise<undefined | V>\n\n async fetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions<K, V, FC> = {}\n ): Promise<undefined | V> {\n const {\n // get options\n allowStale = this.allowStale,\n updateAgeOnGet = this.updateAgeOnGet,\n noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n // set options\n ttl = this.ttl,\n noDisposeOnSet = this.noDisposeOnSet,\n size = 0,\n sizeCalculation = this.sizeCalculation,\n noUpdateTTL = this.noUpdateTTL,\n // fetch exclusive options\n noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n ignoreFetchAbort = this.ignoreFetchAbort,\n allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n context,\n forceRefresh = false,\n status,\n signal,\n } = fetchOptions\n\n if (!this.#hasFetchMethod) {\n if (status) status.fetch = 'get'\n return this.get(k, {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n status,\n })\n }\n\n const options = {\n allowStale,\n updateAgeOnGet,\n noDeleteOnStaleGet,\n ttl,\n noDisposeOnSet,\n size,\n sizeCalculation,\n noUpdateTTL,\n noDeleteOnFetchRejection,\n allowStaleOnFetchRejection,\n allowStaleOnFetchAbort,\n ignoreFetchAbort,\n status,\n signal,\n }\n\n let index = this.#keyMap.get(k)\n if (index === undefined) {\n if (status) status.fetch = 'miss'\n const p = this.#backgroundFetch(k, index, options, context)\n return (p.__returned = p)\n } else {\n // in cache, maybe already fetching\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n const stale =\n allowStale && v.__staleWhileFetching !== undefined\n if (status) {\n status.fetch = 'inflight'\n if (stale) status.returnedStale = true\n }\n return stale ? v.__staleWhileFetching : (v.__returned = v)\n }\n\n // if we force a refresh, that means do NOT serve the cached value,\n // unless we are already in the process of refreshing the cache.\n const isStale = this.#isStale(index)\n if (!forceRefresh && !isStale) {\n if (status) status.fetch = 'hit'\n this.#moveToTail(index)\n if (updateAgeOnGet) {\n this.#updateItemAge(index)\n }\n if (status) this.#statusTTL(status, index)\n return v\n }\n\n // ok, it is stale or a forced refresh, and not already fetching.\n // refresh the cache.\n const p = this.#backgroundFetch(k, index, options, context)\n const hasStale = p.__staleWhileFetching !== undefined\n const staleVal = hasStale && allowStale\n if (status) {\n status.fetch = isStale ? 'stale' : 'refresh'\n if (staleVal && isStale) status.returnedStale = true\n }\n return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n }\n }\n\n /**\n * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n * because `ignoreFetchAbort` was specified (either to the constructor or\n * in the {@link LRUCache.FetchOptions}). Also, the\n * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making\n * the test even more complicated.\n *\n * Because inferring the cases where `undefined` might be returned are so\n * cumbersome, but testing for `undefined` can also be annoying, this method\n * can be used, which will reject if `this.fetch()` resolves to undefined.\n */\n forceFetch(\n k: K,\n fetchOptions: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n ): Promise<V>\n // this overload not allowed if context is required\n forceFetch(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n fetchOptions?: unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : never\n ): Promise<V>\n async forceFetch(\n k: K,\n fetchOptions: LRUCache.FetchOptions<K, V, FC> = {}\n ): Promise<V> {\n const v = await this.fetch(\n k,\n fetchOptions as unknown extends FC\n ? LRUCache.FetchOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.FetchOptionsNoContext<K, V>\n : LRUCache.FetchOptionsWithContext<K, V, FC>\n )\n if (v === undefined) throw new Error('fetch() returned undefined')\n return v\n }\n\n /**\n * If the key is found in the cache, then this is equivalent to\n * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n *\n * If an `FC` type is set to a type other than `unknown`, `void`, or\n * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n * _must_ provide a `context` option. If set to `undefined` or `void`, then\n * calls to memo _must not_ provide a `context` option.\n *\n * The `context` param allows you to provide arbitrary data that might be\n * relevant in the course of fetching the data. It is only relevant for the\n * course of a single `memo()` operation, and discarded afterwards.\n */\n memo(\n k: K,\n memoOptions: unknown extends FC\n ? LRUCache.MemoOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext<K, V>\n : LRUCache.MemoOptionsWithContext<K, V, FC>\n ): V\n // this overload not allowed if context is required\n memo(\n k: unknown extends FC\n ? K\n : FC extends undefined | void\n ? K\n : never,\n memoOptions?: unknown extends FC\n ? LRUCache.MemoOptions<K, V, FC>\n : FC extends undefined | void\n ? LRUCache.MemoOptionsNoContext<K, V>\n : never\n ): V\n memo(k: K, memoOptions: LRUCache.MemoOptions<K, V, FC> = {}) {\n const memoMethod = this.#memoMethod\n if (!memoMethod) {\n throw new Error('no memoMethod provided to constructor')\n }\n const { context, forceRefresh, ...options } = memoOptions\n const v = this.get(k, options)\n if (!forceRefresh && v !== undefined) return v\n const vv = memoMethod(k, v, {\n options,\n context,\n } as LRUCache.MemoizerOptions<K, V, FC>)\n this.set(k, vv, options)\n return vv\n }\n\n /**\n * Return a value from the cache. Will update the recency of the cache\n * entry found.\n *\n * If the key is not found, get() will return `undefined`.\n */\n get(k: K, getOptions: LRUCache.GetOptions<K, V, FC> = {}) {\n const {\n allowStale = this.allowStale,\n updateAgeOnGet = this.updateAgeOnGet,\n noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n status,\n } = getOptions\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n const value = this.#valList[index]\n const fetching = this.#isBackgroundFetch(value)\n if (status) this.#statusTTL(status, index)\n if (this.#isStale(index)) {\n if (status) status.get = 'stale'\n // delete only if not an in-flight background fetch\n if (!fetching) {\n if (!noDeleteOnStaleGet) {\n this.#delete(k, 'expire')\n }\n if (status && allowStale) status.returnedStale = true\n return allowStale ? value : undefined\n } else {\n if (\n status &&\n allowStale &&\n value.__staleWhileFetching !== undefined\n ) {\n status.returnedStale = true\n }\n return allowStale ? value.__staleWhileFetching : undefined\n }\n } else {\n if (status) status.get = 'hit'\n // if we're currently fetching it, we don't actually have it yet\n // it's not stale, which means this isn't a staleWhileRefetching.\n // If it's not stale, and fetching, AND has a __staleWhileFetching\n // value, then that means the user fetched with {forceRefresh:true},\n // so it's safe to return that value.\n if (fetching) {\n return value.__staleWhileFetching\n }\n this.#moveToTail(index)\n if (updateAgeOnGet) {\n this.#updateItemAge(index)\n }\n return value\n }\n } else if (status) {\n status.get = 'miss'\n }\n }\n\n #connect(p: Index, n: Index) {\n this.#prev[n] = p\n this.#next[p] = n\n }\n\n #moveToTail(index: Index): void {\n // if tail already, nothing to do\n // if head, move head to next[index]\n // else\n // move next[prev[index]] to next[index] (head has no prev)\n // move prev[next[index]] to prev[index]\n // prev[index] = tail\n // next[tail] = index\n // tail = index\n if (index !== this.#tail) {\n if (index === this.#head) {\n this.#head = this.#next[index] as Index\n } else {\n this.#connect(\n this.#prev[index] as Index,\n this.#next[index] as Index\n )\n }\n this.#connect(this.#tail, index)\n this.#tail = index\n }\n }\n\n /**\n * Deletes a key out of the cache.\n *\n * Returns true if the key was deleted, false otherwise.\n */\n delete(k: K) {\n return this.#delete(k, 'delete')\n }\n\n #delete(k: K, reason: LRUCache.DisposeReason) {\n let deleted = false\n if (this.#size !== 0) {\n const index = this.#keyMap.get(k)\n if (index !== undefined) {\n deleted = true\n if (this.#size === 1) {\n this.#clear(reason)\n } else {\n this.#removeItemSize(index)\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'))\n } else if (this.#hasDispose || this.#hasDisposeAfter) {\n if (this.#hasDispose) {\n this.#dispose?.(v as V, k, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k, reason])\n }\n }\n this.#keyMap.delete(k)\n this.#keyList[index] = undefined\n this.#valList[index] = undefined\n if (index === this.#tail) {\n this.#tail = this.#prev[index] as Index\n } else if (index === this.#head) {\n this.#head = this.#next[index] as Index\n } else {\n const pi = this.#prev[index] as number\n this.#next[pi] = this.#next[index] as number\n const ni = this.#next[index] as number\n this.#prev[ni] = this.#prev[index] as number\n }\n this.#size--\n this.#free.push(index)\n }\n }\n }\n if (this.#hasDisposeAfter && this.#disposed?.length) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n return deleted\n }\n\n /**\n * Clear the cache entirely, throwing away all values.\n */\n clear() {\n return this.#clear('delete')\n }\n #clear(reason: LRUCache.DisposeReason) {\n for (const index of this.#rindexes({ allowStale: true })) {\n const v = this.#valList[index]\n if (this.#isBackgroundFetch(v)) {\n v.__abortController.abort(new Error('deleted'))\n } else {\n const k = this.#keyList[index]\n if (this.#hasDispose) {\n this.#dispose?.(v as V, k as K, reason)\n }\n if (this.#hasDisposeAfter) {\n this.#disposed?.push([v as V, k as K, reason])\n }\n }\n }\n\n this.#keyMap.clear()\n this.#valList.fill(undefined)\n this.#keyList.fill(undefined)\n if (this.#ttls && this.#starts) {\n this.#ttls.fill(0)\n this.#starts.fill(0)\n }\n if (this.#sizes) {\n this.#sizes.fill(0)\n }\n this.#head = 0 as Index\n this.#tail = 0 as Index\n this.#free.length = 0\n this.#calculatedSize = 0\n this.#size = 0\n if (this.#hasDisposeAfter && this.#disposed) {\n const dt = this.#disposed\n let task: DisposeTask<K, V> | undefined\n while ((task = dt?.shift())) {\n this.#disposeAfter?.(...task)\n }\n }\n }\n}\n","const proc =\n typeof process === 'object' && process\n ? process\n : {\n stdout: null,\n stderr: null,\n }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n s: any\n): s is Minipass.Readable | Minipass.Writable =>\n !!s &&\n typeof s === 'object' &&\n (s instanceof Minipass ||\n s instanceof Stream ||\n isReadable(s) ||\n isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Readable).pipe === 'function' &&\n // node core Writable streams have a pipe() method, but it throws\n (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n !!s &&\n typeof s === 'object' &&\n s instanceof EventEmitter &&\n typeof (s as Minipass.Writable).write === 'function' &&\n typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n b instanceof ArrayBuffer ||\n (!!b &&\n typeof b === 'object' &&\n b.constructor &&\n b.constructor.name === 'ArrayBuffer' &&\n b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n /**\n * end the destination stream when the source stream ends\n */\n end?: boolean\n /**\n * proxy errors from the source stream to the destination stream\n */\n proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe<T extends unknown> {\n src: Minipass<T>\n dest: Minipass<any, T>\n opts: PipeOptions\n ondrain: () => any\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n this.src = src\n this.dest = dest as Minipass<any, T>\n this.opts = opts\n this.ondrain = () => src[RESUME]()\n this.dest.on('drain', this.ondrain)\n }\n unpipe() {\n this.dest.removeListener('drain', this.ondrain)\n }\n // only here for the prototype\n /* c8 ignore start */\n proxyErrors(_er: any) {}\n /* c8 ignore stop */\n end() {\n this.unpipe()\n if (this.opts.end) this.dest.end()\n }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors<T> extends Pipe<T> {\n unpipe() {\n this.src.removeListener('error', this.proxyErrors)\n super.unpipe()\n }\n constructor(\n src: Minipass<T>,\n dest: Minipass.Writable,\n opts: PipeOptions\n ) {\n super(src, dest, opts)\n this.proxyErrors = er => dest.emit('error', er)\n src.on('error', this.proxyErrors)\n }\n}\n\nexport namespace Minipass {\n /**\n * Encoding used to create a stream that outputs strings rather than\n * Buffer objects.\n */\n export type Encoding = BufferEncoding | 'buffer' | null\n\n /**\n * Any stream that Minipass can pipe into\n */\n export type Writable =\n | Minipass<any, any, any>\n | NodeJS.WriteStream\n | (NodeJS.WriteStream & { fd: number })\n | (EventEmitter & {\n end(): any\n write(chunk: any, ...args: any[]): any\n })\n\n /**\n * Any stream that can be read from\n */\n export type Readable =\n | Minipass<any, any, any>\n | NodeJS.ReadStream\n | (NodeJS.ReadStream & { fd: number })\n | (EventEmitter & {\n pause(): any\n resume(): any\n pipe(...destArgs: any[]): any\n })\n\n /**\n * Utility type that can be iterated sync or async\n */\n export type DualIterable<T> = Iterable<T> & AsyncIterable<T>\n\n type EventArguments = Record<string | symbol, unknown[]>\n\n /**\n * The listing of events that a Minipass class can emit.\n * Extend this when extending the Minipass class, and pass as\n * the third template argument. The key is the name of the event,\n * and the value is the argument list.\n *\n * Any undeclared events will still be allowed, but the handler will get\n * arguments as `unknown[]`.\n */\n export interface Events<RType extends any = Buffer>\n extends EventArguments {\n readable: []\n data: [chunk: RType]\n error: [er: unknown]\n abort: [reason: unknown]\n drain: []\n resume: []\n end: []\n finish: []\n prefinish: []\n close: []\n [DESTROYED]: [er?: unknown]\n [ERROR]: [er: unknown]\n }\n\n /**\n * String or buffer-like data that can be joined and sliced\n */\n export type ContiguousData =\n | Buffer\n | ArrayBufferLike\n | ArrayBufferView\n | string\n export type BufferOrString = Buffer | string\n\n /**\n * Options passed to the Minipass constructor.\n */\n export type SharedOptions = {\n /**\n * Defer all data emission and other events until the end of the\n * current tick, similar to Node core streams\n */\n async?: boolean\n /**\n * A signal which will abort the stream\n */\n signal?: AbortSignal\n /**\n * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n * emit Buffer objects rather than strings.\n *\n * Conflicts with `objectMode`\n */\n encoding?: BufferEncoding | null | 'buffer'\n /**\n * Output data exactly as it was written, supporting non-buffer/string\n * data (such as arbitrary objects, falsey values, etc.)\n *\n * Conflicts with `encoding`\n */\n objectMode?: boolean\n }\n\n /**\n * Options for a string encoded output\n */\n export type EncodingOptions = SharedOptions & {\n encoding: BufferEncoding\n objectMode?: false\n }\n\n /**\n * Options for contiguous data buffer output\n */\n export type BufferOptions = SharedOptions & {\n encoding?: null | 'buffer'\n objectMode?: false\n }\n\n /**\n * Options for objectMode arbitrary output\n */\n export type ObjectModeOptions = SharedOptions & {\n objectMode: true\n encoding?: null\n }\n\n /**\n * Utility type to determine allowed options based on read type\n */\n export type Options<T> =\n | ObjectModeOptions\n | (T extends string\n ? EncodingOptions\n : T extends Buffer\n ? BufferOptions\n : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n RType extends unknown = Buffer,\n WType extends unknown = RType extends Minipass.BufferOrString\n ? Minipass.ContiguousData\n : RType,\n Events extends Minipass.Events<RType> = Minipass.Events<RType>\n >\n extends EventEmitter\n implements Minipass.DualIterable<RType>\n{\n [FLOWING]: boolean = false;\n [PAUSED]: boolean = false;\n [PIPES]: Pipe<RType>[] = [];\n [BUFFER]: RType[] = [];\n [OBJECTMODE]: boolean;\n [ENCODING]: BufferEncoding | null;\n [ASYNC]: boolean;\n [DECODER]: SD | null;\n [EOF]: boolean = false;\n [EMITTED_END]: boolean = false;\n [EMITTING_END]: boolean = false;\n [CLOSED]: boolean = false;\n [EMITTED_ERROR]: unknown = null;\n [BUFFERLENGTH]: number = 0;\n [DESTROYED]: boolean = false;\n [SIGNAL]?: AbortSignal;\n [ABORTED]: boolean = false;\n [DATALISTENERS]: number = 0;\n [DISCARDED]: boolean = false\n\n /**\n * true if the stream can be written\n */\n writable: boolean = true\n /**\n * true if the stream can be read\n */\n readable: boolean = true\n\n /**\n * If `RType` is Buffer, then options do not need to be provided.\n * Otherwise, an options object must be provided to specify either\n * {@link Minipass.SharedOptions.objectMode} or\n * {@link Minipass.SharedOptions.encoding}, as appropriate.\n */\n constructor(\n ...args:\n | [Minipass.ObjectModeOptions]\n | (RType extends Buffer\n ? [] | [Minipass.Options<RType>]\n : [Minipass.Options<RType>])\n ) {\n const options: Minipass.Options<RType> = (args[0] ||\n {}) as Minipass.Options<RType>\n super()\n if (options.objectMode && typeof options.encoding === 'string') {\n throw new TypeError(\n 'Encoding and objectMode may not be used together'\n )\n }\n if (isObjectModeOptions(options)) {\n this[OBJECTMODE] = true\n this[ENCODING] = null\n } else if (isEncodingOptions(options)) {\n this[ENCODING] = options.encoding\n this[OBJECTMODE] = false\n } else {\n this[OBJECTMODE] = false\n this[ENCODING] = null\n }\n this[ASYNC] = !!options.async\n this[DECODER] = this[ENCODING]\n ? (new StringDecoder(this[ENCODING]) as SD)\n : null\n\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposeBuffer === true) {\n Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n }\n //@ts-ignore - private option for debugging and testing\n if (options && options.debugExposePipes === true) {\n Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n }\n\n const { signal } = options\n if (signal) {\n this[SIGNAL] = signal\n if (signal.aborted) {\n this[ABORT]()\n } else {\n signal.addEventListener('abort', () => this[ABORT]())\n }\n }\n }\n\n /**\n * The amount of data stored in the buffer waiting to be read.\n *\n * For Buffer strings, this will be the total byte length.\n * For string encoding streams, this will be the string character length,\n * according to JavaScript's `string.length` logic.\n * For objectMode streams, this is a count of the items waiting to be\n * emitted.\n */\n get bufferLength() {\n return this[BUFFERLENGTH]\n }\n\n /**\n * The `BufferEncoding` currently in use, or `null`\n */\n get encoding() {\n return this[ENCODING]\n }\n\n /**\n * @deprecated - This is a read only property\n */\n set encoding(_enc) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * @deprecated - Encoding may only be set at instantiation time\n */\n setEncoding(_enc: Minipass.Encoding) {\n throw new Error('Encoding must be set at instantiation time')\n }\n\n /**\n * True if this is an objectMode stream\n */\n get objectMode() {\n return this[OBJECTMODE]\n }\n\n /**\n * @deprecated - This is a read-only property\n */\n set objectMode(_om) {\n throw new Error('objectMode must be set at instantiation time')\n }\n\n /**\n * true if this is an async stream\n */\n get ['async'](): boolean {\n return this[ASYNC]\n }\n /**\n * Set to true to make this stream async.\n *\n * Once set, it cannot be unset, as this would potentially cause incorrect\n * behavior. Ie, a sync stream can be made async, but an async stream\n * cannot be safely made sync.\n */\n set ['async'](a: boolean) {\n this[ASYNC] = this[ASYNC] || !!a\n }\n\n // drop everything and get out of the flow completely\n [ABORT]() {\n this[ABORTED] = true\n this.emit('abort', this[SIGNAL]?.reason)\n this.destroy(this[SIGNAL]?.reason)\n }\n\n /**\n * True if the stream has been aborted.\n */\n get aborted() {\n return this[ABORTED]\n }\n /**\n * No-op setter. Stream aborted status is set via the AbortSignal provided\n * in the constructor options.\n */\n set aborted(_) {}\n\n /**\n * Write data into the stream\n *\n * If the chunk written is a string, and encoding is not specified, then\n * `utf8` will be assumed. If the stream encoding matches the encoding of\n * a written string, and the state of the string decoder allows it, then\n * the string will be passed through to either the output or the internal\n * buffer without any processing. Otherwise, it will be turned into a\n * Buffer object for processing into the desired encoding.\n *\n * If provided, `cb` function is called immediately before return for\n * sync streams, or on next tick for async streams, because for this\n * base class, a chunk is considered \"processed\" once it is accepted\n * and either emitted or buffered. That is, the callback does not indicate\n * that the chunk has been eventually emitted, though of course child\n * classes can override this function to do whatever processing is required\n * and call `super.write(...)` only once processing is completed.\n */\n write(chunk: WType, cb?: () => void): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding,\n cb?: () => void\n ): boolean\n write(\n chunk: WType,\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): boolean {\n if (this[ABORTED]) return false\n if (this[EOF]) throw new Error('write after end')\n\n if (this[DESTROYED]) {\n this.emit(\n 'error',\n Object.assign(\n new Error('Cannot call write after a stream was destroyed'),\n { code: 'ERR_STREAM_DESTROYED' }\n )\n )\n return true\n }\n\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n\n if (!encoding) encoding = 'utf8'\n\n const fn = this[ASYNC] ? defer : nodefer\n\n // convert array buffers and typed array views into buffers\n // at some point in the future, we may want to do the opposite!\n // leave strings and buffers as-is\n // anything is only allowed if in object mode, so throw\n if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n if (isArrayBufferView(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(\n chunk.buffer,\n chunk.byteOffset,\n chunk.byteLength\n )\n } else if (isArrayBufferLike(chunk)) {\n //@ts-ignore - sinful unsafe type changing\n chunk = Buffer.from(chunk)\n } else if (typeof chunk !== 'string') {\n throw new Error(\n 'Non-contiguous data written to non-objectMode stream'\n )\n }\n }\n\n // handle object mode up front, since it's simpler\n // this yields better performance, fewer checks later.\n if (this[OBJECTMODE]) {\n // maybe impossible?\n /* c8 ignore start */\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n /* c8 ignore stop */\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n // at this point the chunk is a buffer or string\n // don't buffer it up or send it to the decoder\n if (!(chunk as Minipass.BufferOrString).length) {\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n if (cb) fn(cb)\n return this[FLOWING]\n }\n\n // fast-path writing strings of same encoding to a stream with\n // an empty buffer, skipping the buffer/decoder dance\n if (\n typeof chunk === 'string' &&\n // unless it is a string already ready for us to use\n !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n ) {\n //@ts-ignore - sinful unsafe type change\n chunk = Buffer.from(chunk, encoding)\n }\n\n if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n //@ts-ignore - sinful unsafe type change\n chunk = this[DECODER].write(chunk)\n }\n\n // Note: flushing CAN potentially switch us into not-flowing mode\n if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n else this[BUFFERPUSH](chunk as unknown as RType)\n\n if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n if (cb) fn(cb)\n\n return this[FLOWING]\n }\n\n /**\n * Low-level explicit read method.\n *\n * In objectMode, the argument is ignored, and one item is returned if\n * available.\n *\n * `n` is the number of bytes (or in the case of encoding streams,\n * characters) to consume. If `n` is not provided, then the entire buffer\n * is returned, or `null` is returned if no data is available.\n *\n * If `n` is greater that the amount of data in the internal buffer,\n * then `null` is returned.\n */\n read(n?: number | null): RType | null {\n if (this[DESTROYED]) return null\n this[DISCARDED] = false\n\n if (\n this[BUFFERLENGTH] === 0 ||\n n === 0 ||\n (n && n > this[BUFFERLENGTH])\n ) {\n this[MAYBE_EMIT_END]()\n return null\n }\n\n if (this[OBJECTMODE]) n = null\n\n if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n // not object mode, so if we have an encoding, then RType is string\n // otherwise, must be Buffer\n this[BUFFER] = [\n (this[ENCODING]\n ? this[BUFFER].join('')\n : Buffer.concat(\n this[BUFFER] as Buffer[],\n this[BUFFERLENGTH]\n )) as RType,\n ]\n }\n\n const ret = this[READ](n || null, this[BUFFER][0] as RType)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [READ](n: number | null, chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n else {\n const c = chunk as Minipass.BufferOrString\n if (n === c.length || n === null) this[BUFFERSHIFT]()\n else if (typeof c === 'string') {\n this[BUFFER][0] = c.slice(n) as RType\n chunk = c.slice(0, n) as RType\n this[BUFFERLENGTH] -= n\n } else {\n this[BUFFER][0] = c.subarray(n) as RType\n chunk = c.subarray(0, n) as RType\n this[BUFFERLENGTH] -= n\n }\n }\n\n this.emit('data', chunk)\n\n if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n return chunk\n }\n\n /**\n * End the stream, optionally providing a final write.\n *\n * See {@link Minipass#write} for argument descriptions\n */\n end(cb?: () => void): this\n end(chunk: WType, cb?: () => void): this\n end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n end(\n chunk?: WType | (() => void),\n encoding?: Minipass.Encoding | (() => void),\n cb?: () => void\n ): this {\n if (typeof chunk === 'function') {\n cb = chunk as () => void\n chunk = undefined\n }\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = 'utf8'\n }\n if (chunk !== undefined) this.write(chunk, encoding)\n if (cb) this.once('end', cb)\n this[EOF] = true\n this.writable = false\n\n // if we haven't written anything, then go ahead and emit,\n // even if we're not reading.\n // we'll re-emit if a new 'end' listener is added anyway.\n // This makes MP more suitable to write-only use cases.\n if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n return this\n }\n\n // don't let the internal resume be overwritten\n [RESUME]() {\n if (this[DESTROYED]) return\n\n if (!this[DATALISTENERS] && !this[PIPES].length) {\n this[DISCARDED] = true\n }\n this[PAUSED] = false\n this[FLOWING] = true\n this.emit('resume')\n if (this[BUFFER].length) this[FLUSH]()\n else if (this[EOF]) this[MAYBE_EMIT_END]()\n else this.emit('drain')\n }\n\n /**\n * Resume the stream if it is currently in a paused state\n *\n * If called when there are no pipe destinations or `data` event listeners,\n * this will place the stream in a \"discarded\" state, where all data will\n * be thrown away. The discarded state is removed if a pipe destination or\n * data handler is added, if pause() is called, or if any synchronous or\n * asynchronous iteration is started.\n */\n resume() {\n return this[RESUME]()\n }\n\n /**\n * Pause the stream\n */\n pause() {\n this[FLOWING] = false\n this[PAUSED] = true\n this[DISCARDED] = false\n }\n\n /**\n * true if the stream has been forcibly destroyed\n */\n get destroyed() {\n return this[DESTROYED]\n }\n\n /**\n * true if the stream is currently in a flowing state, meaning that\n * any writes will be immediately emitted.\n */\n get flowing() {\n return this[FLOWING]\n }\n\n /**\n * true if the stream is currently in a paused state\n */\n get paused() {\n return this[PAUSED]\n }\n\n [BUFFERPUSH](chunk: RType) {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n this[BUFFER].push(chunk)\n }\n\n [BUFFERSHIFT](): RType {\n if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n else\n this[BUFFERLENGTH] -= (\n this[BUFFER][0] as Minipass.BufferOrString\n ).length\n return this[BUFFER].shift() as RType\n }\n\n [FLUSH](noDrain: boolean = false) {\n do {} while (\n this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n this[BUFFER].length\n )\n\n if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n }\n\n [FLUSHCHUNK](chunk: RType) {\n this.emit('data', chunk)\n return this[FLOWING]\n }\n\n /**\n * Pipe all data emitted by this stream into the destination provided.\n *\n * Triggers the flow of data.\n */\n pipe<W extends Minipass.Writable>(dest: W, opts?: PipeOptions): W {\n if (this[DESTROYED]) return dest\n this[DISCARDED] = false\n\n const ended = this[EMITTED_END]\n opts = opts || {}\n if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n else opts.end = opts.end !== false\n opts.proxyErrors = !!opts.proxyErrors\n\n // piping an ended stream ends immediately\n if (ended) {\n if (opts.end) dest.end()\n } else {\n // \"as\" here just ignores the WType, which pipes don't care about,\n // since they're only consuming from us, and writing to the dest\n this[PIPES].push(\n !opts.proxyErrors\n ? new Pipe<RType>(this as Minipass<RType>, dest, opts)\n : new PipeProxyErrors<RType>(this as Minipass<RType>, dest, opts)\n )\n if (this[ASYNC]) defer(() => this[RESUME]())\n else this[RESUME]()\n }\n\n return dest\n }\n\n /**\n * Fully unhook a piped destination stream.\n *\n * If the destination stream was the only consumer of this stream (ie,\n * there are no other piped destinations or `'data'` event listeners)\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n unpipe<W extends Minipass.Writable>(dest: W) {\n const p = this[PIPES].find(p => p.dest === dest)\n if (p) {\n if (this[PIPES].length === 1) {\n if (this[FLOWING] && this[DATALISTENERS] === 0) {\n this[FLOWING] = false\n }\n this[PIPES] = []\n } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n p.unpipe()\n }\n }\n\n /**\n * Alias for {@link Minipass#on}\n */\n addListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n return this.on(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.on`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * - Adding a 'data' event handler will trigger the flow of data\n *\n * - Adding a 'readable' event handler when there is data waiting to be read\n * will cause 'readable' to be emitted immediately.\n *\n * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n * already passed will cause the event to be emitted immediately and all\n * handlers removed.\n *\n * - Adding an 'error' event handler after an error has been emitted will\n * cause the event to be re-emitted immediately with the error previously\n * raised.\n */\n on<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ): this {\n const ret = super.on(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n if (ev === 'data') {\n this[DISCARDED] = false\n this[DATALISTENERS]++\n if (!this[PIPES].length && !this[FLOWING]) {\n this[RESUME]()\n }\n } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n super.emit('readable')\n } else if (isEndish(ev) && this[EMITTED_END]) {\n super.emit(ev)\n this.removeAllListeners(ev)\n } else if (ev === 'error' && this[EMITTED_ERROR]) {\n const h = handler as (...a: Events['error']) => any\n if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n else h.call(this, this[EMITTED_ERROR])\n }\n return ret\n }\n\n /**\n * Alias for {@link Minipass#off}\n */\n removeListener<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n return this.off(ev, handler)\n }\n\n /**\n * Mostly identical to `EventEmitter.off`\n *\n * If a 'data' event handler is removed, and it was the last consumer\n * (ie, there are no pipe destinations or other 'data' event listeners),\n * then the flow of data will stop until there is another consumer or\n * {@link Minipass#resume} is explicitly called.\n */\n off<Event extends keyof Events>(\n ev: Event,\n handler: (...args: Events[Event]) => any\n ) {\n const ret = super.off(\n ev as string | symbol,\n handler as (...a: any[]) => any\n )\n // if we previously had listeners, and now we don't, and we don't\n // have any pipes, then stop the flow, unless it's been explicitly\n // put in a discarded flowing state via stream.resume().\n if (ev === 'data') {\n this[DATALISTENERS] = this.listeners('data').length\n if (\n this[DATALISTENERS] === 0 &&\n !this[DISCARDED] &&\n !this[PIPES].length\n ) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * Mostly identical to `EventEmitter.removeAllListeners`\n *\n * If all 'data' event handlers are removed, and they were the last consumer\n * (ie, there are no pipe destinations), then the flow of data will stop\n * until there is another consumer or {@link Minipass#resume} is explicitly\n * called.\n */\n removeAllListeners<Event extends keyof Events>(ev?: Event) {\n const ret = super.removeAllListeners(ev as string | symbol | undefined)\n if (ev === 'data' || ev === undefined) {\n this[DATALISTENERS] = 0\n if (!this[DISCARDED] && !this[PIPES].length) {\n this[FLOWING] = false\n }\n }\n return ret\n }\n\n /**\n * true if the 'end' event has been emitted\n */\n get emittedEnd() {\n return this[EMITTED_END]\n }\n\n [MAYBE_EMIT_END]() {\n if (\n !this[EMITTING_END] &&\n !this[EMITTED_END] &&\n !this[DESTROYED] &&\n this[BUFFER].length === 0 &&\n this[EOF]\n ) {\n this[EMITTING_END] = true\n this.emit('end')\n this.emit('prefinish')\n this.emit('finish')\n if (this[CLOSED]) this.emit('close')\n this[EMITTING_END] = false\n }\n }\n\n /**\n * Mostly identical to `EventEmitter.emit`, with the following\n * behavior differences to prevent data loss and unnecessary hangs:\n *\n * If the stream has been destroyed, and the event is something other\n * than 'close' or 'error', then `false` is returned and no handlers\n * are called.\n *\n * If the event is 'end', and has already been emitted, then the event\n * is ignored. If the stream is in a paused or non-flowing state, then\n * the event will be deferred until data flow resumes. If the stream is\n * async, then handlers will be called on the next tick rather than\n * immediately.\n *\n * If the event is 'close', and 'end' has not yet been emitted, then\n * the event will be deferred until after 'end' is emitted.\n *\n * If the event is 'error', and an AbortSignal was provided for the stream,\n * and there are no listeners, then the event is ignored, matching the\n * behavior of node core streams in the presense of an AbortSignal.\n *\n * If the event is 'finish' or 'prefinish', then all listeners will be\n * removed after emitting the event, to prevent double-firing.\n */\n emit<Event extends keyof Events>(\n ev: Event,\n ...args: Events[Event]\n ): boolean {\n const data = args[0]\n // error and close are only events allowed after calling destroy()\n if (\n ev !== 'error' &&\n ev !== 'close' &&\n ev !== DESTROYED &&\n this[DESTROYED]\n ) {\n return false\n } else if (ev === 'data') {\n return !this[OBJECTMODE] && !data\n ? false\n : this[ASYNC]\n ? (defer(() => this[EMITDATA](data as RType)), true)\n : this[EMITDATA](data as RType)\n } else if (ev === 'end') {\n return this[EMITEND]()\n } else if (ev === 'close') {\n this[CLOSED] = true\n // don't emit close before 'end' and 'finish'\n if (!this[EMITTED_END] && !this[DESTROYED]) return false\n const ret = super.emit('close')\n this.removeAllListeners('close')\n return ret\n } else if (ev === 'error') {\n this[EMITTED_ERROR] = data\n super.emit(ERROR, data)\n const ret =\n !this[SIGNAL] || this.listeners('error').length\n ? super.emit('error', data)\n : false\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'resume') {\n const ret = super.emit('resume')\n this[MAYBE_EMIT_END]()\n return ret\n } else if (ev === 'finish' || ev === 'prefinish') {\n const ret = super.emit(ev)\n this.removeAllListeners(ev)\n return ret\n }\n\n // Some other unknown event\n const ret = super.emit(ev as string, ...args)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITDATA](data: RType) {\n for (const p of this[PIPES]) {\n if (p.dest.write(data as RType) === false) this.pause()\n }\n const ret = this[DISCARDED] ? false : super.emit('data', data)\n this[MAYBE_EMIT_END]()\n return ret\n }\n\n [EMITEND]() {\n if (this[EMITTED_END]) return false\n\n this[EMITTED_END] = true\n this.readable = false\n return this[ASYNC]\n ? (defer(() => this[EMITEND2]()), true)\n : this[EMITEND2]()\n }\n\n [EMITEND2]() {\n if (this[DECODER]) {\n const data = this[DECODER].end()\n if (data) {\n for (const p of this[PIPES]) {\n p.dest.write(data as RType)\n }\n if (!this[DISCARDED]) super.emit('data', data)\n }\n }\n\n for (const p of this[PIPES]) {\n p.end()\n }\n const ret = super.emit('end')\n this.removeAllListeners('end')\n return ret\n }\n\n /**\n * Return a Promise that resolves to an array of all emitted data once\n * the stream ends.\n */\n async collect(): Promise<RType[] & { dataLength: number }> {\n const buf: RType[] & { dataLength: number } = Object.assign([], {\n dataLength: 0,\n })\n if (!this[OBJECTMODE]) buf.dataLength = 0\n // set the promise first, in case an error is raised\n // by triggering the flow here.\n const p = this.promise()\n this.on('data', c => {\n buf.push(c)\n if (!this[OBJECTMODE])\n buf.dataLength += (c as Minipass.BufferOrString).length\n })\n await p\n return buf\n }\n\n /**\n * Return a Promise that resolves to the concatenation of all emitted data\n * once the stream ends.\n *\n * Not allowed on objectMode streams.\n */\n async concat(): Promise<RType> {\n if (this[OBJECTMODE]) {\n throw new Error('cannot concat in objectMode')\n }\n const buf = await this.collect()\n return (\n this[ENCODING]\n ? buf.join('')\n : Buffer.concat(buf as Buffer[], buf.dataLength)\n ) as RType\n }\n\n /**\n * Return a void Promise that resolves once the stream ends.\n */\n async promise(): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n this.on('error', er => reject(er))\n this.on('end', () => resolve())\n })\n }\n\n /**\n * Asynchronous `for await of` iteration.\n *\n * This will continue emitting all chunks until the stream terminates.\n */\n [Symbol.asyncIterator](): AsyncGenerator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = async (): Promise<IteratorReturnResult<void>> => {\n this.pause()\n stopped = true\n return { value: undefined, done: true }\n }\n const next = (): Promise<IteratorResult<RType, void>> => {\n if (stopped) return stop()\n const res = this.read()\n if (res !== null) return Promise.resolve({ done: false, value: res })\n\n if (this[EOF]) return stop()\n\n let resolve!: (res: IteratorResult<RType>) => void\n let reject!: (er: unknown) => void\n const onerr = (er: unknown) => {\n this.off('data', ondata)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n stop()\n reject(er)\n }\n const ondata = (value: RType) => {\n this.off('error', onerr)\n this.off('end', onend)\n this.off(DESTROYED, ondestroy)\n this.pause()\n resolve({ value, done: !!this[EOF] })\n }\n const onend = () => {\n this.off('error', onerr)\n this.off('data', ondata)\n this.off(DESTROYED, ondestroy)\n stop()\n resolve({ done: true, value: undefined })\n }\n const ondestroy = () => onerr(new Error('stream destroyed'))\n return new Promise<IteratorResult<RType>>((res, rej) => {\n reject = rej\n resolve = res\n this.once(DESTROYED, ondestroy)\n this.once('error', onerr)\n this.once('end', onend)\n this.once('data', ondata)\n })\n }\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.asyncIterator]() {\n return this\n },\n }\n }\n\n /**\n * Synchronous `for of` iteration.\n *\n * The iteration will terminate when the internal buffer runs out, even\n * if the stream has not yet terminated.\n */\n [Symbol.iterator](): Generator<RType, void, void> {\n // set this up front, in case the consumer doesn't call next()\n // right away.\n this[DISCARDED] = false\n let stopped = false\n const stop = (): IteratorReturnResult<void> => {\n this.pause()\n this.off(ERROR, stop)\n this.off(DESTROYED, stop)\n this.off('end', stop)\n stopped = true\n return { done: true, value: undefined }\n }\n\n const next = (): IteratorResult<RType, void> => {\n if (stopped) return stop()\n const value = this.read()\n return value === null ? stop() : { done: false, value }\n }\n\n this.once('end', stop)\n this.once(ERROR, stop)\n this.once(DESTROYED, stop)\n\n return {\n next,\n throw: stop,\n return: stop,\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n /**\n * Destroy a stream, preventing it from being used for any further purpose.\n *\n * If the stream has a `close()` method, then it will be called on\n * destruction.\n *\n * After destruction, any attempt to write data, read data, or emit most\n * events will be ignored.\n *\n * If an error argument is provided, then it will be emitted in an\n * 'error' event.\n */\n destroy(er?: unknown) {\n if (this[DESTROYED]) {\n if (er) this.emit('error', er)\n else this.emit(DESTROYED)\n return this\n }\n\n this[DESTROYED] = true\n this[DISCARDED] = true\n\n // throw away all buffered data, it's never coming out\n this[BUFFER].length = 0\n this[BUFFERLENGTH] = 0\n\n const wc = this as Minipass<RType, WType, Events> & {\n close?: () => void\n }\n if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n if (er) this.emit('error', er)\n // if no error to emit, still reject pending promises\n else this.emit(DESTROYED)\n\n return this\n }\n\n /**\n * Alias for {@link isStream}\n *\n * Former export location, maintained for backwards compatibility.\n *\n * @deprecated\n */\n static get isStream() {\n return isStream\n }\n}\n","import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n lstatSync,\n readdir as readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods. Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n * readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n * - lstat\n * - readdir (Dirent variant only)\n * - readlink\n * - realpath\n */\nexport interface FSOption {\n lstatSync?: (path: string) => Stats\n readdir?: (\n path: string,\n options: { withFileTypes: true },\n cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n ) => void\n readdirSync?: (\n path: string,\n options: { withFileTypes: true },\n ) => Dirent[]\n readlinkSync?: (path: string) => string\n realpathSync?: (path: string) => string\n promises?: {\n lstat?: (path: string) => Promise<Stats>\n readdir?: (\n path: string,\n options: { withFileTypes: true },\n ) => Promise<Dirent[]>\n readlink?: (path: string) => Promise<string>\n realpath?: (path: string) => Promise<string>\n [k: string]: any\n }\n [k: string]: any\n}\n\ninterface FSValue {\n lstatSync: (path: string) => Stats\n readdir: (\n path: string,\n options: { withFileTypes: true },\n cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n ) => void\n readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n readlinkSync: (path: string) => string\n realpathSync: (path: string) => string\n promises: {\n lstat: (path: string) => Promise<Stats>\n readdir: (\n path: string,\n options: { withFileTypes: true },\n ) => Promise<Dirent[]>\n readlink: (path: string) => Promise<string>\n realpath: (path: string) => Promise<string>\n [k: string]: any\n }\n [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n lstatSync,\n readdir: readdirCB,\n readdirSync,\n readlinkSync,\n realpathSync,\n promises: {\n lstat,\n readdir,\n readlink,\n realpath,\n },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n defaultFS\n : {\n ...defaultFS,\n ...fsOption,\n promises: {\n ...defaultFS.promises,\n ...(fsOption.promises || {}),\n },\n }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n | 'Unknown'\n | 'FIFO'\n | 'CharacterDevice'\n | 'Directory'\n | 'BlockDevice'\n | 'File'\n | 'SymbolicLink'\n | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n s.isFile() ? IFREG\n : s.isDirectory() ? IFDIR\n : s.isSymbolicLink() ? IFLNK\n : s.isCharacterDevice() ? IFCHR\n : s.isBlockDevice() ? IFBLK\n : s.isSocket() ? IFSOCK\n : s.isFIFO() ? IFIFO\n : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new Map<string, string>()\nconst normalize = (s: string) => {\n const c = normalizeCache.get(s)\n if (c) return c\n const n = s.normalize('NFKD')\n normalizeCache.set(s, n)\n return n\n}\n\nconst normalizeNocaseCache = new Map<string, string>()\nconst normalizeNocase = (s: string) => {\n const c = normalizeNocaseCache.get(s)\n if (c) return c\n const n = normalize(s.toLowerCase())\n normalizeNocaseCache.set(s, n)\n return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n fullpath?: string\n relative?: string\n relativePosix?: string\n parent?: PathBase\n /**\n * See {@link FSOption}\n */\n fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache<string, string> {\n constructor() {\n super({ max: 256 })\n }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent. At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache. This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache<PathBase, Children> {\n constructor(maxSize: number = 16 * 1024) {\n super({\n maxSize,\n // parent + children\n sizeCalculation: a => a.length + 1,\n })\n }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n /**\n * the basename of this path\n *\n * **Important**: *always* test the path name against any test string\n * usingthe {@link isNamed} method, and not by directly comparing this\n * string. Otherwise, unicode path strings that the system sees as identical\n * will not be properly treated as the same path, leading to incorrect\n * behavior and possible security issues.\n */\n name: string\n /**\n * the Path entry corresponding to the path root.\n *\n * @internal\n */\n root: PathBase\n /**\n * All roots found within the current PathScurry family\n *\n * @internal\n */\n roots: { [k: string]: PathBase }\n /**\n * a reference to the parent path, or undefined in the case of root entries\n *\n * @internal\n */\n parent?: PathBase\n /**\n * boolean indicating whether paths are compared case-insensitively\n * @internal\n */\n nocase: boolean\n\n /**\n * boolean indicating that this path is the current working directory\n * of the PathScurry collection that contains it.\n */\n isCWD: boolean = false\n\n /**\n * the string or regexp used to split paths. On posix, it is `'/'`, and on\n * windows it is a RegExp matching either `'/'` or `'\\\\'`\n */\n abstract splitSep: string | RegExp\n /**\n * The path separator string to use when joining paths\n */\n abstract sep: string\n\n // potential default fs override\n #fs: FSValue\n\n // Stats fields\n #dev?: number\n get dev() {\n return this.#dev\n }\n #mode?: number\n get mode() {\n return this.#mode\n }\n #nlink?: number\n get nlink() {\n return this.#nlink\n }\n #uid?: number\n get uid() {\n return this.#uid\n }\n #gid?: number\n get gid() {\n return this.#gid\n }\n #rdev?: number\n get rdev() {\n return this.#rdev\n }\n #blksize?: number\n get blksize() {\n return this.#blksize\n }\n #ino?: number\n get ino() {\n return this.#ino\n }\n #size?: number\n get size() {\n return this.#size\n }\n #blocks?: number\n get blocks() {\n return this.#blocks\n }\n #atimeMs?: number\n get atimeMs() {\n return this.#atimeMs\n }\n #mtimeMs?: number\n get mtimeMs() {\n return this.#mtimeMs\n }\n #ctimeMs?: number\n get ctimeMs() {\n return this.#ctimeMs\n }\n #birthtimeMs?: number\n get birthtimeMs() {\n return this.#birthtimeMs\n }\n #atime?: Date\n get atime() {\n return this.#atime\n }\n #mtime?: Date\n get mtime() {\n return this.#mtime\n }\n #ctime?: Date\n get ctime() {\n return this.#ctime\n }\n #birthtime?: Date\n get birthtime() {\n return this.#birthtime\n }\n\n #matchName: string\n #depth?: number\n #fullpath?: string\n #fullpathPosix?: string\n #relative?: string\n #relativePosix?: string\n #type: number\n #children: ChildrenCache\n #linkTarget?: PathBase\n #realpath?: PathBase\n\n /**\n * This property is for compatibility with the Dirent class as of\n * Node v20, where Dirent['parentPath'] refers to the path of the\n * directory that was passed to readdir. For root entries, it's the path\n * to the entry itself.\n */\n get parentPath(): string {\n return (this.parent || this).fullpath()\n }\n\n /**\n * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n * this property refers to the *parent* path, not the path object itself.\n */\n get path(): string {\n return this.parentPath\n }\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n this.name = name\n this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n this.#type = type & TYPEMASK\n this.nocase = nocase\n this.roots = roots\n this.root = root || this\n this.#children = children\n this.#fullpath = opts.fullpath\n this.#relative = opts.relative\n this.#relativePosix = opts.relativePosix\n this.parent = opts.parent\n if (this.parent) {\n this.#fs = this.parent.#fs\n } else {\n this.#fs = fsFromOption(opts.fs)\n }\n }\n\n /**\n * Returns the depth of the Path object from its root.\n *\n * For example, a path at `/foo/bar` would have a depth of 2.\n */\n depth(): number {\n if (this.#depth !== undefined) return this.#depth\n if (!this.parent) return (this.#depth = 0)\n return (this.#depth = this.parent.depth() + 1)\n }\n\n /**\n * @internal\n */\n abstract getRootString(path: string): string\n /**\n * @internal\n */\n abstract getRoot(rootPath: string): PathBase\n /**\n * @internal\n */\n abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n /**\n * @internal\n */\n childrenCache() {\n return this.#children\n }\n\n /**\n * Get the Path object referenced by the string path, resolved from this Path\n */\n resolve(path?: string): PathBase {\n if (!path) {\n return this\n }\n const rootPath = this.getRootString(path)\n const dir = path.substring(rootPath.length)\n const dirParts = dir.split(this.splitSep)\n const result: PathBase =\n rootPath ?\n this.getRoot(rootPath).#resolveParts(dirParts)\n : this.#resolveParts(dirParts)\n return result\n }\n\n #resolveParts(dirParts: string[]) {\n let p: PathBase = this\n for (const part of dirParts) {\n p = p.child(part)\n }\n return p\n }\n\n /**\n * Returns the cached children Path objects, if still available. If they\n * have fallen out of the cache, then returns an empty array, and resets the\n * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n * lookup.\n *\n * @internal\n */\n children(): Children {\n const cached = this.#children.get(this)\n if (cached) {\n return cached\n }\n const children: Children = Object.assign([], { provisional: 0 })\n this.#children.set(this, children)\n this.#type &= ~READDIR_CALLED\n return children\n }\n\n /**\n * Resolves a path portion and returns or creates the child Path.\n *\n * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n * `'..'`.\n *\n * This should not be called directly. If `pathPart` contains any path\n * separators, it will lead to unsafe undefined behavior.\n *\n * Use `Path.resolve()` instead.\n *\n * @internal\n */\n child(pathPart: string, opts?: PathOpts): PathBase {\n if (pathPart === '' || pathPart === '.') {\n return this\n }\n if (pathPart === '..') {\n return this.parent || this\n }\n\n // find the child\n const children = this.children()\n const name =\n this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n for (const p of children) {\n if (p.#matchName === name) {\n return p\n }\n }\n\n // didn't find it, create provisional child, since it might not\n // actually exist. If we know the parent isn't a dir, then\n // in fact it CAN'T exist.\n const s = this.parent ? this.sep : ''\n const fullpath =\n this.#fullpath ? this.#fullpath + s + pathPart : undefined\n const pchild = this.newChild(pathPart, UNKNOWN, {\n ...opts,\n parent: this,\n fullpath,\n })\n\n if (!this.canReaddir()) {\n pchild.#type |= ENOENT\n }\n\n // don't have to update provisional, because if we have real children,\n // then provisional is set to children.length, otherwise a lower number\n children.push(pchild)\n return pchild\n }\n\n /**\n * The relative path from the cwd. If it does not share an ancestor with\n * the cwd, then this ends up being equivalent to the fullpath()\n */\n relative(): string {\n if (this.isCWD) return ''\n if (this.#relative !== undefined) {\n return this.#relative\n }\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#relative = this.name)\n }\n const pv = p.relative()\n return pv + (!pv || !p.parent ? '' : this.sep) + name\n }\n\n /**\n * The relative path from the cwd, using / as the path separator.\n * If it does not share an ancestor with\n * the cwd, then this ends up being equivalent to the fullpathPosix()\n * On posix systems, this is identical to relative().\n */\n relativePosix(): string {\n if (this.sep === '/') return this.relative()\n if (this.isCWD) return ''\n if (this.#relativePosix !== undefined) return this.#relativePosix\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#relativePosix = this.fullpathPosix())\n }\n const pv = p.relativePosix()\n return pv + (!pv || !p.parent ? '' : '/') + name\n }\n\n /**\n * The fully resolved path string for this Path entry\n */\n fullpath(): string {\n if (this.#fullpath !== undefined) {\n return this.#fullpath\n }\n const name = this.name\n const p = this.parent\n if (!p) {\n return (this.#fullpath = this.name)\n }\n const pv = p.fullpath()\n const fp = pv + (!p.parent ? '' : this.sep) + name\n return (this.#fullpath = fp)\n }\n\n /**\n * On platforms other than windows, this is identical to fullpath.\n *\n * On windows, this is overridden to return the forward-slash form of the\n * full UNC path.\n */\n fullpathPosix(): string {\n if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n if (!this.parent) {\n const p = this.fullpath().replace(/\\\\/g, '/')\n if (/^[a-z]:\\//i.test(p)) {\n return (this.#fullpathPosix = `//?/${p}`)\n } else {\n return (this.#fullpathPosix = p)\n }\n }\n const p = this.parent\n const pfpp = p.fullpathPosix()\n const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n return (this.#fullpathPosix = fpp)\n }\n\n /**\n * Is the Path of an unknown type?\n *\n * Note that we might know *something* about it if there has been a previous\n * filesystem operation, for example that it does not exist, or is not a\n * link, or whether it has child entries.\n */\n isUnknown(): boolean {\n return (this.#type & IFMT) === UNKNOWN\n }\n\n isType(type: Type): boolean {\n return this[`is${type}`]()\n }\n\n getType(): Type {\n return (\n this.isUnknown() ? 'Unknown'\n : this.isDirectory() ? 'Directory'\n : this.isFile() ? 'File'\n : this.isSymbolicLink() ? 'SymbolicLink'\n : this.isFIFO() ? 'FIFO'\n : this.isCharacterDevice() ? 'CharacterDevice'\n : this.isBlockDevice() ? 'BlockDevice'\n : /* c8 ignore start */ this.isSocket() ? 'Socket'\n : 'Unknown'\n )\n /* c8 ignore stop */\n }\n\n /**\n * Is the Path a regular file?\n */\n isFile(): boolean {\n return (this.#type & IFMT) === IFREG\n }\n\n /**\n * Is the Path a directory?\n */\n isDirectory(): boolean {\n return (this.#type & IFMT) === IFDIR\n }\n\n /**\n * Is the path a character device?\n */\n isCharacterDevice(): boolean {\n return (this.#type & IFMT) === IFCHR\n }\n\n /**\n * Is the path a block device?\n */\n isBlockDevice(): boolean {\n return (this.#type & IFMT) === IFBLK\n }\n\n /**\n * Is the path a FIFO pipe?\n */\n isFIFO(): boolean {\n return (this.#type & IFMT) === IFIFO\n }\n\n /**\n * Is the path a socket?\n */\n isSocket(): boolean {\n return (this.#type & IFMT) === IFSOCK\n }\n\n /**\n * Is the path a symbolic link?\n */\n isSymbolicLink(): boolean {\n return (this.#type & IFLNK) === IFLNK\n }\n\n /**\n * Return the entry if it has been subject of a successful lstat, or\n * undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* simply\n * mean that we haven't called lstat on it.\n */\n lstatCached(): PathBase | undefined {\n return this.#type & LSTAT_CALLED ? this : undefined\n }\n\n /**\n * Return the cached link target if the entry has been the subject of a\n * successful readlink, or undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * readlink() has been called at some point.\n */\n readlinkCached(): PathBase | undefined {\n return this.#linkTarget\n }\n\n /**\n * Returns the cached realpath target if the entry has been the subject\n * of a successful realpath, or undefined otherwise.\n *\n * Does not read the filesystem, so an undefined result *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * realpath() has been called at some point.\n */\n realpathCached(): PathBase | undefined {\n return this.#realpath\n }\n\n /**\n * Returns the cached child Path entries array if the entry has been the\n * subject of a successful readdir(), or [] otherwise.\n *\n * Does not read the filesystem, so an empty array *could* just mean we\n * don't have any cached data. Only use it if you are very sure that a\n * readdir() has been called recently enough to still be valid.\n */\n readdirCached(): PathBase[] {\n const children = this.children()\n return children.slice(0, children.provisional)\n }\n\n /**\n * Return true if it's worth trying to readlink. Ie, we don't (yet) have\n * any indication that readlink will definitely fail.\n *\n * Returns false if the path is known to not be a symlink, if a previous\n * readlink failed, or if the entry does not exist.\n */\n canReadlink(): boolean {\n if (this.#linkTarget) return true\n if (!this.parent) return false\n // cases where it cannot possibly succeed\n const ifmt = this.#type & IFMT\n return !(\n (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n this.#type & ENOREADLINK ||\n this.#type & ENOENT\n )\n }\n\n /**\n * Return true if readdir has previously been successfully called on this\n * path, indicating that cachedReaddir() is likely valid.\n */\n calledReaddir(): boolean {\n return !!(this.#type & READDIR_CALLED)\n }\n\n /**\n * Returns true if the path is known to not exist. That is, a previous lstat\n * or readdir failed to verify its existence when that would have been\n * expected, or a parent entry was marked either enoent or enotdir.\n */\n isENOENT(): boolean {\n return !!(this.#type & ENOENT)\n }\n\n /**\n * Return true if the path is a match for the given path name. This handles\n * case sensitivity and unicode normalization.\n *\n * Note: even on case-sensitive systems, it is **not** safe to test the\n * equality of the `.name` property to determine whether a given pathname\n * matches, due to unicode normalization mismatches.\n *\n * Always use this method instead of testing the `path.name` property\n * directly.\n */\n isNamed(n: string): boolean {\n return !this.nocase ?\n this.#matchName === normalize(n)\n : this.#matchName === normalizeNocase(n)\n }\n\n /**\n * Return the Path object corresponding to the target of a symbolic link.\n *\n * If the Path is not a symbolic link, or if the readlink call fails for any\n * reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n */\n async readlink(): Promise<PathBase | undefined> {\n const target = this.#linkTarget\n if (target) {\n return target\n }\n if (!this.canReadlink()) {\n return undefined\n }\n /* c8 ignore start */\n // already covered by the canReadlink test, here for ts grumples\n if (!this.parent) {\n return undefined\n }\n /* c8 ignore stop */\n try {\n const read = await this.#fs.promises.readlink(this.fullpath())\n const linkTarget = (await this.parent.realpath())?.resolve(read)\n if (linkTarget) {\n return (this.#linkTarget = linkTarget)\n }\n } catch (er) {\n this.#readlinkFail((er as NodeJS.ErrnoException).code)\n return undefined\n }\n }\n\n /**\n * Synchronous {@link PathBase.readlink}\n */\n readlinkSync(): PathBase | undefined {\n const target = this.#linkTarget\n if (target) {\n return target\n }\n if (!this.canReadlink()) {\n return undefined\n }\n /* c8 ignore start */\n // already covered by the canReadlink test, here for ts grumples\n if (!this.parent) {\n return undefined\n }\n /* c8 ignore stop */\n try {\n const read = this.#fs.readlinkSync(this.fullpath())\n const linkTarget = this.parent.realpathSync()?.resolve(read)\n if (linkTarget) {\n return (this.#linkTarget = linkTarget)\n }\n } catch (er) {\n this.#readlinkFail((er as NodeJS.ErrnoException).code)\n return undefined\n }\n }\n\n #readdirSuccess(children: Children) {\n // succeeded, mark readdir called bit\n this.#type |= READDIR_CALLED\n // mark all remaining provisional children as ENOENT\n for (let p = children.provisional; p < children.length; p++) {\n const c = children[p]\n if (c) c.#markENOENT()\n }\n }\n\n #markENOENT() {\n // mark as UNKNOWN and ENOENT\n if (this.#type & ENOENT) return\n this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n this.#markChildrenENOENT()\n }\n\n #markChildrenENOENT() {\n // all children are provisional and do not exist\n const children = this.children()\n children.provisional = 0\n for (const p of children) {\n p.#markENOENT()\n }\n }\n\n #markENOREALPATH() {\n this.#type |= ENOREALPATH\n this.#markENOTDIR()\n }\n\n // save the information when we know the entry is not a dir\n #markENOTDIR() {\n // entry is not a directory, so any children can't exist.\n // this *should* be impossible, since any children created\n // after it's been marked ENOTDIR should be marked ENOENT,\n // so it won't even get to this point.\n /* c8 ignore start */\n if (this.#type & ENOTDIR) return\n /* c8 ignore stop */\n let t = this.#type\n // this could happen if we stat a dir, then delete it,\n // then try to read it or one of its children.\n if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n this.#type = t | ENOTDIR\n this.#markChildrenENOENT()\n }\n\n #readdirFail(code: string = '') {\n // markENOTDIR and markENOENT also set provisional=0\n if (code === 'ENOTDIR' || code === 'EPERM') {\n this.#markENOTDIR()\n } else if (code === 'ENOENT') {\n this.#markENOENT()\n } else {\n this.children().provisional = 0\n }\n }\n\n #lstatFail(code: string = '') {\n // Windows just raises ENOENT in this case, disable for win CI\n /* c8 ignore start */\n if (code === 'ENOTDIR') {\n // already know it has a parent by this point\n const p = this.parent as PathBase\n p.#markENOTDIR()\n } else if (code === 'ENOENT') {\n /* c8 ignore stop */\n this.#markENOENT()\n }\n }\n\n #readlinkFail(code: string = '') {\n let ter = this.#type\n ter |= ENOREADLINK\n if (code === 'ENOENT') ter |= ENOENT\n // windows gets a weird error when you try to readlink a file\n if (code === 'EINVAL' || code === 'UNKNOWN') {\n // exists, but not a symlink, we don't know WHAT it is, so remove\n // all IFMT bits.\n ter &= IFMT_UNKNOWN\n }\n this.#type = ter\n // windows just gets ENOENT in this case. We do cover the case,\n // just disabled because it's impossible on Windows CI\n /* c8 ignore start */\n if (code === 'ENOTDIR' && this.parent) {\n this.parent.#markENOTDIR()\n }\n /* c8 ignore stop */\n }\n\n #readdirAddChild(e: Dirent, c: Children) {\n return (\n this.#readdirMaybePromoteChild(e, c) ||\n this.#readdirAddNewChild(e, c)\n )\n }\n\n #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n // alloc new entry at head, so it's never provisional\n const type = entToType(e)\n const child = this.newChild(e.name, type, { parent: this })\n const ifmt = child.#type & IFMT\n if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n child.#type |= ENOTDIR\n }\n c.unshift(child)\n c.provisional++\n return child\n }\n\n #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n for (let p = c.provisional; p < c.length; p++) {\n const pchild = c[p]\n const name =\n this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n if (name !== pchild!.#matchName) {\n continue\n }\n\n return this.#readdirPromoteChild(e, pchild!, p, c)\n }\n }\n\n #readdirPromoteChild(\n e: Dirent,\n p: PathBase,\n index: number,\n c: Children,\n ): PathBase {\n const v = p.name\n // retain any other flags, but set ifmt from dirent\n p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n // case sensitivity fixing when we learn the true name.\n if (v !== e.name) p.name = e.name\n\n // just advance provisional index (potentially off the list),\n // otherwise we have to splice/pop it out and re-insert at head\n if (index !== c.provisional) {\n if (index === c.length - 1) c.pop()\n else c.splice(index, 1)\n c.unshift(p)\n }\n c.provisional++\n return p\n }\n\n /**\n * Call lstat() on this Path, and update all known information that can be\n * determined.\n *\n * Note that unlike `fs.lstat()`, the returned value does not contain some\n * information, such as `mode`, `dev`, `nlink`, and `ino`. If that\n * information is required, you will need to call `fs.lstat` yourself.\n *\n * If the Path refers to a nonexistent file, or if the lstat call fails for\n * any reason, `undefined` is returned. Otherwise the updated Path object is\n * returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async lstat(): Promise<PathBase | undefined> {\n if ((this.#type & ENOENT) === 0) {\n try {\n this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n return this\n } catch (er) {\n this.#lstatFail((er as NodeJS.ErrnoException).code)\n }\n }\n }\n\n /**\n * synchronous {@link PathBase.lstat}\n */\n lstatSync(): PathBase | undefined {\n if ((this.#type & ENOENT) === 0) {\n try {\n this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n return this\n } catch (er) {\n this.#lstatFail((er as NodeJS.ErrnoException).code)\n }\n }\n }\n\n #applyStat(st: Stats) {\n const {\n atime,\n atimeMs,\n birthtime,\n birthtimeMs,\n blksize,\n blocks,\n ctime,\n ctimeMs,\n dev,\n gid,\n ino,\n mode,\n mtime,\n mtimeMs,\n nlink,\n rdev,\n size,\n uid,\n } = st\n this.#atime = atime\n this.#atimeMs = atimeMs\n this.#birthtime = birthtime\n this.#birthtimeMs = birthtimeMs\n this.#blksize = blksize\n this.#blocks = blocks\n this.#ctime = ctime\n this.#ctimeMs = ctimeMs\n this.#dev = dev\n this.#gid = gid\n this.#ino = ino\n this.#mode = mode\n this.#mtime = mtime\n this.#mtimeMs = mtimeMs\n this.#nlink = nlink\n this.#rdev = rdev\n this.#size = size\n this.#uid = uid\n const ifmt = entToType(st)\n // retain any other flags, but set the ifmt\n this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n this.#type |= ENOTDIR\n }\n }\n\n #onReaddirCB: ((\n er: NodeJS.ErrnoException | null,\n entries: Path[],\n ) => any)[] = []\n #readdirCBInFlight: boolean = false\n #callOnReaddirCB(children: Path[]) {\n this.#readdirCBInFlight = false\n const cbs = this.#onReaddirCB.slice()\n this.#onReaddirCB.length = 0\n cbs.forEach(cb => cb(null, children))\n }\n\n /**\n * Standard node-style callback interface to get list of directory entries.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n *\n * @param cb The callback called with (er, entries). Note that the `er`\n * param is somewhat extraneous, as all readdir() errors are handled and\n * simply result in an empty set of entries being returned.\n * @param allowZalgo Boolean indicating that immediately known results should\n * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n * zalgo at your peril, the dark pony lord is devious and unforgiving.\n */\n readdirCB(\n cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n allowZalgo: boolean = false,\n ): void {\n if (!this.canReaddir()) {\n if (allowZalgo) cb(null, [])\n else queueMicrotask(() => cb(null, []))\n return\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n const c = children.slice(0, children.provisional)\n if (allowZalgo) cb(null, c)\n else queueMicrotask(() => cb(null, c))\n return\n }\n\n // don't have to worry about zalgo at this point.\n this.#onReaddirCB.push(cb)\n if (this.#readdirCBInFlight) {\n return\n }\n this.#readdirCBInFlight = true\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n if (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n } else {\n // if we didn't get an error, we always get entries.\n //@ts-ignore\n for (const e of entries) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n }\n this.#callOnReaddirCB(children.slice(0, children.provisional))\n return\n })\n }\n\n #asyncReaddirInFlight?: Promise<void>\n\n /**\n * Return an array of known child entries.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async readdir(): Promise<PathBase[]> {\n if (!this.canReaddir()) {\n return []\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n return children.slice(0, children.provisional)\n }\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n if (this.#asyncReaddirInFlight) {\n await this.#asyncReaddirInFlight\n } else {\n /* c8 ignore start */\n let resolve: () => void = () => {}\n /* c8 ignore stop */\n this.#asyncReaddirInFlight = new Promise<void>(\n res => (resolve = res),\n )\n try {\n for (const e of await this.#fs.promises.readdir(fullpath, {\n withFileTypes: true,\n })) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n } catch (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n }\n this.#asyncReaddirInFlight = undefined\n resolve()\n }\n return children.slice(0, children.provisional)\n }\n\n /**\n * synchronous {@link PathBase.readdir}\n */\n readdirSync(): PathBase[] {\n if (!this.canReaddir()) {\n return []\n }\n\n const children = this.children()\n if (this.calledReaddir()) {\n return children.slice(0, children.provisional)\n }\n\n // else read the directory, fill up children\n // de-provisionalize any provisional children.\n const fullpath = this.fullpath()\n try {\n for (const e of this.#fs.readdirSync(fullpath, {\n withFileTypes: true,\n })) {\n this.#readdirAddChild(e, children)\n }\n this.#readdirSuccess(children)\n } catch (er) {\n this.#readdirFail((er as NodeJS.ErrnoException).code)\n children.provisional = 0\n }\n return children.slice(0, children.provisional)\n }\n\n canReaddir() {\n if (this.#type & ENOCHILD) return false\n const ifmt = IFMT & this.#type\n // we always set ENOTDIR when setting IFMT, so should be impossible\n /* c8 ignore start */\n if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n return false\n }\n /* c8 ignore stop */\n return true\n }\n\n shouldWalk(\n dirs: Set<PathBase | undefined>,\n walkFilter?: (e: PathBase) => boolean,\n ): boolean {\n return (\n (this.#type & IFDIR) === IFDIR &&\n !(this.#type & ENOCHILD) &&\n !dirs.has(this) &&\n (!walkFilter || walkFilter(this))\n )\n }\n\n /**\n * Return the Path object corresponding to path as resolved\n * by realpath(3).\n *\n * If the realpath call fails for any reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n * On success, returns a Path object.\n */\n async realpath(): Promise<PathBase | undefined> {\n if (this.#realpath) return this.#realpath\n if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n try {\n const rp = await this.#fs.promises.realpath(this.fullpath())\n return (this.#realpath = this.resolve(rp))\n } catch (_) {\n this.#markENOREALPATH()\n }\n }\n\n /**\n * Synchronous {@link realpath}\n */\n realpathSync(): PathBase | undefined {\n if (this.#realpath) return this.#realpath\n if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n try {\n const rp = this.#fs.realpathSync(this.fullpath())\n return (this.#realpath = this.resolve(rp))\n } catch (_) {\n this.#markENOREALPATH()\n }\n }\n\n /**\n * Internal method to mark this Path object as the scurry cwd,\n * called by {@link PathScurry#chdir}\n *\n * @internal\n */\n [setAsCwd](oldCwd: PathBase): void {\n if (oldCwd === this) return\n oldCwd.isCWD = false\n this.isCWD = true\n\n const changed = new Set<PathBase>([])\n let rp = []\n let p: PathBase = this\n while (p && p.parent) {\n changed.add(p)\n p.#relative = rp.join(this.sep)\n p.#relativePosix = rp.join('/')\n p = p.parent\n rp.push('..')\n }\n // now un-memoize parents of old cwd\n p = oldCwd\n while (p && p.parent && !changed.has(p)) {\n p.#relative = undefined\n p.#relativePosix = undefined\n p = p.parent\n }\n }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n /**\n * Separator for generating path strings.\n */\n sep: '\\\\' = '\\\\'\n /**\n * Separator for parsing path strings.\n */\n splitSep: RegExp = eitherSep\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n super(name, type, root, roots, nocase, children, opts)\n }\n\n /**\n * @internal\n */\n newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n return new PathWin32(\n name,\n type,\n this.root,\n this.roots,\n this.nocase,\n this.childrenCache(),\n opts,\n )\n }\n\n /**\n * @internal\n */\n getRootString(path: string): string {\n return win32.parse(path).root\n }\n\n /**\n * @internal\n */\n getRoot(rootPath: string): PathBase {\n rootPath = uncToDrive(rootPath.toUpperCase())\n if (rootPath === this.root.name) {\n return this.root\n }\n // ok, not that one, check if it matches another we know about\n for (const [compare, root] of Object.entries(this.roots)) {\n if (this.sameRoot(rootPath, compare)) {\n return (this.roots[rootPath] = root)\n }\n }\n // otherwise, have to create a new one.\n return (this.roots[rootPath] = new PathScurryWin32(\n rootPath,\n this,\n ).root)\n }\n\n /**\n * @internal\n */\n sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n // windows can (rarely) have case-sensitive filesystem, but\n // UNC and drive letters are always case-insensitive, and canonically\n // represented uppercase.\n rootPath = rootPath\n .toUpperCase()\n .replace(/\\//g, '\\\\')\n .replace(uncDriveRegexp, '$1\\\\')\n return rootPath === compare\n }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n /**\n * separator for parsing path strings\n */\n splitSep: '/' = '/'\n /**\n * separator for generating path strings\n */\n sep: '/' = '/'\n\n /**\n * Do not create new Path objects directly. They should always be accessed\n * via the PathScurry class or other methods on the Path class.\n *\n * @internal\n */\n constructor(\n name: string,\n type: number = UNKNOWN,\n root: PathBase | undefined,\n roots: { [k: string]: PathBase },\n nocase: boolean,\n children: ChildrenCache,\n opts: PathOpts,\n ) {\n super(name, type, root, roots, nocase, children, opts)\n }\n\n /**\n * @internal\n */\n getRootString(path: string): string {\n return path.startsWith('/') ? '/' : ''\n }\n\n /**\n * @internal\n */\n getRoot(_rootPath: string): PathBase {\n return this.root\n }\n\n /**\n * @internal\n */\n newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n return new PathPosix(\n name,\n type,\n this.root,\n this.roots,\n this.nocase,\n this.childrenCache(),\n opts,\n )\n }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n /**\n * perform case-insensitive path matching. Default based on platform\n * subclass.\n */\n nocase?: boolean\n /**\n * Number of Path entries to keep in the cache of Path child references.\n *\n * Setting this higher than 65536 will dramatically increase the data\n * consumption and construction time overhead of each PathScurry.\n *\n * Setting this value to 256 or lower will significantly reduce the data\n * consumption and construction time overhead, but may also reduce resolve()\n * and readdir() performance on large filesystems.\n *\n * Default `16384`.\n */\n childrenCacheSize?: number\n /**\n * An object that overrides the built-in functions from the fs and\n * fs/promises modules.\n *\n * See {@link FSOption}\n */\n fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n /**\n * The root Path entry for the current working directory of this Scurry\n */\n root: PathBase\n /**\n * The string path for the root of this Scurry's current working directory\n */\n rootPath: string\n /**\n * A collection of all roots encountered, referenced by rootPath\n */\n roots: { [k: string]: PathBase }\n /**\n * The Path entry corresponding to this PathScurry's current working directory.\n */\n cwd: PathBase\n #resolveCache: ResolveCache\n #resolvePosixCache: ResolveCache\n #children: ChildrenCache\n /**\n * Perform path comparisons case-insensitively.\n *\n * Defaults true on Darwin and Windows systems, false elsewhere.\n */\n nocase: boolean\n\n /**\n * The path separator used for parsing paths\n *\n * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n */\n abstract sep: string | RegExp\n\n #fs: FSValue\n\n /**\n * This class should not be instantiated directly.\n *\n * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n *\n * @internal\n */\n constructor(\n cwd: URL | string = process.cwd(),\n pathImpl: typeof win32 | typeof posix,\n sep: string | RegExp,\n {\n nocase,\n childrenCacheSize = 16 * 1024,\n fs = defaultFS,\n }: PathScurryOpts = {},\n ) {\n this.#fs = fsFromOption(fs)\n if (cwd instanceof URL || cwd.startsWith('file://')) {\n cwd = fileURLToPath(cwd)\n }\n // resolve and split root, and then add to the store.\n // this is the only time we call path.resolve()\n const cwdPath = pathImpl.resolve(cwd)\n this.roots = Object.create(null)\n this.rootPath = this.parseRootPath(cwdPath)\n this.#resolveCache = new ResolveCache()\n this.#resolvePosixCache = new ResolveCache()\n this.#children = new ChildrenCache(childrenCacheSize)\n\n const split = cwdPath.substring(this.rootPath.length).split(sep)\n // resolve('/') leaves '', splits to [''], we don't want that.\n if (split.length === 1 && !split[0]) {\n split.pop()\n }\n /* c8 ignore start */\n if (nocase === undefined) {\n throw new TypeError(\n 'must provide nocase setting to PathScurryBase ctor',\n )\n }\n /* c8 ignore stop */\n this.nocase = nocase\n this.root = this.newRoot(this.#fs)\n this.roots[this.rootPath] = this.root\n let prev: PathBase = this.root\n let len = split.length - 1\n const joinSep = pathImpl.sep\n let abs = this.rootPath\n let sawFirst = false\n for (const part of split) {\n const l = len--\n prev = prev.child(part, {\n relative: new Array(l).fill('..').join(joinSep),\n relativePosix: new Array(l).fill('..').join('/'),\n fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n })\n sawFirst = true\n }\n this.cwd = prev\n }\n\n /**\n * Get the depth of a provided path, string, or the cwd\n */\n depth(path: Path | string = this.cwd): number {\n if (typeof path === 'string') {\n path = this.cwd.resolve(path)\n }\n return path.depth()\n }\n\n /**\n * Parse the root portion of a path string\n *\n * @internal\n */\n abstract parseRootPath(dir: string): string\n /**\n * create a new Path to use as root during construction.\n *\n * @internal\n */\n abstract newRoot(fs: FSValue): PathBase\n /**\n * Determine whether a given path string is absolute\n */\n abstract isAbsolute(p: string): boolean\n\n /**\n * Return the cache of child entries. Exposed so subclasses can create\n * child Path objects in a platform-specific way.\n *\n * @internal\n */\n childrenCache() {\n return this.#children\n }\n\n /**\n * Resolve one or more path strings to a resolved string\n *\n * Same interface as require('path').resolve.\n *\n * Much faster than path.resolve() when called multiple times for the same\n * path, because the resolved Path objects are cached. Much slower\n * otherwise.\n */\n resolve(...paths: string[]): string {\n // first figure out the minimum number of paths we have to test\n // we always start at cwd, but any absolutes will bump the start\n let r = ''\n for (let i = paths.length - 1; i >= 0; i--) {\n const p = paths[i]\n if (!p || p === '.') continue\n r = r ? `${p}/${r}` : p\n if (this.isAbsolute(p)) {\n break\n }\n }\n const cached = this.#resolveCache.get(r)\n if (cached !== undefined) {\n return cached\n }\n const result = this.cwd.resolve(r).fullpath()\n this.#resolveCache.set(r, result)\n return result\n }\n\n /**\n * Resolve one or more path strings to a resolved string, returning\n * the posix path. Identical to .resolve() on posix systems, but on\n * windows will return a forward-slash separated UNC path.\n *\n * Same interface as require('path').resolve.\n *\n * Much faster than path.resolve() when called multiple times for the same\n * path, because the resolved Path objects are cached. Much slower\n * otherwise.\n */\n resolvePosix(...paths: string[]): string {\n // first figure out the minimum number of paths we have to test\n // we always start at cwd, but any absolutes will bump the start\n let r = ''\n for (let i = paths.length - 1; i >= 0; i--) {\n const p = paths[i]\n if (!p || p === '.') continue\n r = r ? `${p}/${r}` : p\n if (this.isAbsolute(p)) {\n break\n }\n }\n const cached = this.#resolvePosixCache.get(r)\n if (cached !== undefined) {\n return cached\n }\n const result = this.cwd.resolve(r).fullpathPosix()\n this.#resolvePosixCache.set(r, result)\n return result\n }\n\n /**\n * find the relative path from the cwd to the supplied path string or entry\n */\n relative(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.relative()\n }\n\n /**\n * find the relative path from the cwd to the supplied path string or\n * entry, using / as the path delimiter, even on Windows.\n */\n relativePosix(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.relativePosix()\n }\n\n /**\n * Return the basename for the provided string or Path object\n */\n basename(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.name\n }\n\n /**\n * Return the dirname for the provided string or Path object\n */\n dirname(entry: PathBase | string = this.cwd): string {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return (entry.parent || entry).fullpath()\n }\n\n /**\n * Return an array of known child entries.\n *\n * First argument may be either a string, or a Path object.\n *\n * If the Path cannot or does not contain any children, then an empty array\n * is returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n *\n * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n * `{ withFileTypes: false }` to return strings.\n */\n\n readdir(): Promise<PathBase[]>\n readdir(opts: { withFileTypes: true }): Promise<PathBase[]>\n readdir(opts: { withFileTypes: false }): Promise<string[]>\n readdir(opts: { withFileTypes: boolean }): Promise<PathBase[] | string[]>\n readdir(entry: PathBase | string): Promise<PathBase[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: true },\n ): Promise<PathBase[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: false },\n ): Promise<string[]>\n readdir(\n entry: PathBase | string,\n opts: { withFileTypes: boolean },\n ): Promise<PathBase[] | string[]>\n async readdir(\n entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n opts: { withFileTypes: boolean } = {\n withFileTypes: true,\n },\n ): Promise<PathBase[] | string[]> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const { withFileTypes } = opts\n if (!entry.canReaddir()) {\n return []\n } else {\n const p = await entry.readdir()\n return withFileTypes ? p : p.map(e => e.name)\n }\n }\n\n /**\n * synchronous {@link PathScurryBase.readdir}\n */\n readdirSync(): PathBase[]\n readdirSync(opts: { withFileTypes: true }): PathBase[]\n readdirSync(opts: { withFileTypes: false }): string[]\n readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n readdirSync(entry: PathBase | string): PathBase[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: true },\n ): PathBase[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: false },\n ): string[]\n readdirSync(\n entry: PathBase | string,\n opts: { withFileTypes: boolean },\n ): PathBase[] | string[]\n readdirSync(\n entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n opts: { withFileTypes: boolean } = {\n withFileTypes: true,\n },\n ): PathBase[] | string[] {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const { withFileTypes = true } = opts\n if (!entry.canReaddir()) {\n return []\n } else if (withFileTypes) {\n return entry.readdirSync()\n } else {\n return entry.readdirSync().map(e => e.name)\n }\n }\n\n /**\n * Call lstat() on the string or Path object, and update all known\n * information that can be determined.\n *\n * Note that unlike `fs.lstat()`, the returned value does not contain some\n * information, such as `mode`, `dev`, `nlink`, and `ino`. If that\n * information is required, you will need to call `fs.lstat` yourself.\n *\n * If the Path refers to a nonexistent file, or if the lstat call fails for\n * any reason, `undefined` is returned. Otherwise the updated Path object is\n * returned.\n *\n * Results are cached, and thus may be out of date if the filesystem is\n * mutated.\n */\n async lstat(\n entry: string | PathBase = this.cwd,\n ): Promise<PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.lstat()\n }\n\n /**\n * synchronous {@link PathScurryBase.lstat}\n */\n lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n }\n return entry.lstatSync()\n }\n\n /**\n * Return the Path object or string path corresponding to the target of a\n * symbolic link.\n *\n * If the path is not a symbolic link, or if the readlink call fails for any\n * reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n *\n * `{withFileTypes}` option defaults to `false`.\n *\n * On success, returns a Path object if `withFileTypes` option is true,\n * otherwise a string.\n */\n readlink(): Promise<string | undefined>\n readlink(opt: { withFileTypes: false }): Promise<string | undefined>\n readlink(opt: { withFileTypes: true }): Promise<PathBase | undefined>\n readlink(opt: {\n withFileTypes: boolean\n }): Promise<PathBase | string | undefined>\n readlink(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): Promise<string | undefined>\n readlink(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): Promise<PathBase | undefined>\n readlink(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): Promise<string | PathBase | undefined>\n async readlink(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): Promise<string | PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = await entry.readlink()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * synchronous {@link PathScurryBase.readlink}\n */\n readlinkSync(): string | undefined\n readlinkSync(opt: { withFileTypes: false }): string | undefined\n readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n readlinkSync(opt: {\n withFileTypes: boolean\n }): PathBase | string | undefined\n readlinkSync(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): string | undefined\n readlinkSync(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): PathBase | undefined\n readlinkSync(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): string | PathBase | undefined\n readlinkSync(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): string | PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = entry.readlinkSync()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * Return the Path object or string path corresponding to path as resolved\n * by realpath(3).\n *\n * If the realpath call fails for any reason, `undefined` is returned.\n *\n * Result is cached, and thus may be outdated if the filesystem is mutated.\n *\n * `{withFileTypes}` option defaults to `false`.\n *\n * On success, returns a Path object if `withFileTypes` option is true,\n * otherwise a string.\n */\n realpath(): Promise<string | undefined>\n realpath(opt: { withFileTypes: false }): Promise<string | undefined>\n realpath(opt: { withFileTypes: true }): Promise<PathBase | undefined>\n realpath(opt: {\n withFileTypes: boolean\n }): Promise<PathBase | string | undefined>\n realpath(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): Promise<string | undefined>\n realpath(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): Promise<PathBase | undefined>\n realpath(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): Promise<string | PathBase | undefined>\n async realpath(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): Promise<string | PathBase | undefined> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = await entry.realpath()\n return withFileTypes ? e : e?.fullpath()\n }\n\n realpathSync(): string | undefined\n realpathSync(opt: { withFileTypes: false }): string | undefined\n realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n realpathSync(opt: {\n withFileTypes: boolean\n }): PathBase | string | undefined\n realpathSync(\n entry: string | PathBase,\n opt?: { withFileTypes: false },\n ): string | undefined\n realpathSync(\n entry: string | PathBase,\n opt: { withFileTypes: true },\n ): PathBase | undefined\n realpathSync(\n entry: string | PathBase,\n opt: { withFileTypes: boolean },\n ): string | PathBase | undefined\n realpathSync(\n entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n { withFileTypes }: { withFileTypes: boolean } = {\n withFileTypes: false,\n },\n ): string | PathBase | undefined {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n withFileTypes = entry.withFileTypes\n entry = this.cwd\n }\n const e = entry.realpathSync()\n return withFileTypes ? e : e?.fullpath()\n }\n\n /**\n * Asynchronously walk the directory tree, returning an array of\n * all path strings or Path objects found.\n *\n * Note that this will be extremely memory-hungry on large filesystems.\n * In such cases, it may be better to use the stream or async iterator\n * walk implementation.\n */\n walk(): Promise<PathBase[]>\n walk(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Promise<PathBase[]>\n walk(opts: WalkOptionsWithFileTypesFalse): Promise<string[]>\n walk(opts: WalkOptions): Promise<string[] | PathBase[]>\n walk(entry: string | PathBase): Promise<PathBase[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Promise<PathBase[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Promise<string[]>\n walk(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Promise<PathBase[] | string[]>\n async walk(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Promise<PathBase[] | string[]> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results: (string | PathBase)[] = []\n if (!filter || filter(entry)) {\n results.push(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>()\n const walk = (\n dir: PathBase,\n cb: (er?: NodeJS.ErrnoException) => void,\n ) => {\n dirs.add(dir)\n dir.readdirCB((er, entries) => {\n /* c8 ignore start */\n if (er) {\n return cb(er)\n }\n /* c8 ignore stop */\n let len = entries.length\n if (!len) return cb()\n const next = () => {\n if (--len === 0) {\n cb()\n }\n }\n for (const e of entries) {\n if (!filter || filter(e)) {\n results.push(withFileTypes ? e : e.fullpath())\n }\n if (follow && e.isSymbolicLink()) {\n e.realpath()\n .then(r => (r?.isUnknown() ? r.lstat() : r))\n .then(r =>\n r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n )\n } else {\n if (e.shouldWalk(dirs, walkFilter)) {\n walk(e, next)\n } else {\n next()\n }\n }\n }\n }, true) // zalgooooooo\n }\n\n const start = entry\n return new Promise<PathBase[] | string[]>((res, rej) => {\n walk(start, er => {\n /* c8 ignore start */\n if (er) return rej(er)\n /* c8 ignore stop */\n res(results as PathBase[] | string[])\n })\n })\n }\n\n /**\n * Synchronously walk the directory tree, returning an array of\n * all path strings or Path objects found.\n *\n * Note that this will be extremely memory-hungry on large filesystems.\n * In such cases, it may be better to use the stream or async iterator\n * walk implementation.\n */\n walkSync(): PathBase[]\n walkSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): PathBase[]\n walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n walkSync(opts: WalkOptions): string[] | PathBase[]\n walkSync(entry: string | PathBase): PathBase[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): PathBase[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): string[]\n walkSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): PathBase[] | string[]\n walkSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): PathBase[] | string[] {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results: (string | PathBase)[] = []\n if (!filter || filter(entry)) {\n results.push(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>([entry])\n for (const dir of dirs) {\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n results.push(withFileTypes ? e : e.fullpath())\n }\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n dirs.add(r)\n }\n }\n }\n return results as string[] | PathBase[]\n }\n\n /**\n * Support for `for await`\n *\n * Alias for {@link PathScurryBase.iterate}\n *\n * Note: As of Node 19, this is very slow, compared to other methods of\n * walking. Consider using {@link PathScurryBase.stream} if memory overhead\n * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n */\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n\n /**\n * Async generator form of {@link PathScurryBase.walk}\n *\n * Note: As of Node 19, this is very slow, compared to other methods of\n * walking, especially if most/all of the directory tree has been previously\n * walked. Consider using {@link PathScurryBase.stream} if memory overhead\n * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n */\n iterate(): AsyncGenerator<PathBase, void, void>\n iterate(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): AsyncGenerator<PathBase, void, void>\n iterate(\n opts: WalkOptionsWithFileTypesFalse,\n ): AsyncGenerator<string, void, void>\n iterate(opts: WalkOptions): AsyncGenerator<string | PathBase, void, void>\n iterate(entry: string | PathBase): AsyncGenerator<PathBase, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): AsyncGenerator<PathBase, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): AsyncGenerator<string, void, void>\n iterate(\n entry: string | PathBase,\n opts: WalkOptions,\n ): AsyncGenerator<PathBase | string, void, void>\n iterate(\n entry: string | PathBase | WalkOptions = this.cwd,\n options: WalkOptions = {},\n ): AsyncGenerator<PathBase | string, void, void> {\n // iterating async over the stream is significantly more performant,\n // especially in the warm-cache scenario, because it buffers up directory\n // entries in the background instead of waiting for a yield for each one.\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n options = entry\n entry = this.cwd\n }\n return this.stream(entry, options)[Symbol.asyncIterator]()\n }\n\n /**\n * Iterating over a PathScurry performs a synchronous walk.\n *\n * Alias for {@link PathScurryBase.iterateSync}\n */\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n iterateSync(): Generator<PathBase, void, void>\n iterateSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Generator<PathBase, void, void>\n iterateSync(\n opts: WalkOptionsWithFileTypesFalse,\n ): Generator<string, void, void>\n iterateSync(opts: WalkOptions): Generator<string | PathBase, void, void>\n iterateSync(entry: string | PathBase): Generator<PathBase, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Generator<PathBase, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Generator<string, void, void>\n iterateSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Generator<PathBase | string, void, void>\n *iterateSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Generator<PathBase | string, void, void> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n if (!filter || filter(entry)) {\n yield withFileTypes ? entry : entry.fullpath()\n }\n const dirs = new Set<PathBase>([entry])\n for (const dir of dirs) {\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n yield withFileTypes ? e : e.fullpath()\n }\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n dirs.add(r)\n }\n }\n }\n }\n\n /**\n * Stream form of {@link PathScurryBase.walk}\n *\n * Returns a Minipass stream that emits {@link PathBase} objects by default,\n * or strings if `{ withFileTypes: false }` is set in the options.\n */\n stream(): Minipass<PathBase>\n stream(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Minipass<PathBase>\n stream(opts: WalkOptionsWithFileTypesFalse): Minipass<string>\n stream(opts: WalkOptions): Minipass<string | PathBase>\n stream(entry: string | PathBase): Minipass<PathBase>\n stream(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): Minipass<PathBase>\n stream(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Minipass<string>\n stream(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Minipass<string> | Minipass<PathBase>\n stream(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Minipass<string> | Minipass<PathBase> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results = new Minipass<string | PathBase>({ objectMode: true })\n if (!filter || filter(entry)) {\n results.write(withFileTypes ? entry : entry.fullpath())\n }\n const dirs = new Set<PathBase>()\n const queue: PathBase[] = [entry]\n let processing = 0\n const process = () => {\n let paused = false\n while (!paused) {\n const dir = queue.shift()\n if (!dir) {\n if (processing === 0) results.end()\n return\n }\n\n processing++\n dirs.add(dir)\n\n const onReaddir = (\n er: null | NodeJS.ErrnoException,\n entries: PathBase[],\n didRealpaths: boolean = false,\n ) => {\n /* c8 ignore start */\n if (er) return results.emit('error', er)\n /* c8 ignore stop */\n if (follow && !didRealpaths) {\n const promises: Promise<PathBase | undefined>[] = []\n for (const e of entries) {\n if (e.isSymbolicLink()) {\n promises.push(\n e\n .realpath()\n .then((r: PathBase | undefined) =>\n r?.isUnknown() ? r.lstat() : r,\n ),\n )\n }\n }\n if (promises.length) {\n Promise.all(promises).then(() =>\n onReaddir(null, entries, true),\n )\n return\n }\n }\n\n for (const e of entries) {\n if (e && (!filter || filter(e))) {\n if (!results.write(withFileTypes ? e : e.fullpath())) {\n paused = true\n }\n }\n }\n\n processing--\n for (const e of entries) {\n const r = e.realpathCached() || e\n if (r.shouldWalk(dirs, walkFilter)) {\n queue.push(r)\n }\n }\n if (paused && !results.flowing) {\n results.once('drain', process)\n } else if (!sync) {\n process()\n }\n }\n\n // zalgo containment\n let sync = true\n dir.readdirCB(onReaddir, true)\n sync = false\n }\n }\n process()\n return results as Minipass<string> | Minipass<PathBase>\n }\n\n /**\n * Synchronous form of {@link PathScurryBase.stream}\n *\n * Returns a Minipass stream that emits {@link PathBase} objects by default,\n * or strings if `{ withFileTypes: false }` is set in the options.\n *\n * Will complete the walk in a single tick if the stream is consumed fully.\n * Otherwise, will pause as needed for stream backpressure.\n */\n streamSync(): Minipass<PathBase>\n streamSync(\n opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n ): Minipass<PathBase>\n streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass<string>\n streamSync(opts: WalkOptions): Minipass<string | PathBase>\n streamSync(entry: string | PathBase): Minipass<PathBase>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n ): Minipass<PathBase>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptionsWithFileTypesFalse,\n ): Minipass<string>\n streamSync(\n entry: string | PathBase,\n opts: WalkOptions,\n ): Minipass<string> | Minipass<PathBase>\n streamSync(\n entry: string | PathBase | WalkOptions = this.cwd,\n opts: WalkOptions = {},\n ): Minipass<string> | Minipass<PathBase> {\n if (typeof entry === 'string') {\n entry = this.cwd.resolve(entry)\n } else if (!(entry instanceof PathBase)) {\n opts = entry\n entry = this.cwd\n }\n const {\n withFileTypes = true,\n follow = false,\n filter,\n walkFilter,\n } = opts\n const results = new Minipass<string | PathBase>({ objectMode: true })\n const dirs = new Set<PathBase>()\n if (!filter || filter(entry)) {\n results.write(withFileTypes ? entry : entry.fullpath())\n }\n const queue: PathBase[] = [entry]\n let processing = 0\n const process = () => {\n let paused = false\n while (!paused) {\n const dir = queue.shift()\n if (!dir) {\n if (processing === 0) results.end()\n return\n }\n processing++\n dirs.add(dir)\n\n const entries = dir.readdirSync()\n for (const e of entries) {\n if (!filter || filter(e)) {\n if (!results.write(withFileTypes ? e : e.fullpath())) {\n paused = true\n }\n }\n }\n processing--\n for (const e of entries) {\n let r: PathBase | undefined = e\n if (e.isSymbolicLink()) {\n if (!(follow && (r = e.realpathSync()))) continue\n if (r.isUnknown()) r.lstatSync()\n }\n if (r.shouldWalk(dirs, walkFilter)) {\n queue.push(r)\n }\n }\n }\n if (paused && !results.flowing) results.once('drain', process)\n }\n process()\n return results as Minipass<string> | Minipass<PathBase>\n }\n\n chdir(path: string | Path = this.cwd) {\n const oldCwd = this.cwd\n this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n this.cwd[setAsCwd](oldCwd)\n }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n /**\n * Return results as {@link PathBase} objects rather than strings.\n * When set to false, results are fully resolved paths, as returned by\n * {@link PathBase.fullpath}.\n * @default true\n */\n withFileTypes?: boolean\n\n /**\n * Attempt to read directory entries from symbolic links. Otherwise, only\n * actual directories are traversed. Regardless of this setting, a given\n * target path will only ever be walked once, meaning that a symbolic link\n * to a previously traversed directory will never be followed.\n *\n * Setting this imposes a slight performance penalty, because `readlink`\n * must be called on all symbolic links encountered, in order to avoid\n * infinite cycles.\n * @default false\n */\n follow?: boolean\n\n /**\n * Only return entries where the provided function returns true.\n *\n * This will not prevent directories from being traversed, even if they do\n * not pass the filter, though it will prevent directories themselves from\n * being included in the result set. See {@link walkFilter}\n *\n * Asynchronous functions are not supported here.\n *\n * By default, if no filter is provided, all entries and traversed\n * directories are included.\n */\n filter?: (entry: PathBase) => boolean\n\n /**\n * Only traverse directories (and in the case of {@link follow} being set to\n * true, symbolic links to directories) if the provided function returns\n * true.\n *\n * This will not prevent directories from being included in the result set,\n * even if they do not pass the supplied filter function. See {@link filter}\n * to do that.\n *\n * Asynchronous functions are not supported here.\n */\n walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings. Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n /**\n * separator for generating path strings\n */\n sep: '\\\\' = '\\\\'\n\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = true } = opts\n super(cwd, win32, '\\\\', { ...opts, nocase })\n this.nocase = nocase\n for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n p.nocase = this.nocase\n }\n }\n\n /**\n * @internal\n */\n parseRootPath(dir: string): string {\n // if the path starts with a single separator, it's not a UNC, and we'll\n // just get separator as the root, and driveFromUNC will return \\\n // In that case, mount \\ on the root from the cwd.\n return win32.parse(dir).root.toUpperCase()\n }\n\n /**\n * @internal\n */\n newRoot(fs: FSValue) {\n return new PathWin32(\n this.rootPath,\n IFDIR,\n undefined,\n this.roots,\n this.nocase,\n this.childrenCache(),\n { fs },\n )\n }\n\n /**\n * Return true if the provided path string is an absolute path\n */\n isAbsolute(p: string): boolean {\n return (\n p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n )\n }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n /**\n * separator for generating path strings\n */\n sep: '/' = '/'\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = false } = opts\n super(cwd, posix, '/', { ...opts, nocase })\n this.nocase = nocase\n }\n\n /**\n * @internal\n */\n parseRootPath(_dir: string): string {\n return '/'\n }\n\n /**\n * @internal\n */\n newRoot(fs: FSValue) {\n return new PathPosix(\n this.rootPath,\n IFDIR,\n undefined,\n this.roots,\n this.nocase,\n this.childrenCache(),\n { fs },\n )\n }\n\n /**\n * Return true if the provided path string is an absolute path\n */\n isAbsolute(p: string): boolean {\n return p.startsWith('/')\n }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n constructor(\n cwd: URL | string = process.cwd(),\n opts: PathScurryOpts = {},\n ) {\n const { nocase = true } = opts\n super(cwd, { ...opts, nocase })\n }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType<typeof Path>\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n | typeof PathScurryWin32\n | typeof PathScurryDarwin\n | typeof PathScurryPosix =\n process.platform === 'win32' ? PathScurryWin32\n : process.platform === 'darwin' ? PathScurryDarwin\n : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType<typeof PathScurry>\n","// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n p0: '',\n p1: '',\n p2: string,\n p3: string,\n ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n readonly #patternList: PatternList\n readonly #globList: GlobList\n readonly #index: number\n readonly length: number\n readonly #platform: NodeJS.Platform\n #rest?: Pattern | null\n #globString?: string\n #isDrive?: boolean\n #isUNC?: boolean\n #isAbsolute?: boolean\n #followGlobstar: boolean = true\n\n constructor(\n patternList: MMPattern[],\n globList: string[],\n index: number,\n platform: NodeJS.Platform,\n ) {\n if (!isPatternList(patternList)) {\n throw new TypeError('empty pattern list')\n }\n if (!isGlobList(globList)) {\n throw new TypeError('empty glob list')\n }\n if (globList.length !== patternList.length) {\n throw new TypeError('mismatched pattern list and glob list lengths')\n }\n this.length = patternList.length\n if (index < 0 || index >= this.length) {\n throw new TypeError('index out of range')\n }\n this.#patternList = patternList\n this.#globList = globList\n this.#index = index\n this.#platform = platform\n\n // normalize root entries of absolute patterns on initial creation.\n if (this.#index === 0) {\n // c: => ['c:/']\n // C:/ => ['C:/']\n // C:/x => ['C:/', 'x']\n // //host/share => ['//host/share/']\n // //host/share/ => ['//host/share/']\n // //host/share/x => ['//host/share/', 'x']\n // /etc => ['/', 'etc']\n // / => ['/']\n if (this.isUNC()) {\n // '' / '' / 'host' / 'share'\n const [p0, p1, p2, p3, ...prest] = this.#patternList\n const [g0, g1, g2, g3, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = [p0, p1, p2, p3, ''].join('/')\n const g = [g0, g1, g2, g3, ''].join('/')\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n } else if (this.isDrive() || this.isAbsolute()) {\n const [p1, ...prest] = this.#patternList\n const [g1, ...grest] = this.#globList\n if (prest[0] === '') {\n // ends in /\n prest.shift()\n grest.shift()\n }\n const p = (p1 as string) + '/'\n const g = g1 + '/'\n this.#patternList = [p, ...prest]\n this.#globList = [g, ...grest]\n this.length = this.#patternList.length\n }\n }\n }\n\n /**\n * The first entry in the parsed list of patterns\n */\n pattern(): MMPattern {\n return this.#patternList[this.#index] as MMPattern\n }\n\n /**\n * true of if pattern() returns a string\n */\n isString(): boolean {\n return typeof this.#patternList[this.#index] === 'string'\n }\n /**\n * true of if pattern() returns GLOBSTAR\n */\n isGlobstar(): boolean {\n return this.#patternList[this.#index] === GLOBSTAR\n }\n /**\n * true if pattern() returns a regexp\n */\n isRegExp(): boolean {\n return this.#patternList[this.#index] instanceof RegExp\n }\n\n /**\n * The /-joined set of glob parts that make up this pattern\n */\n globString(): string {\n return (this.#globString =\n this.#globString ||\n (this.#index === 0 ?\n this.isAbsolute() ?\n this.#globList[0] + this.#globList.slice(1).join('/')\n : this.#globList.join('/')\n : this.#globList.slice(this.#index).join('/')))\n }\n\n /**\n * true if there are more pattern parts after this one\n */\n hasMore(): boolean {\n return this.length > this.#index + 1\n }\n\n /**\n * The rest of the pattern after this part, or null if this is the end\n */\n rest(): Pattern | null {\n if (this.#rest !== undefined) return this.#rest\n if (!this.hasMore()) return (this.#rest = null)\n this.#rest = new Pattern(\n this.#patternList,\n this.#globList,\n this.#index + 1,\n this.#platform,\n )\n this.#rest.#isAbsolute = this.#isAbsolute\n this.#rest.#isUNC = this.#isUNC\n this.#rest.#isDrive = this.#isDrive\n return this.#rest\n }\n\n /**\n * true if the pattern represents a //unc/path/ on windows\n */\n isUNC(): boolean {\n const pl = this.#patternList\n return this.#isUNC !== undefined ?\n this.#isUNC\n : (this.#isUNC =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n pl[0] === '' &&\n pl[1] === '' &&\n typeof pl[2] === 'string' &&\n !!pl[2] &&\n typeof pl[3] === 'string' &&\n !!pl[3])\n }\n\n // pattern like C:/...\n // split = ['C:', ...]\n // XXX: would be nice to handle patterns like `c:*` to test the cwd\n // in c: for *, but I don't know of a way to even figure out what that\n // cwd is without actually chdir'ing into it?\n /**\n * True if the pattern starts with a drive letter on Windows\n */\n isDrive(): boolean {\n const pl = this.#patternList\n return this.#isDrive !== undefined ?\n this.#isDrive\n : (this.#isDrive =\n this.#platform === 'win32' &&\n this.#index === 0 &&\n this.length > 1 &&\n typeof pl[0] === 'string' &&\n /^[a-z]:$/i.test(pl[0]))\n }\n\n // pattern = '/' or '/...' or '/x/...'\n // split = ['', ''] or ['', ...] or ['', 'x', ...]\n // Drive and UNC both considered absolute on windows\n /**\n * True if the pattern is rooted on an absolute path\n */\n isAbsolute(): boolean {\n const pl = this.#patternList\n return this.#isAbsolute !== undefined ?\n this.#isAbsolute\n : (this.#isAbsolute =\n (pl[0] === '' && pl.length > 1) ||\n this.isDrive() ||\n this.isUNC())\n }\n\n /**\n * consume the root of the pattern, and return it\n */\n root(): string {\n const p = this.#patternList[0]\n return (\n typeof p === 'string' && this.isAbsolute() && this.#index === 0\n ) ?\n p\n : ''\n }\n\n /**\n * Check to see if the current globstar pattern is allowed to follow\n * a symbolic link.\n */\n checkFollowGlobstar(): boolean {\n return !(\n this.#index === 0 ||\n !this.isGlobstar() ||\n !this.#followGlobstar\n )\n }\n\n /**\n * Mark that the current globstar pattern is following a symbolic link\n */\n markFollowGlobstar(): boolean {\n if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n return false\n this.#followGlobstar = false\n return true\n }\n}\n","// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n ignored?: (p: Path) => boolean\n childrenIgnored?: (p: Path) => boolean\n add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n relative: Minimatch[]\n relativeChildren: Minimatch[]\n absolute: Minimatch[]\n absoluteChildren: Minimatch[]\n platform: NodeJS.Platform\n mmopts: MinimatchOptions\n\n constructor(\n ignored: string[],\n {\n nobrace,\n nocase,\n noext,\n noglobstar,\n platform = defaultPlatform,\n }: GlobWalkerOpts,\n ) {\n this.relative = []\n this.absolute = []\n this.relativeChildren = []\n this.absoluteChildren = []\n this.platform = platform\n this.mmopts = {\n dot: true,\n nobrace,\n nocase,\n noext,\n noglobstar,\n optimizationLevel: 2,\n platform,\n nocomment: true,\n nonegate: true,\n }\n for (const ign of ignored) this.add(ign)\n }\n\n add(ign: string) {\n // this is a little weird, but it gives us a clean set of optimized\n // minimatch matchers, without getting tripped up if one of them\n // ends in /** inside a brace section, and it's only inefficient at\n // the start of the walk, not along it.\n // It'd be nice if the Pattern class just had a .test() method, but\n // handling globstars is a bit of a pita, and that code already lives\n // in minimatch anyway.\n // Another way would be if maybe Minimatch could take its set/globParts\n // as an option, and then we could at least just use Pattern to test\n // for absolute-ness.\n // Yet another way, Minimatch could take an array of glob strings, and\n // a cwd option, and do the right thing.\n const mm = new Minimatch(ign, this.mmopts)\n for (let i = 0; i < mm.set.length; i++) {\n const parsed = mm.set[i]\n const globParts = mm.globParts[i]\n /* c8 ignore start */\n if (!parsed || !globParts) {\n throw new Error('invalid pattern object')\n }\n // strip off leading ./ portions\n // https://github.com/isaacs/node-glob/issues/570\n while (parsed[0] === '.' && globParts[0] === '.') {\n parsed.shift()\n globParts.shift()\n }\n /* c8 ignore stop */\n const p = new Pattern(parsed, globParts, 0, this.platform)\n const m = new Minimatch(p.globString(), this.mmopts)\n const children = globParts[globParts.length - 1] === '**'\n const absolute = p.isAbsolute()\n if (absolute) this.absolute.push(m)\n else this.relative.push(m)\n if (children) {\n if (absolute) this.absoluteChildren.push(m)\n else this.relativeChildren.push(m)\n }\n }\n }\n\n ignored(p: Path): boolean {\n const fullpath = p.fullpath()\n const fullpaths = `${fullpath}/`\n const relative = p.relative() || '.'\n const relatives = `${relative}/`\n for (const m of this.relative) {\n if (m.match(relative) || m.match(relatives)) return true\n }\n for (const m of this.absolute) {\n if (m.match(fullpath) || m.match(fullpaths)) return true\n }\n return false\n }\n\n childrenIgnored(p: Path): boolean {\n const fullpath = p.fullpath() + '/'\n const relative = (p.relative() || '.') + '/'\n for (const m of this.relativeChildren) {\n if (m.match(relative)) return true\n }\n for (const m of this.absoluteChildren) {\n if (m.match(fullpath)) return true\n }\n return false\n }\n}\n","// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n store: Map<string, Set<string>>\n constructor(store: Map<string, Set<string>> = new Map()) {\n this.store = store\n }\n copy() {\n return new HasWalkedCache(new Map(this.store))\n }\n hasWalked(target: Path, pattern: Pattern) {\n return this.store.get(target.fullpath())?.has(pattern.globString())\n }\n storeWalked(target: Path, pattern: Pattern) {\n const fullpath = target.fullpath()\n const cached = this.store.get(fullpath)\n if (cached) cached.add(pattern.globString())\n else this.store.set(fullpath, new Set([pattern.globString()]))\n }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n store: Map<Path, number> = new Map()\n add(target: Path, absolute: boolean, ifDir: boolean) {\n const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n const current = this.store.get(target)\n this.store.set(target, current === undefined ? n : n & current)\n }\n // match, absolute, ifdir\n entries(): [Path, boolean, boolean][] {\n return [...this.store.entries()].map(([path, n]) => [\n path,\n !!(n & 2),\n !!(n & 1),\n ])\n }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n store: Map<Path, Pattern[]> = new Map()\n add(target: Path, pattern: Pattern) {\n if (!target.canReaddir()) {\n return\n }\n const subs = this.store.get(target)\n if (subs) {\n if (!subs.find(p => p.globString() === pattern.globString())) {\n subs.push(pattern)\n }\n } else this.store.set(target, [pattern])\n }\n get(target: Path): Pattern[] {\n const subs = this.store.get(target)\n /* c8 ignore start */\n if (!subs) {\n throw new Error('attempting to walk unknown path')\n }\n /* c8 ignore stop */\n return subs\n }\n entries(): [Path, Pattern[]][] {\n return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n }\n keys(): Path[] {\n return [...this.store.keys()].filter(t => t.canReaddir())\n }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n hasWalkedCache: HasWalkedCache\n matches = new MatchRecord()\n subwalks = new SubWalks()\n patterns?: Pattern[]\n follow: boolean\n dot: boolean\n opts: GlobWalkerOpts\n\n constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n this.opts = opts\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.hasWalkedCache =\n hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n }\n\n processPatterns(target: Path, patterns: Pattern[]) {\n this.patterns = patterns\n const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n // map of paths to the magic-starting subwalks they need to walk\n // first item in patterns is the filter\n\n for (let [t, pattern] of processingSet) {\n this.hasWalkedCache.storeWalked(t, pattern)\n\n const root = pattern.root()\n const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n // start absolute patterns at root\n if (root) {\n t = t.resolve(\n root === '/' && this.opts.root !== undefined ?\n this.opts.root\n : root,\n )\n const rest = pattern.rest()\n if (!rest) {\n this.matches.add(t, true, false)\n continue\n } else {\n pattern = rest\n }\n }\n\n if (t.isENOENT()) continue\n\n let p: MMPattern\n let rest: Pattern | null\n let changed = false\n while (\n typeof (p = pattern.pattern()) === 'string' &&\n (rest = pattern.rest())\n ) {\n const c = t.resolve(p)\n t = c\n pattern = rest\n changed = true\n }\n p = pattern.pattern()\n rest = pattern.rest()\n if (changed) {\n if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n this.hasWalkedCache.storeWalked(t, pattern)\n }\n\n // now we have either a final string for a known entry,\n // more strings for an unknown entry,\n // or a pattern starting with magic, mounted on t.\n if (typeof p === 'string') {\n // must not be final entry, otherwise we would have\n // concatenated it earlier.\n const ifDir = p === '..' || p === '' || p === '.'\n this.matches.add(t.resolve(p), absolute, ifDir)\n continue\n } else if (p === GLOBSTAR) {\n // if no rest, match and subwalk pattern\n // if rest, process rest and subwalk pattern\n // if it's a symlink, but we didn't get here by way of a\n // globstar match (meaning it's the first time THIS globstar\n // has traversed a symlink), then we follow it. Otherwise, stop.\n if (\n !t.isSymbolicLink() ||\n this.follow ||\n pattern.checkFollowGlobstar()\n ) {\n this.subwalks.add(t, pattern)\n }\n const rp = rest?.pattern()\n const rrest = rest?.rest()\n if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n // only HAS to be a dir if it ends in **/ or **/.\n // but ending in ** will match files as well.\n this.matches.add(t, absolute, rp === '' || rp === '.')\n } else {\n if (rp === '..') {\n // this would mean you're matching **/.. at the fs root,\n // and no thanks, I'm not gonna test that specific case.\n /* c8 ignore start */\n const tp = t.parent || t\n /* c8 ignore stop */\n if (!rrest) this.matches.add(tp, absolute, true)\n else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n this.subwalks.add(tp, rrest)\n }\n }\n }\n } else if (p instanceof RegExp) {\n this.subwalks.add(t, pattern)\n }\n }\n\n return this\n }\n\n subwalkTargets(): Path[] {\n return this.subwalks.keys()\n }\n\n child() {\n return new Processor(this.opts, this.hasWalkedCache)\n }\n\n // return a new Processor containing the subwalks for each\n // child entry, and a set of matches, and\n // a hasWalkedCache that's a copy of this one\n // then we're going to call\n filterEntries(parent: Path, entries: Path[]): Processor {\n const patterns = this.subwalks.get(parent)\n // put matches and entry walks into the results processor\n const results = this.child()\n for (const e of entries) {\n for (const pattern of patterns) {\n const absolute = pattern.isAbsolute()\n const p = pattern.pattern()\n const rest = pattern.rest()\n if (p === GLOBSTAR) {\n results.testGlobstar(e, pattern, rest, absolute)\n } else if (p instanceof RegExp) {\n results.testRegExp(e, p, rest, absolute)\n } else {\n results.testString(e, p, rest, absolute)\n }\n }\n }\n return results\n }\n\n testGlobstar(\n e: Path,\n pattern: Pattern,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (this.dot || !e.name.startsWith('.')) {\n if (!pattern.hasMore()) {\n this.matches.add(e, absolute, false)\n }\n if (e.canReaddir()) {\n // if we're in follow mode or it's not a symlink, just keep\n // testing the same pattern. If there's more after the globstar,\n // then this symlink consumes the globstar. If not, then we can\n // follow at most ONE symlink along the way, so we mark it, which\n // also checks to ensure that it wasn't already marked.\n if (this.follow || !e.isSymbolicLink()) {\n this.subwalks.add(e, pattern)\n } else if (e.isSymbolicLink()) {\n if (rest && pattern.checkFollowGlobstar()) {\n this.subwalks.add(e, rest)\n } else if (pattern.markFollowGlobstar()) {\n this.subwalks.add(e, pattern)\n }\n }\n }\n }\n // if the NEXT thing matches this entry, then also add\n // the rest.\n if (rest) {\n const rp = rest.pattern()\n if (\n typeof rp === 'string' &&\n // dots and empty were handled already\n rp !== '..' &&\n rp !== '' &&\n rp !== '.'\n ) {\n this.testString(e, rp, rest.rest(), absolute)\n } else if (rp === '..') {\n /* c8 ignore start */\n const ep = e.parent || e\n /* c8 ignore stop */\n this.subwalks.add(ep, rest)\n } else if (rp instanceof RegExp) {\n this.testRegExp(e, rp, rest.rest(), absolute)\n }\n }\n }\n\n testRegExp(\n e: Path,\n p: MMRegExp,\n rest: Pattern | null,\n absolute: boolean,\n ) {\n if (!p.test(e.name)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n\n testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n // should never happen?\n if (!e.isNamed(p)) return\n if (!rest) {\n this.matches.add(e, absolute, false)\n } else {\n this.subwalks.add(e, rest)\n }\n }\n}\n","/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed? that'd speed\n// things up a lot. Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n absolute?: boolean\n allowWindowsEscape?: boolean\n cwd?: string | URL\n dot?: boolean\n dotRelative?: boolean\n follow?: boolean\n ignore?: string | string[] | IgnoreLike\n mark?: boolean\n matchBase?: boolean\n // Note: maxDepth here means \"maximum actual Path.depth()\",\n // not \"maximum depth beyond cwd\"\n maxDepth?: number\n nobrace?: boolean\n nocase?: boolean\n nodir?: boolean\n noext?: boolean\n noglobstar?: boolean\n platform?: NodeJS.Platform\n posix?: boolean\n realpath?: boolean\n root?: string\n stat?: boolean\n signal?: AbortSignal\n windowsPathsNoEscape?: boolean\n withFileTypes?: boolean\n includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n withFileTypes?: undefined\n}\n\nexport type Result<O extends GlobWalkerOpts> =\n O extends GWOFileTypesTrue ? Path\n : O extends GWOFileTypesFalse ? string\n : O extends GWOFileTypesUnset ? string\n : Path | string\n\nexport type Matches<O extends GlobWalkerOpts> =\n O extends GWOFileTypesTrue ? Set<Path>\n : O extends GWOFileTypesFalse ? Set<string>\n : O extends GWOFileTypesUnset ? Set<string>\n : Set<Path | string>\n\nexport type MatchStream<O extends GlobWalkerOpts> = Minipass<\n Result<O>,\n Result<O>\n>\n\nconst makeIgnore = (\n ignore: string | string[] | IgnoreLike,\n opts: GlobWalkerOpts,\n): IgnoreLike =>\n typeof ignore === 'string' ? new Ignore([ignore], opts)\n : Array.isArray(ignore) ? new Ignore(ignore, opts)\n : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil<O extends GlobWalkerOpts = GlobWalkerOpts> {\n path: Path\n patterns: Pattern[]\n opts: O\n seen: Set<Path> = new Set<Path>()\n paused: boolean = false\n aborted: boolean = false\n #onResume: (() => any)[] = []\n #ignore?: IgnoreLike\n #sep: '\\\\' | '/'\n signal?: AbortSignal\n maxDepth: number\n includeChildMatches: boolean\n\n constructor(patterns: Pattern[], path: Path, opts: O)\n constructor(patterns: Pattern[], path: Path, opts: O) {\n this.patterns = patterns\n this.path = path\n this.opts = opts\n this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n this.includeChildMatches = opts.includeChildMatches !== false\n if (opts.ignore || !this.includeChildMatches) {\n this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n if (\n !this.includeChildMatches &&\n typeof this.#ignore.add !== 'function'\n ) {\n const m = 'cannot ignore child matches, ignore lacks add() method.'\n throw new Error(m)\n }\n }\n // ignore, always set with maxDepth, but it's optional on the\n // GlobOptions type\n /* c8 ignore start */\n this.maxDepth = opts.maxDepth || Infinity\n /* c8 ignore stop */\n if (opts.signal) {\n this.signal = opts.signal\n this.signal.addEventListener('abort', () => {\n this.#onResume.length = 0\n })\n }\n }\n\n #ignored(path: Path): boolean {\n return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n }\n #childrenIgnored(path: Path): boolean {\n return !!this.#ignore?.childrenIgnored?.(path)\n }\n\n // backpressure mechanism\n pause() {\n this.paused = true\n }\n resume() {\n /* c8 ignore start */\n if (this.signal?.aborted) return\n /* c8 ignore stop */\n this.paused = false\n let fn: (() => any) | undefined = undefined\n while (!this.paused && (fn = this.#onResume.shift())) {\n fn()\n }\n }\n onResume(fn: () => any) {\n if (this.signal?.aborted) return\n /* c8 ignore start */\n if (!this.paused) {\n fn()\n } else {\n /* c8 ignore stop */\n this.#onResume.push(fn)\n }\n }\n\n // do the requisite realpath/stat checking, and return the path\n // to add or undefined to filter it out.\n async matchCheck(e: Path, ifDir: boolean): Promise<Path | undefined> {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || (await e.realpath())\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? await e.lstat() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = await s.realpath()\n /* c8 ignore start */\n if (target && (target.isUnknown() || this.opts.stat)) {\n await target.lstat()\n }\n /* c8 ignore stop */\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n return (\n e &&\n (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n (!ifDir || e.canReaddir()) &&\n (!this.opts.nodir || !e.isDirectory()) &&\n (!this.opts.nodir ||\n !this.opts.follow ||\n !e.isSymbolicLink() ||\n !e.realpathCached()?.isDirectory()) &&\n !this.#ignored(e)\n ) ?\n e\n : undefined\n }\n\n matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n if (ifDir && this.opts.nodir) return undefined\n let rpc: Path | undefined\n if (this.opts.realpath) {\n rpc = e.realpathCached() || e.realpathSync()\n if (!rpc) return undefined\n e = rpc\n }\n const needStat = e.isUnknown() || this.opts.stat\n const s = needStat ? e.lstatSync() : e\n if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n const target = s.realpathSync()\n if (target && (target?.isUnknown() || this.opts.stat)) {\n target.lstatSync()\n }\n }\n return this.matchCheckTest(s, ifDir)\n }\n\n abstract matchEmit(p: Result<O>): void\n abstract matchEmit(p: string | Path): void\n\n matchFinish(e: Path, absolute: boolean) {\n if (this.#ignored(e)) return\n // we know we have an ignore if this is false, but TS doesn't\n if (!this.includeChildMatches && this.#ignore?.add) {\n const ign = `${e.relativePosix()}/**`\n this.#ignore.add(ign)\n }\n const abs =\n this.opts.absolute === undefined ? absolute : this.opts.absolute\n this.seen.add(e)\n const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n // ok, we have what we need!\n if (this.opts.withFileTypes) {\n this.matchEmit(e)\n } else if (abs) {\n const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n this.matchEmit(abs + mark)\n } else {\n const rel = this.opts.posix ? e.relativePosix() : e.relative()\n const pre =\n this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n '.' + this.#sep\n : ''\n this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n }\n }\n\n async match(e: Path, absolute: boolean, ifDir: boolean): Promise<void> {\n const p = await this.matchCheck(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n const p = this.matchCheckSync(e, ifDir)\n if (p) this.matchFinish(p, absolute)\n }\n\n walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const childrenCached = t.readdirCached()\n if (t.calledReaddir())\n this.walkCB3(t, childrenCached, processor, next)\n else {\n t.readdirCB(\n (_, entries) => this.walkCB3(t, entries, processor, next),\n true,\n )\n }\n }\n\n next()\n }\n\n walkCB3(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n tasks++\n this.match(m, absolute, ifDir).then(() => next())\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2(target, patterns, processor.child(), next)\n }\n\n next()\n }\n\n walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n /* c8 ignore start */\n if (this.signal?.aborted) cb()\n /* c8 ignore stop */\n this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n }\n\n walkCB2Sync(\n target: Path,\n patterns: Pattern[],\n processor: Processor,\n cb: () => any,\n ) {\n if (this.#childrenIgnored(target)) return cb()\n if (this.signal?.aborted) cb()\n if (this.paused) {\n this.onResume(() =>\n this.walkCB2Sync(target, patterns, processor, cb),\n )\n return\n }\n processor.processPatterns(target, patterns)\n\n // done processing. all of the above is sync, can be abstracted out.\n // subwalks is a map of paths to the entry filters they need\n // matches is a map of paths to [absolute, ifDir] tuples.\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n\n for (const t of processor.subwalkTargets()) {\n if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n continue\n }\n tasks++\n const children = t.readdirSync()\n this.walkCB3Sync(t, children, processor, next)\n }\n\n next()\n }\n\n walkCB3Sync(\n target: Path,\n entries: Path[],\n processor: Processor,\n cb: () => any,\n ) {\n processor = processor.filterEntries(target, entries)\n\n let tasks = 1\n const next = () => {\n if (--tasks === 0) cb()\n }\n\n for (const [m, absolute, ifDir] of processor.matches.entries()) {\n if (this.#ignored(m)) continue\n this.matchSync(m, absolute, ifDir)\n }\n for (const [target, patterns] of processor.subwalks.entries()) {\n tasks++\n this.walkCB2Sync(target, patterns, processor.child(), next)\n }\n\n next()\n }\n}\n\nexport class GlobWalker<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil<O> {\n matches = new Set<Result<O>>()\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n }\n\n matchEmit(e: Result<O>): void {\n this.matches.add(e)\n }\n\n async walk(): Promise<Set<Result<O>>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n await this.path.lstat()\n }\n await new Promise((res, rej) => {\n this.walkCB(this.path, this.patterns, () => {\n if (this.signal?.aborted) {\n rej(this.signal.reason)\n } else {\n res(this.matches)\n }\n })\n })\n return this.matches\n }\n\n walkSync(): Set<Result<O>> {\n if (this.signal?.aborted) throw this.signal.reason\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n // nothing for the callback to do, because this never pauses\n this.walkCBSync(this.path, this.patterns, () => {\n if (this.signal?.aborted) throw this.signal.reason\n })\n return this.matches\n }\n}\n\nexport class GlobStream<\n O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil<O> {\n results: Minipass<Result<O>, Result<O>>\n\n constructor(patterns: Pattern[], path: Path, opts: O) {\n super(patterns, path, opts)\n this.results = new Minipass<Result<O>, Result<O>>({\n signal: this.signal,\n objectMode: true,\n })\n this.results.on('drain', () => this.resume())\n this.results.on('resume', () => this.resume())\n }\n\n matchEmit(e: Result<O>): void {\n this.results.write(e)\n if (!this.results.flowing) this.pause()\n }\n\n stream(): MatchStream<O> {\n const target = this.path\n if (target.isUnknown()) {\n target.lstat().then(() => {\n this.walkCB(target, this.patterns, () => this.results.end())\n })\n } else {\n this.walkCB(target, this.patterns, () => this.results.end())\n }\n return this.results\n }\n\n streamSync(): MatchStream<O> {\n if (this.path.isUnknown()) {\n this.path.lstatSync()\n }\n this.walkCBSync(this.path, this.patterns, () => this.results.end())\n return this.results\n }\n}\n","import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n FSOption,\n Path,\n PathScurry,\n PathScurryDarwin,\n PathScurryPosix,\n PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude<Minimatch['globParts'], undefined>\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n (\n typeof process === 'object' &&\n process &&\n typeof process.platform === 'string'\n ) ?\n process.platform\n : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n /**\n * Set to `true` to always receive absolute paths for\n * matched files. Set to `false` to always return relative paths.\n *\n * When this option is not set, absolute paths are returned for patterns\n * that are absolute, and otherwise paths are returned that are relative\n * to the `cwd` setting.\n *\n * This does _not_ make an extra system call to get\n * the realpath, it only does string path resolution.\n *\n * Conflicts with {@link withFileTypes}\n */\n absolute?: boolean\n\n /**\n * Set to false to enable {@link windowsPathsNoEscape}\n *\n * @deprecated\n */\n allowWindowsEscape?: boolean\n\n /**\n * The current working directory in which to search. Defaults to\n * `process.cwd()`.\n *\n * May be eiher a string path or a `file://` URL object or string.\n */\n cwd?: string | URL\n\n /**\n * Include `.dot` files in normal matches and `globstar`\n * matches. Note that an explicit dot in a portion of the pattern\n * will always match dot files.\n */\n dot?: boolean\n\n /**\n * Prepend all relative path strings with `./` (or `.\\` on Windows).\n *\n * Without this option, returned relative paths are \"bare\", so instead of\n * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n *\n * Relative patterns starting with `'../'` are not prepended with `./`, even\n * if this option is set.\n */\n dotRelative?: boolean\n\n /**\n * Follow symlinked directories when expanding `**`\n * patterns. This can result in a lot of duplicate references in\n * the presence of cyclic links, and make performance quite bad.\n *\n * By default, a `**` in a pattern will follow 1 symbolic link if\n * it is not the first item in the pattern, or none if it is the\n * first item in the pattern, following the same behavior as Bash.\n */\n follow?: boolean\n\n /**\n * string or string[], or an object with `ignore` and `ignoreChildren`\n * methods.\n *\n * If a string or string[] is provided, then this is treated as a glob\n * pattern or array of glob patterns to exclude from matches. To ignore all\n * children within a directory, as well as the entry itself, append `'/**'`\n * to the ignore pattern.\n *\n * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n * any other settings.\n *\n * If an object is provided that has `ignored(path)` and/or\n * `childrenIgnored(path)` methods, then these methods will be called to\n * determine whether any Path is a match or if its children should be\n * traversed, respectively.\n */\n ignore?: string | string[] | IgnoreLike\n\n /**\n * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n * effect if {@link nobrace} is set.\n *\n * Only has effect on the {@link hasMagic} function.\n */\n magicalBraces?: boolean\n\n /**\n * Add a `/` character to directory matches. Note that this requires\n * additional stat calls in some cases.\n */\n mark?: boolean\n\n /**\n * Perform a basename-only match if the pattern does not contain any slash\n * characters. That is, `*.js` would be treated as equivalent to\n * `**\\/*.js`, matching all js files in all directories.\n */\n matchBase?: boolean\n\n /**\n * Limit the directory traversal to a given depth below the cwd.\n * Note that this does NOT prevent traversal to sibling folders,\n * root patterns, and so on. It only limits the maximum folder depth\n * that the walk will descend, relative to the cwd.\n */\n maxDepth?: number\n\n /**\n * Do not expand `{a,b}` and `{1..3}` brace sets.\n */\n nobrace?: boolean\n\n /**\n * Perform a case-insensitive match. This defaults to `true` on macOS and\n * Windows systems, and `false` on all others.\n *\n * **Note** `nocase` should only be explicitly set when it is\n * known that the filesystem's case sensitivity differs from the\n * platform default. If set `true` on case-sensitive file\n * systems, or `false` on case-insensitive file systems, then the\n * walk may return more or less results than expected.\n */\n nocase?: boolean\n\n /**\n * Do not match directories, only files. (Note: to match\n * _only_ directories, put a `/` at the end of the pattern.)\n */\n nodir?: boolean\n\n /**\n * Do not match \"extglob\" patterns such as `+(a|b)`.\n */\n noext?: boolean\n\n /**\n * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n * `*` instead.)\n *\n * Conflicts with {@link matchBase}\n */\n noglobstar?: boolean\n\n /**\n * Defaults to value of `process.platform` if available, or `'linux'` if\n * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n * behavior.\n */\n platform?: NodeJS.Platform\n\n /**\n * Set to true to call `fs.realpath` on all of the\n * results. In the case of an entry that cannot be resolved, the\n * entry is omitted. This incurs a slight performance penalty, of\n * course, because of the added system calls.\n */\n realpath?: boolean\n\n /**\n *\n * A string path resolved against the `cwd` option, which\n * is used as the starting point for absolute patterns that start\n * with `/`, (but not drive letters or UNC paths on Windows).\n *\n * Note that this _doesn't_ necessarily limit the walk to the\n * `root` directory, and doesn't affect the cwd starting point for\n * non-absolute patterns. A pattern containing `..` will still be\n * able to traverse out of the root directory, if it is not an\n * actual root directory on the filesystem, and any non-absolute\n * patterns will be matched in the `cwd`. For example, the\n * pattern `/../*` with `{root:'/some/path'}` will return all\n * files in `/some`, not all files in `/some/path`. The pattern\n * `*` with `{root:'/some/path'}` will return all the entries in\n * the cwd, not the entries in `/some/path`.\n *\n * To start absolute and non-absolute patterns in the same\n * path, you can use `{root:''}`. However, be aware that on\n * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n * _always_ start in the `x:/` or `//host/share` directory,\n * regardless of the `root` setting.\n */\n root?: string\n\n /**\n * A [PathScurry](http://npm.im/path-scurry) object used\n * to traverse the file system. If the `nocase` option is set\n * explicitly, then any provided `scurry` object must match this\n * setting.\n */\n scurry?: PathScurry\n\n /**\n * Call `lstat()` on all entries, whether required or not to determine\n * if it's a valid match. When used with {@link withFileTypes}, this means\n * that matches will include data such as modified time, permissions, and\n * so on. Note that this will incur a performance cost due to the added\n * system calls.\n */\n stat?: boolean\n\n /**\n * An AbortSignal which will cancel the Glob walk when\n * triggered.\n */\n signal?: AbortSignal\n\n /**\n * Use `\\\\` as a path separator _only_, and\n * _never_ as an escape character. If set, all `\\\\` characters are\n * replaced with `/` in the pattern.\n *\n * Note that this makes it **impossible** to match against paths\n * containing literal glob pattern characters, but allows matching\n * with patterns constructed using `path.join()` and\n * `path.resolve()` on Windows platforms, mimicking the (buggy!)\n * behavior of Glob v7 and before on Windows. Please use with\n * caution, and be mindful of [the caveat below about Windows\n * paths](#windows). (For legacy reasons, this is also set if\n * `allowWindowsEscape` is set to the exact value `false`.)\n */\n windowsPathsNoEscape?: boolean\n\n /**\n * Return [PathScurry](http://npm.im/path-scurry)\n * `Path` objects instead of strings. These are similar to a\n * NodeJS `Dirent` object, but with additional methods and\n * properties.\n *\n * Conflicts with {@link absolute}\n */\n withFileTypes?: boolean\n\n /**\n * An fs implementation to override some or all of the defaults. See\n * http://npm.im/path-scurry for details about what can be overridden.\n */\n fs?: FSOption\n\n /**\n * Just passed along to Minimatch. Note that this makes all pattern\n * matching operations slower and *extremely* noisy.\n */\n debug?: boolean\n\n /**\n * Return `/` delimited paths, even on Windows.\n *\n * On posix systems, this has no effect. But, on Windows, it means that\n * paths will be `/` delimited, and absolute paths will be their full\n * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n * `'//?/C:/foo/bar'`\n */\n posix?: boolean\n\n /**\n * Do not match any children of any matches. For example, the pattern\n * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n *\n * This is especially useful for cases like \"find all `node_modules`\n * folders, but not the ones in `node_modules`\".\n *\n * In order to support this, the `Ignore` implementation must support an\n * `add(pattern: string)` method. If using the default `Ignore` class, then\n * this is fine, but if this is set to `false`, and a custom `Ignore` is\n * provided that does not have an `add()` method, then it will throw an\n * error.\n *\n * **Caveat** It *only* ignores matches that would be a descendant of a\n * previous match, and only if that descendant is matched *after* the\n * ancestor is encountered. Since the file system walk happens in\n * indeterminate order, it's possible that a match will already be added\n * before its ancestor, if multiple or braced patterns are used.\n *\n * For example:\n *\n * ```ts\n * const results = await glob([\n * // likely to match first, since it's just a stat\n * 'a/b/c/d/e/f',\n *\n * // this pattern is more complicated! It must to various readdir()\n * // calls and test the results against a regular expression, and that\n * // is certainly going to take a little bit longer.\n * //\n * // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n * // late to ignore a/b/c/d/e/f, because it's already been emitted.\n * 'a/[bdf]/?/[a-z]/*',\n * ], { includeChildMatches: false })\n * ```\n *\n * It's best to only set this to `false` if you can be reasonably sure that\n * no components of the pattern will potentially match one another's file\n * system descendants, or if the occasional included child entry will not\n * cause problems.\n *\n * @default true\n */\n includeChildMatches?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n withFileTypes: true\n // string options not relevant if returning Path objects.\n absolute?: undefined\n mark?: undefined\n posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n withFileTypes?: undefined\n}\n\nexport type Result<Opts> =\n Opts extends GlobOptionsWithFileTypesTrue ? Path\n : Opts extends GlobOptionsWithFileTypesFalse ? string\n : Opts extends GlobOptionsWithFileTypesUnset ? string\n : string | Path\nexport type Results<Opts> = Result<Opts>[]\n\nexport type FileTypes<Opts> =\n Opts extends GlobOptionsWithFileTypesTrue ? true\n : Opts extends GlobOptionsWithFileTypesFalse ? false\n : Opts extends GlobOptionsWithFileTypesUnset ? false\n : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob<Opts extends GlobOptions> implements GlobOptions {\n absolute?: boolean\n cwd: string\n root?: string\n dot: boolean\n dotRelative: boolean\n follow: boolean\n ignore?: string | string[] | IgnoreLike\n magicalBraces: boolean\n mark?: boolean\n matchBase: boolean\n maxDepth: number\n nobrace: boolean\n nocase: boolean\n nodir: boolean\n noext: boolean\n noglobstar: boolean\n pattern: string[]\n platform: NodeJS.Platform\n realpath: boolean\n scurry: PathScurry\n stat: boolean\n signal?: AbortSignal\n windowsPathsNoEscape: boolean\n withFileTypes: FileTypes<Opts>\n includeChildMatches: boolean\n\n /**\n * The options provided to the constructor.\n */\n opts: Opts\n\n /**\n * An array of parsed immutable {@link Pattern} objects.\n */\n patterns: Pattern[]\n\n /**\n * All options are stored as properties on the `Glob` object.\n *\n * See {@link GlobOptions} for full options descriptions.\n *\n * Note that a previous `Glob` object can be passed as the\n * `GlobOptions` to another `Glob` instantiation to re-use settings\n * and caches with a new pattern.\n *\n * Traversal functions can be called multiple times to run the walk\n * again.\n */\n constructor(pattern: string | string[], opts: Opts) {\n /* c8 ignore start */\n if (!opts) throw new TypeError('glob options required')\n /* c8 ignore stop */\n this.withFileTypes = !!opts.withFileTypes as FileTypes<Opts>\n this.signal = opts.signal\n this.follow = !!opts.follow\n this.dot = !!opts.dot\n this.dotRelative = !!opts.dotRelative\n this.nodir = !!opts.nodir\n this.mark = !!opts.mark\n if (!opts.cwd) {\n this.cwd = ''\n } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n opts.cwd = fileURLToPath(opts.cwd)\n }\n this.cwd = opts.cwd || ''\n this.root = opts.root\n this.magicalBraces = !!opts.magicalBraces\n this.nobrace = !!opts.nobrace\n this.noext = !!opts.noext\n this.realpath = !!opts.realpath\n this.absolute = opts.absolute\n this.includeChildMatches = opts.includeChildMatches !== false\n\n this.noglobstar = !!opts.noglobstar\n this.matchBase = !!opts.matchBase\n this.maxDepth =\n typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n this.stat = !!opts.stat\n this.ignore = opts.ignore\n\n if (this.withFileTypes && this.absolute !== undefined) {\n throw new Error('cannot set absolute and withFileTypes:true')\n }\n\n if (typeof pattern === 'string') {\n pattern = [pattern]\n }\n\n this.windowsPathsNoEscape =\n !!opts.windowsPathsNoEscape ||\n (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n false\n\n if (this.windowsPathsNoEscape) {\n pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n }\n\n if (this.matchBase) {\n if (opts.noglobstar) {\n throw new TypeError('base matching requires globstar')\n }\n pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n }\n\n this.pattern = pattern\n\n this.platform = opts.platform || defaultPlatform\n this.opts = { ...opts, platform: this.platform }\n if (opts.scurry) {\n this.scurry = opts.scurry\n if (\n opts.nocase !== undefined &&\n opts.nocase !== opts.scurry.nocase\n ) {\n throw new Error('nocase option contradicts provided scurry option')\n }\n } else {\n const Scurry =\n opts.platform === 'win32' ? PathScurryWin32\n : opts.platform === 'darwin' ? PathScurryDarwin\n : opts.platform ? PathScurryPosix\n : PathScurry\n this.scurry = new Scurry(this.cwd, {\n nocase: opts.nocase,\n fs: opts.fs,\n })\n }\n this.nocase = this.scurry.nocase\n\n // If you do nocase:true on a case-sensitive file system, then\n // we need to use regexps instead of strings for non-magic\n // path portions, because statting `aBc` won't return results\n // for the file `AbC` for example.\n const nocaseMagicOnly =\n this.platform === 'darwin' || this.platform === 'win32'\n\n const mmo: MinimatchOptions = {\n // default nocase based on platform\n ...opts,\n dot: this.dot,\n matchBase: this.matchBase,\n nobrace: this.nobrace,\n nocase: this.nocase,\n nocaseMagicOnly,\n nocomment: true,\n noext: this.noext,\n nonegate: true,\n optimizationLevel: 2,\n platform: this.platform,\n windowsPathsNoEscape: this.windowsPathsNoEscape,\n debug: !!this.opts.debug,\n }\n\n const mms = this.pattern.map(p => new Minimatch(p, mmo))\n const [matchSet, globParts] = mms.reduce(\n (set: [MatchSet, GlobParts], m) => {\n set[0].push(...m.set)\n set[1].push(...m.globParts)\n return set\n },\n [[], []],\n )\n this.patterns = matchSet.map((set, i) => {\n const g = globParts[i]\n /* c8 ignore start */\n if (!g) throw new Error('invalid pattern object')\n /* c8 ignore stop */\n return new Pattern(set, g, 0, this.platform)\n })\n }\n\n /**\n * Returns a Promise that resolves to the results array.\n */\n async walk(): Promise<Results<Opts>>\n async walk(): Promise<(string | Path)[]> {\n // Walkers always return array of Path objects, so we just have to\n // coerce them into the right shape. It will have already called\n // realpath() if the option was set to do so, so we know that's cached.\n // start out knowing the cwd, at least\n return [\n ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walk()),\n ]\n }\n\n /**\n * synchronous {@link Glob.walk}\n */\n walkSync(): Results<Opts>\n walkSync(): (string | Path)[] {\n return [\n ...new GlobWalker(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).walkSync(),\n ]\n }\n\n /**\n * Stream results asynchronously.\n */\n stream(): Minipass<Result<Opts>, Result<Opts>>\n stream(): Minipass<string | Path, string | Path> {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).stream()\n }\n\n /**\n * Stream results synchronously.\n */\n streamSync(): Minipass<Result<Opts>, Result<Opts>>\n streamSync(): Minipass<string | Path, string | Path> {\n return new GlobStream(this.patterns, this.scurry.cwd, {\n ...this.opts,\n maxDepth:\n this.maxDepth !== Infinity ?\n this.maxDepth + this.scurry.cwd.depth()\n : Infinity,\n platform: this.platform,\n nocase: this.nocase,\n includeChildMatches: this.includeChildMatches,\n }).streamSync()\n }\n\n /**\n * Default sync iteration function. Returns a Generator that\n * iterates over the results.\n */\n iterateSync(): Generator<Result<Opts>, void, void> {\n return this.streamSync()[Symbol.iterator]()\n }\n [Symbol.iterator]() {\n return this.iterateSync()\n }\n\n /**\n * Default async iteration function. Returns an AsyncGenerator that\n * iterates over the results.\n */\n iterate(): AsyncGenerator<Result<Opts>, void, void> {\n return this.stream()[Symbol.asyncIterator]()\n }\n [Symbol.asyncIterator]() {\n return this.iterate()\n }\n}\n","import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n pattern: string | string[],\n options: GlobOptions = {},\n): boolean => {\n if (!Array.isArray(pattern)) {\n pattern = [pattern]\n }\n for (const p of pattern) {\n if (new Minimatch(p, options).hasMagic()) return true\n }\n return false\n}\n","import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n FSOption,\n Path,\n WalkOptions,\n WalkOptionsWithFileTypesTrue,\n WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n GlobOptions,\n GlobOptionsWithFileTypesFalse,\n GlobOptionsWithFileTypesTrue,\n GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass<Path, Path>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesUnset,\n): Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass<Path, Path> | Minipass<string, string>\nexport function globStreamSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Minipass<Path, Path>\nexport function globStream(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions,\n): Minipass<Path, Path> | Minipass<string, string>\nexport function globStream(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise<string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Promise<Path[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Promise<string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions,\n): Promise<Path[] | string[]>\nasync function glob_(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): Generator<Path, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions,\n): Generator<Path, void, void> | Generator<string, void, void>\nexport function globIterateSync(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n pattern: string | string[],\n options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator<Path, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions,\n): AsyncGenerator<Path, void, void> | AsyncGenerator<string, void, void>\nexport function globIterate(\n pattern: string | string[],\n options: GlobOptions = {},\n) {\n return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n stream: globStreamSync,\n iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n glob: glob_,\n globSync,\n sync,\n globStream,\n stream,\n globStreamSync,\n streamSync,\n globIterate,\n iterate,\n globIterateSync,\n iterateSync,\n Glob,\n hasMagic,\n escape,\n unescape,\n})\nglob.glob = glob\n","// External imports\nimport { readFileSync } from \"fs\";\nimport { join } from \"path\";\n\nimport { sync } from \"glob\";\n\n// Internal imports\nimport logger from \"@utils/logger\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\n\nconst consola = logger.withTag(\"listChromeProfiles\");\n\n/**\n * Lists all Chrome profile paths that contain cookie files\n * @internal\n * @returns An array of absolute paths to Chrome cookie files\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome cookie file paths\n * const cookiePaths = listChromeProfilePaths();\n * // Returns: [\n * // '/Users/name/Library/Application Support/Chrome/Profile 1/Cookies',\n * // '/Users/name/Library/Application Support/Chrome/Profile 2/Cookies'\n * // ]\n *\n * // Handle errors\n * try {\n * const paths = listChromeProfilePaths();\n * } catch (error) {\n * console.error('Failed to access Chrome profiles:', error);\n * }\n * ```\n */\nexport function listChromeProfilePaths(): string[] {\n const files: string[] = sync(`./**/Cookies`, {\n cwd: chromeApplicationSupport,\n absolute: true,\n });\n\n consola.debug(\"Found cookie files:\", files);\n return files;\n}\n\n/**\n * Chrome Local State file structure\n * @internal\n */\ninterface ChromeLocalState {\n profile: {\n info_cache: Record<string, ChromeProfileInfo>;\n };\n}\n\n/**\n * Chrome profile information structure\n * @property {string} name - The name of the profile\n * @property {number} active_time - Unix timestamp of last profile activity\n * @property {string} account_id - Unique identifier for the Chrome profile\n * @property {Record<string, unknown>} accountcapabilities - Account feature flags\n * @property {string} email - User's email address\n * @property {string} full_name - User's full name\n * @property {boolean} is_using_default_avatar - Whether using default profile picture\n * @property {boolean} is_using_default_name - Whether using default profile name\n * @property {string} last_downloaded_gaia_picture_url_with_size - Profile picture URL\n * @property {string} local_auth_credentials - Authentication credentials\n * @property {string} shortcut_name - Profile shortcut name\n * @property {string} user_name - Username associated with profile\n */\ninterface ChromeProfileInfo {\n /** The name of the profile */\n name: string;\n /** Unix timestamp of last profile activity */\n active_time: number;\n /** Unique identifier for the Chrome profile */\n account_id: string;\n /** Account feature flags */\n accountcapabilities: Record<string, unknown>;\n /** User's email address */\n email: string;\n /** User's full name */\n full_name: string;\n /** Whether using default profile picture */\n is_using_default_avatar: boolean;\n /** Whether using default profile name */\n is_using_default_name: boolean;\n /** Profile picture URL */\n last_downloaded_gaia_picture_url_with_size: string;\n /** Authentication credentials */\n local_auth_credentials: string;\n /** Profile shortcut name */\n shortcut_name: string;\n /** Username associated with profile */\n user_name: string;\n}\n\n/**\n * Lists all Chrome profiles and their associated information\n * @internal\n * @returns An array of Chrome profile information objects. Returns empty array if profiles cannot be read\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome profiles\n * const profiles = listChromeProfiles();\n * // Returns: [\n * // {\n * // name: \"Default\",\n * // email: \"user@example.com\",\n * // full_name: \"John Doe\",\n * // ...\n * // },\n * // ...\n * // ]\n *\n * // Handle empty or error case\n * const profiles = listChromeProfiles();\n * if (profiles.length === 0) {\n * console.log('No Chrome profiles found or error occurred');\n * }\n * ```\n */\nexport function listChromeProfiles(): ChromeProfileInfo[] {\n try {\n const localStatePath = join(chromeApplicationSupport, \"Local State\");\n const localState = JSON.parse(\n readFileSync(localStatePath, \"utf8\"),\n ) as ChromeLocalState;\n return Object.values(localState.profile.info_cache);\n } catch (error) {\n if (error instanceof Error) {\n consola.error(\"Failed to read Chrome profiles:\", error.message);\n } else {\n consola.error(\"Failed to read Chrome profiles: Unknown error\");\n }\n return [];\n }\n}\n","// External imports\nimport { createDecipheriv, pbkdf2 } from \"crypto\";\n\nimport { memoize } from \"lodash-es\";\n\n/**\n * Removes the v10 prefix from the encrypted value if present\n * @param value - The encrypted value\n * @returns The value without the v10 prefix\n */\nconst removeV10Prefix = memoize(\n (value: Buffer): Buffer => {\n if (\n value.length >= 3 &&\n value[0] === 0x76 && // 'v'\n value[1] === 0x31 && // '1'\n value[2] === 0x30\n ) {\n // '0'\n return value.slice(3);\n }\n return value;\n },\n (value: Buffer) => value.toString(\"hex\"),\n);\n\n/**\n * Removes PKCS7 padding from the decrypted value\n * @param decrypted - The decrypted buffer\n * @returns The buffer without padding\n */\nconst removePadding = memoize(\n (decrypted: Buffer): Buffer => {\n const padding = decrypted[decrypted.length - 1];\n if (padding && padding <= 16) {\n return decrypted.slice(0, -padding);\n }\n return decrypted;\n },\n (decrypted: Buffer) => decrypted.toString(\"hex\"),\n);\n\n/**\n * Extracts the actual value from the decoded string by removing Chrome's prefixes\n * @param decodedString - The decoded string to clean up\n * @returns The cleaned up value\n */\nfunction extractValue(decodedString: string): string {\n const cleanupPatterns = [\n /.*?0t(.+)$/, // Pattern ending in \"0t\" followed by value\n /.*?1e`(.+)$/, // Pattern ending in \"1e`\" followed by value\n /.*?[`'](.+)$/, // Any backtick or quote followed by value\n /[^\\x20-\\x7E]*([\\x20-\\x7E].+)$/, // Non-printable chars followed by printable chars\n ];\n\n for (const pattern of cleanupPatterns) {\n const match = decodedString.match(pattern);\n const value = match?.[1] ?? \"\";\n if (value.length > 0) {\n return value;\n }\n }\n return decodedString;\n}\n\n/**\n * Decrypts Chrome's encrypted cookie values\n * @param encryptedValue - The encrypted cookie value as a Buffer\n * @param password - The Chrome encryption password\n * @returns A promise that resolves to the decrypted cookie value\n * @throws {Error} If decryption fails\n * @example\n */\nexport async function decrypt(\n encryptedValue: Buffer,\n password: string,\n): Promise<string> {\n if (typeof password !== \"string\") {\n throw new Error(\"password must be a string\");\n }\n if (!Buffer.isBuffer(encryptedValue)) {\n throw new Error(\"encryptedData must be a Buffer\");\n }\n\n return new Promise((resolve, reject) => {\n pbkdf2(password, \"saltysalt\", 1003, 16, \"sha1\", (error, key) => {\n try {\n if (error) {\n reject(new Error(\"Failed to derive key: \" + error.message));\n return;\n }\n\n const value = removeV10Prefix(encryptedValue);\n if (value.length % 16 !== 0) {\n reject(new Error(\"Encrypted data length is not a multiple of 16\"));\n return;\n }\n\n // Chrome's encryption parameters\n const iv = Buffer.alloc(16, \" \"); // 16 spaces\n const decipher = createDecipheriv(\"aes-128-cbc\", key, iv);\n decipher.setAutoPadding(false);\n\n // Decrypt the value\n let decrypted = decipher.update(value);\n try {\n decipher.final();\n } catch (e) {\n reject(\n new Error(\"Failed to finalize decryption: \" + (e as Error).message),\n );\n return;\n }\n\n decrypted = removePadding(decrypted);\n const decodedString = decrypted.toString(\"utf8\");\n resolve(extractValue(decodedString));\n } catch (e) {\n reject(new Error(\"Decryption failed: \" + (e as Error).message));\n }\n });\n });\n}\n","// External imports\nimport { exec, ExecOptions } from \"child_process\";\nimport { promisify } from \"util\";\n\n// Internal imports\nimport { logError } from \"@utils/logHelpers\";\n\nconst execPromise = promisify(exec);\n\n/**\n * Custom error class for command execution failures.\n * @property {string} command - The command that failed to execute\n * @property {Error} [originalError] - The underlying error that caused the failure\n * @throws CommandExecutionError Always throws with appropriate error context\n * @example\n * ```typescript\n * throw new CommandExecutionError(\n * 'Command timed out',\n * 'git status',\n * originalError\n * );\n * ```\n */\nclass CommandExecutionError extends Error {\n public constructor(\n message: string,\n public readonly command: string,\n public readonly originalError?: Error,\n ) {\n super(message);\n this.name = \"CommandExecutionError\";\n }\n}\n\n/**\n * Handles execution errors and throws appropriate CommandExecutionError.\n * @internal\n * @param error - The error that occurred during command execution\n * @param command - The command that was being executed when the error occurred\n * @throws CommandExecutionError Always throws with appropriate error context\n * @example\n * ```typescript\n * try {\n * await execPromise('invalid-command');\n * } catch (error) {\n * handleExecutionError(error, 'invalid-command');\n * }\n * ```\n */\nfunction handleExecutionError(error: unknown, command: string): never {\n if (error instanceof CommandExecutionError) {\n logError(\"Command execution failed\", error, {\n command: error.command,\n originalError: error.originalError,\n });\n throw error;\n }\n\n if (error instanceof Error) {\n const commandError = new CommandExecutionError(\n error.message,\n command,\n error,\n );\n logError(\"Failed to execute command\", error, {\n command,\n stack: error.stack,\n });\n throw commandError;\n }\n\n // Handle unknown error types\n const commandError = new CommandExecutionError(\n \"Unknown error occurred during command execution\",\n command,\n );\n logError(\"Failed to execute command\", null, {\n error,\n command,\n });\n throw commandError;\n}\n\n/**\n * Executes a shell command asynchronously and returns its output as a string.\n * @param command - The shell command to execute\n * @param options - Optional execution options that override the defaults\n * @returns A promise that resolves to the trimmed command output\n * @throws CommandExecutionError if the command returns an empty result, times out, or fails to execute\n * @example\n * ```typescript\n * // Basic usage\n * const gitStatus = await execSimple('git status');\n *\n * // With custom timeout\n * const output = await execSimple('long-running-command', { timeout: 60000 });\n *\n * // Error handling\n * try {\n * const result = await execSimple('git push');\n * } catch (error) {\n * if (error instanceof CommandExecutionError) {\n * console.error('Push failed:', error.message);\n * }\n * }\n * ```\n */\nexport async function execSimple(\n command: string,\n options: Partial<ExecOptions> = {},\n): Promise<string> {\n if (!command || typeof command !== \"string\") {\n throw new CommandExecutionError(\n \"Command must be a non-empty string\",\n command,\n );\n }\n\n const defaultOptions = {\n encoding: \"utf8\" as BufferEncoding,\n maxBuffer: 5 * 1024 * 1024, // 5MB buffer\n timeout: 30000, // 30 second timeout\n };\n\n try {\n const { stdout, stderr } = await execPromise(command, {\n ...defaultOptions,\n ...options,\n });\n const result = stdout.trim();\n\n if (!result) {\n if (stderr) {\n throw new CommandExecutionError(\n `Command failed with stderr: ${stderr}`,\n command,\n );\n }\n throw new CommandExecutionError(\"Command returned empty result\", command);\n }\n\n return result;\n } catch (error) {\n handleExecutionError(error, command);\n }\n}\n","import { memoize } from \"lodash-es\";\n\nimport { execSimple } from \"@utils/execSimple\";\n\n/**\n * Retrieves the Chrome Safe Storage password from the macOS keychain\n * @returns A promise that resolves to the Chrome Safe Storage password\n * @throws {Error} If the password cannot be retrieved from the keychain\n */\nconst getChromeSafeStoragePassword = async (): Promise<string> => {\n const command = 'security find-generic-password -w -s \"Chrome Safe Storage\"';\n return execSimple(command);\n};\n\n/**\n * Memoized version of getChromeSafeStoragePassword that caches the result\n * to avoid repeated keychain queries\n * @returns A promise that resolves to the Chrome Safe Storage password\n * @throws {Error} If the password cannot be retrieved from the keychain\n * @example\n */\nexport const getChromePassword: () => Promise<string> = memoize(\n getChromeSafeStoragePassword,\n);\n","import { memoize } from \"lodash-es\";\n\nimport { logError, logDebug } from \"@utils/logHelpers\";\n\n/**\n * Retrieves the Chrome password for decrypting cookies\n * This is only supported on macOS\n * @returns A promise that resolves to the Chrome password\n * @throws {Error} If the platform is not macOS or if password retrieval fails\n * @example\n */\nexport const getChromePassword: () => Promise<string> = memoize(async () => {\n if (process.platform !== \"darwin\") {\n logError(\n \"Chrome password retrieval failed\",\n new Error(\"This only works on macOS\"),\n {\n platform: process.platform,\n },\n );\n throw new Error(\"This only works on macOS\");\n }\n\n try {\n const { getChromePassword: getMacOSPassword } = await import(\n \"./macos/getChromePassword\"\n );\n const password = await getMacOSPassword();\n logDebug(\"ChromePassword\", \"Retrieved password successfully\", {\n platform: \"macOS\",\n });\n return password;\n } catch (error) {\n logError(\"Chrome password retrieval failed\", error, { platform: \"macOS\" });\n throw error;\n }\n});\n","import { createTaggedLogger, logError } from \"@utils/logHelpers\";\n\nimport {\n BrowserName,\n CookieQueryStrategy,\n CookieRow,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { getEncryptedChromeCookie } from \"../getEncryptedChromeCookie\";\nimport { listChromeProfilePaths } from \"../listChromeProfiles\";\n\nimport { decrypt } from \"./decrypt\";\nimport { getChromePassword } from \"./getChromePassword\";\n\ninterface DecryptionContext {\n file: string;\n password: string;\n}\n\nfunction getExpiryDate(expiry: number | undefined | null): Date | \"Infinity\" {\n if (typeof expiry !== \"number\" || expiry <= 0) {\n return \"Infinity\";\n }\n return new Date(expiry);\n}\n\nfunction createExportedCookie(\n domain: string,\n name: string,\n value: string,\n expiry: number | undefined | null,\n file: string,\n decrypted: boolean,\n): ExportedCookie {\n return {\n domain,\n name,\n value,\n expiry: getExpiryDate(expiry),\n meta: {\n file,\n browser: \"Chrome\",\n decrypted,\n },\n };\n}\n\n/**\n * Strategy for querying cookies from Chrome browser\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ChromeCookieQueryStrategy implements CookieQueryStrategy {\n private readonly logger = createTaggedLogger(\"ChromeCookieQueryStrategy\");\n\n /**\n * The browser name for this strategy\n */\n public readonly browserName: BrowserName = \"Chrome\";\n\n /**\n * Queries cookies from Chrome's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @returns A promise that resolves to an array of exported cookies\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * console.log(cookies);\n * ```\n */\n public async queryCookies(\n name: string,\n domain: string,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\"Querying cookies\", { name, domain });\n\n if (process.platform !== \"darwin\") {\n this.logger.warn(\"Platform not supported\", {\n platform: process.platform,\n });\n return [];\n }\n\n const cookieFiles = listChromeProfilePaths();\n if (cookieFiles.length === 0) {\n this.logger.warn(\"No Chrome cookie files found\");\n return [];\n }\n\n const password = await getChromePassword();\n const results = await Promise.all(\n cookieFiles.map((file) =>\n this.processFile(file, name, domain, password),\n ),\n );\n\n return results.flat();\n } catch (error) {\n if (error instanceof Error) {\n logError(\"Failed to query cookies\", error, { name, domain });\n } else {\n logError(\"Failed to query cookies\", new Error(String(error)), {\n name,\n domain,\n });\n }\n return [];\n }\n }\n\n private async processFile(\n file: string,\n name: string,\n domain: string,\n password: string,\n ): Promise<ExportedCookie[]> {\n try {\n const encryptedCookies = await getEncryptedChromeCookie({\n name,\n domain,\n file,\n });\n\n const context: DecryptionContext = { file, password };\n const results = await Promise.allSettled(\n encryptedCookies.map((cookie) => this.processCookie(cookie, context)),\n );\n\n return results\n .map((result) => (result.status === \"fulfilled\" ? result.value : null))\n .filter((cookie): cookie is ExportedCookie => cookie !== null);\n } catch (error) {\n if (error instanceof Error) {\n this.logger.error(\"Failed to process cookie file\", { error, file });\n } else {\n this.logger.error(\"Failed to process cookie file\", {\n error: String(error),\n file,\n });\n }\n return [];\n }\n }\n\n private async processCookie(\n cookie: CookieRow,\n context: DecryptionContext,\n ): Promise<ExportedCookie> {\n try {\n const value = Buffer.isBuffer(cookie.value)\n ? cookie.value\n : Buffer.from(String(cookie.value));\n\n const decryptedValue = await decrypt(value, context.password);\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n decryptedValue,\n cookie.expiry,\n context.file,\n true,\n );\n } catch (error) {\n if (error instanceof Error) {\n this.logger.warn(\"Failed to decrypt cookie\", { error });\n } else {\n this.logger.warn(\"Failed to decrypt cookie\", { error: String(error) });\n }\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n cookie.value.toString(\"utf-8\"),\n cookie.expiry,\n context.file,\n false,\n );\n }\n }\n}\n","import { join } from \"path\";\n\nimport { sync } from \"glob\";\n\nimport { logDebug, logWarn } from \"@utils/logHelpers\";\n\nimport {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { querySqliteThenTransform } from \"../QuerySqliteThenTransform\";\n\ninterface FirefoxCookieRow {\n name: string;\n value: string;\n domain: string;\n expiry: number;\n}\n\n/**\n * Find all Firefox cookie database files\n * @returns An array of file paths to Firefox cookie databases\n */\nfunction findFirefoxCookieFiles(): string[] {\n const files: string[] = [];\n const homedir = process.env.HOME;\n\n if (typeof homedir !== \"string\" || homedir.length === 0) {\n logWarn(\"FirefoxCookieQuery\", \"HOME environment variable not set\");\n return files;\n }\n\n const patterns = [\n join(\n homedir,\n \"Library/Application Support/Firefox/Profiles/*/cookies.sqlite\",\n ),\n join(homedir, \".mozilla/firefox/*/cookies.sqlite\"),\n ];\n\n for (const pattern of patterns) {\n const matches = sync(pattern);\n files.push(...matches);\n }\n\n logDebug(\"FirefoxCookieQuery\", \"Found Firefox cookie files\", { files });\n return files;\n}\n\n/**\n * Strategy for querying cookies from Firefox browser\n * @example\n */\nexport class FirefoxCookieQueryStrategy implements CookieQueryStrategy {\n /**\n *\n */\n public readonly browserName: BrowserName = \"Firefox\";\n\n /**\n * Queries cookies from Firefox's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @returns A promise that resolves to an array of exported cookies\n */\n public async queryCookies(\n name: string,\n domain: string,\n ): Promise<ExportedCookie[]> {\n const files = findFirefoxCookieFiles();\n const results: ExportedCookie[] = [];\n\n for (const file of files) {\n try {\n const cookies = await querySqliteThenTransform<\n FirefoxCookieRow,\n ExportedCookie\n >({\n file,\n sql: \"SELECT name, value, host as domain, expiry FROM moz_cookies WHERE name = ? AND host LIKE ?\",\n params: [name, `%${domain}%`],\n rowTransform: (row) => ({\n name: row.name,\n value: row.value,\n domain: row.domain,\n expiry: row.expiry > 0 ? new Date(row.expiry * 1000) : \"Infinity\",\n meta: {\n file,\n browser: \"Firefox\",\n decrypted: false,\n },\n }),\n });\n\n results.push(...cookies);\n } catch (error) {\n if (error instanceof Error) {\n logWarn(\n \"FirefoxCookieQuery\",\n `Error reading Firefox cookie file ${file}`,\n { error: error.message },\n );\n } else {\n logWarn(\n \"FirefoxCookieQuery\",\n `Error reading Firefox cookie file ${file}`,\n );\n }\n }\n }\n\n return results;\n }\n}\n","import destr from \"destr\";\nimport { z } from \"zod\";\n\n/**\n * Zod schema for cookie domain validation.\n * Enforces standard cookie domain rules.\n * @example\n * ```typescript\n * // Valid domains\n * CookieDomainSchema.parse(\"example.com\"); // OK\n * CookieDomainSchema.parse(\".example.com\"); // OK - leading dot is valid\n * CookieDomainSchema.parse(\"sub.example.com\"); // OK\n *\n * // Invalid domains\n * CookieDomainSchema.parse(\"\"); // Error: Domain cannot be empty\n * CookieDomainSchema.parse(\"invalid domain\"); // Error: Invalid domain format\n * ```\n */\nexport const CookieDomainSchema = z\n .string()\n .trim()\n .min(1, \"Domain cannot be empty\")\n .refine(\n (domain) =>\n /^\\.?[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(\n domain,\n ),\n \"Invalid domain format\",\n );\n\n/**\n * Zod schema for cookie name validation.\n * Enforces standard cookie name rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid names\n * CookieNameSchema.parse(\"session\"); // OK\n * CookieNameSchema.parse(\"auth_token\"); // OK\n * CookieNameSchema.parse(\"user-preference\"); // OK\n *\n * // Invalid names\n * CookieNameSchema.parse(\"\"); // Error: Cookie name cannot be empty\n * CookieNameSchema.parse(\"session;\"); // Error: Invalid cookie name format\n * CookieNameSchema.parse(\"my cookie\"); // Error: Invalid cookie name format\n * ```\n */\nexport const CookieNameSchema = z\n .string()\n .trim()\n .min(1, \"Cookie name cannot be empty\")\n .refine(\n (name) =>\n /^[\\x21\\x23-\\x27\\x2A\\x2B\\x2D-\\x2E\\x30-\\x39\\x41-\\x5A\\x5E-\\x7E]+$/.test(\n name,\n ),\n \"Invalid cookie name format - must contain only valid characters (letters, numbers, and certain symbols)\",\n );\n\n/**\n * Zod schema for cookie path validation.\n * Enforces standard cookie path rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid paths\n * CookiePathSchema.parse(\"/\"); // OK\n * CookiePathSchema.parse(\"/api\"); // OK\n * CookiePathSchema.parse(\"/path/to/page\"); // OK\n *\n * // Invalid paths\n * CookiePathSchema.parse(\"\"); // Error: Path cannot be empty\n * CookiePathSchema.parse(\"invalid\"); // Error: Path must start with /\n * CookiePathSchema.parse(\"/path?query\"); // Error: Invalid path format\n * ```\n */\nexport const CookiePathSchema = z\n .string()\n .trim()\n .min(1, \"Path cannot be empty\")\n .refine((path) => path.startsWith(\"/\"), \"Path must start with /\")\n .refine(\n (path) => /^\\/[!#$%&'()*+,\\-./:=@\\w]*$/.test(path),\n \"Invalid path format - must contain only valid URL path characters\",\n )\n .default(\"/\");\n\n/**\n * Zod schema for cookie value.\n * Attempts to parse JSON values using destr for better readability.\n */\nexport const CookieValueSchema = z\n .string()\n .trim()\n .transform((value) => destr(value))\n .pipe(z.any());\n\n/**\n * Zod schema for Safari binary cookie row.\n * Validates and enforces the structure of cookie data read from Safari's Cookies.binarycookies file.\n * @example\n * ```typescript\n * const cookieData = {\n * name: \"session\",\n * value: \"abc123\",\n * domain: \"example.com\",\n * path: \"/\",\n * expiry: 1735689600,\n * creation: 1672531200,\n * flags: 0x5, // Secure + HTTPOnly\n * };\n * const validCookie = BinaryCookieRowSchema.parse(cookieData);\n * ```\n */\nexport const BinaryCookieRowSchema = z.object({\n name: CookieNameSchema,\n value: CookieValueSchema,\n domain: CookieDomainSchema,\n path: CookiePathSchema,\n expiry: z.number().int(),\n creation: z.number().int(),\n flags: z.number().optional(),\n version: z.number().int().optional(),\n port: z.number().int().optional(),\n comment: z.string().optional(),\n commentURL: z.string().optional(),\n});\n\n/**\n * Type representing a decoded Safari binary cookie.\n * This type is inferred from the BinaryCookieRowSchema and includes all cookie properties.\n * @property name - The name of the cookie (non-empty string)\n * @property value - The value stored in the cookie\n * @property domain - The domain the cookie belongs to (non-empty string)\n * @property path - The path where the cookie is valid (defaults to \"/\")\n * @property expiry - Unix timestamp when the cookie expires\n * @property creation - Unix timestamp when the cookie was created\n * @property flags - Optional bit flags (e.g., Secure, HTTPOnly)\n * @property version - Optional cookie version number\n * @property port - Optional port number restriction\n * @property comment - Optional cookie comment\n * @property commentURL - Optional URL for the cookie's comment\n */\nexport type BinaryCookieRow = z.infer<typeof BinaryCookieRowSchema>;\n\n/**\n * Schema for cookie specification parameters\n * Defines the required fields for identifying a cookie\n * @example\n * ```typescript\n * // Validate a cookie specification\n * const spec = {\n * name: 'session',\n * domain: 'example.com'\n * };\n * const result = CookieSpecSchema.safeParse(spec);\n * if (result.success) {\n * console.log('Valid cookie spec:', result.data);\n * } else {\n * console.error('Invalid cookie spec:', result.error);\n * }\n *\n * // Invalid spec (empty name)\n * const invalidSpec = {\n * name: '',\n * domain: 'example.com'\n * };\n * // Throws: \"Cookie name cannot be empty\"\n * CookieSpecSchema.parse(invalidSpec);\n * ```\n */\nexport const CookieSpecSchema = z\n .object({\n name: CookieNameSchema,\n domain: CookieDomainSchema,\n })\n .strict();\n\n/**\n * Type definition for cookie specification\n * Used for specifying which cookie to query\n * @example\n * ```typescript\n * // Basic cookie spec\n * const spec: CookieSpec = {\n * name: 'auth',\n * domain: 'api.example.com'\n * };\n *\n * // Use in function parameters\n * function queryCookie(spec: CookieSpec): Promise<ExportedCookie[]> {\n * return getCookie(spec);\n * }\n *\n * // Array of specs\n * const specs: CookieSpec[] = [\n * { name: 'session', domain: 'app.example.com' },\n * { name: 'theme', domain: 'example.com' }\n * ];\n * ```\n */\nexport type CookieSpec = z.infer<typeof CookieSpecSchema>;\n\n/**\n * Schema for metadata about a cookie\n */\nexport const CookieMetaSchema = z\n .object({\n file: z.string().trim().min(1, \"File path cannot be empty\").optional(),\n browser: z.string().trim().optional(),\n decrypted: z.boolean().optional(),\n secure: z.boolean().optional(),\n httpOnly: z.boolean().optional(),\n path: CookiePathSchema.optional(),\n })\n .catchall(z.unknown())\n .strict();\n\n/**\n * Type definition for cookie metadata\n */\nexport type CookieMeta = z.infer<typeof CookieMetaSchema>;\n\n/**\n * Schema for exported cookie data\n * Represents a cookie with all its properties and metadata\n * @example\n * ```typescript\n * // Validate an exported cookie\n * const cookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n * const result = ExportedCookieSchema.safeParse(cookie);\n * if (result.success) {\n * console.log('Valid cookie:', result.data);\n * } else {\n * console.error('Invalid cookie:', result.error);\n * }\n *\n * // Cookie with infinite expiry\n * const infiniteCookie = {\n * ...cookie,\n * expiry: \"Infinity\"\n * };\n * ExportedCookieSchema.parse(infiniteCookie); // OK\n * ```\n */\nexport const ExportedCookieSchema = z\n .object({\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: CookieValueSchema,\n expiry: z\n .union([\n z.literal(\"Infinity\"),\n z.date(),\n z.number().int().positive(\"Expiry must be a positive number\"),\n ])\n .optional(),\n meta: CookieMetaSchema.optional(),\n })\n .strict();\n\n/**\n * Type definition for exported cookie data\n * Represents the structure of a cookie after it has been retrieved\n * @example\n * ```typescript\n * // Basic exported cookie\n * const cookie: ExportedCookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n *\n * // Process exported cookies\n * function processCookies(cookies: ExportedCookie[]): string[] {\n * return cookies.map(cookie => `${cookie.name}=${cookie.value}`);\n * }\n *\n * // Filter expired cookies\n * function filterExpired(cookies: ExportedCookie[]): ExportedCookie[] {\n * const now = new Date();\n * return cookies.filter(cookie =>\n * cookie.expiry === \"Infinity\" ||\n * (cookie.expiry instanceof Date && cookie.expiry > now)\n * );\n * }\n * ```\n */\nexport type ExportedCookie = z.infer<typeof ExportedCookieSchema>;\n\n/**\n * Schema for raw cookie data from browser stores\n */\nexport const CookieRowSchema = z\n .object({\n expiry: z.number().int().optional(),\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: z.union([z.string(), z.instanceof(Buffer)]),\n })\n .strict();\n\n/**\n * Type definition for raw cookie data\n */\nexport type CookieRow = z.infer<typeof CookieRowSchema>;\n\n/**\n * Schema for cookie render options\n */\nexport const RenderOptionsSchema = z\n .object({\n format: z.enum([\"merged\", \"grouped\"]).optional(),\n separator: z.string().optional(),\n showFilePaths: z.boolean().optional(),\n })\n .strict();\n\n/**\n * Type definition for render options\n */\nexport type RenderOptions = z.infer<typeof RenderOptionsSchema>;\n\n/**\n * Schema for browser names\n */\nexport const BrowserNameSchema = z.enum([\n \"Chrome\",\n \"Firefox\",\n \"Safari\",\n \"internal\",\n \"unknown\",\n]);\n\n/**\n * Type definition for browser names\n */\nexport type BrowserName = z.infer<typeof BrowserNameSchema>;\n\n/**\n * Schema for cookie query strategy\n */\nexport const CookieQueryStrategySchema = z\n .object({\n browserName: BrowserNameSchema,\n queryCookies: z\n .function()\n .args(z.string(), z.string())\n .returns(z.promise(z.array(ExportedCookieSchema))),\n })\n .strict();\n\n/**\n * Type definition for cookie query strategy\n */\nexport type CookieQueryStrategy = z.infer<typeof CookieQueryStrategySchema>;\n\n/**\n * Type representing either a single cookie specification or an array of specifications.\n * Useful when you need to query multiple cookies in a single operation.\n * @example\n * ```typescript\n * // Single cookie spec\n * const single: MultiCookieSpec = {\n * domain: \"example.com\",\n * name: \"sessionId\"\n * };\n *\n * // Multiple cookie specs\n * const multiple: MultiCookieSpec = [\n * { domain: \"example.com\", name: \"sessionId\" },\n * { domain: \"api.example.com\", name: \"authToken\" }\n * ];\n * ```\n */\nexport type MultiCookieSpec = CookieSpec | CookieSpec[];\n","import { readFileSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { join } from \"path\";\n\nimport type { BinaryCookieRow } from \"../../types/schemas\";\nimport { BinaryCookieRowSchema } from \"../../types/schemas\";\n\n// Cookie flag constants\nconst _COOKIE_FLAGS = {\n SECURE: 0x1,\n HTTP_ONLY: 0x4,\n UNKNOWN1: 0x8,\n UNKNOWN2: 0x10,\n} as const;\n\n// File structure constants\nconst _FILE_HEADER_MAGIC = \"cook\";\nconst _FILE_FOOTER = 0x071720050000004b;\n\n// The date offset for Safari cookies (until 2017)\nconst _SAFARI_DATE_OFFSET = 978307200; // Difference between Unix epoch and Mac epoch (2001-01-01 00:00:00)\n\nfunction readNullTerminatedString(\n buffer: Buffer,\n offset: number,\n): [string, number] {\n let end = offset;\n while (end < buffer.length && buffer[end] !== 0) {\n end++;\n }\n return [buffer.toString(\"utf8\", offset, end), end + 1];\n}\n\nfunction decodeCookieHeader(\n buffer: Buffer,\n offset: number,\n): [BinaryCookieRow, number] {\n // First 4 bytes are the cookie size in little-endian\n const size = buffer.readUInt32LE(offset);\n\n // Read version and flags\n const version = buffer.readUInt32LE(offset + 4);\n const flags = buffer.readUInt32LE(offset + 8);\n\n // Check for port\n const hasPort = buffer.readUInt32LE(offset + 12);\n\n // Read offsets for dynamic fields\n const urlOffset = buffer.readUInt32LE(offset + 16);\n const nameOffset = buffer.readUInt32LE(offset + 20);\n const pathOffset = buffer.readUInt32LE(offset + 24);\n const valueOffset = buffer.readUInt32LE(offset + 28);\n const commentOffset = buffer.readUInt32LE(offset + 32);\n const commentURLOffset = buffer.readUInt32LE(offset + 36);\n\n // Read dates and adjust for Safari epoch\n const expiryDate = buffer.readDoubleLE(offset + 40) + _SAFARI_DATE_OFFSET;\n const creationDate = buffer.readDoubleLE(offset + 48) + _SAFARI_DATE_OFFSET;\n\n let currentOffset = offset + 56; // Fixed header size\n\n // Read port if present\n let port: number | undefined;\n if (hasPort) {\n port = buffer.readUInt16LE(currentOffset);\n currentOffset += 2;\n }\n\n // Read strings in order of their offsets\n const offsets = [\n { field: \"url\", offset: urlOffset },\n { field: \"name\", offset: nameOffset },\n { field: \"path\", offset: pathOffset },\n { field: \"value\", offset: valueOffset },\n { field: \"comment\", offset: commentOffset },\n { field: \"commentURL\", offset: commentURLOffset },\n ].sort((a, b) => a.offset - b.offset);\n\n const fields: Record<string, string> = {};\n\n for (const { field, offset: stringOffset } of offsets) {\n if (stringOffset > 0) {\n const [value, nextOffset] = readNullTerminatedString(\n buffer,\n offset + stringOffset,\n );\n fields[field] = value;\n currentOffset = Math.max(currentOffset, nextOffset);\n }\n }\n\n // Create and validate the cookie row\n const cookieRow = BinaryCookieRowSchema.parse({\n name: fields.name,\n value: fields.value,\n domain: fields.url.startsWith(\".\") ? fields.url.slice(1) : fields.url,\n path: fields.path || \"/\",\n expiry: Math.floor(expiryDate),\n creation: Math.floor(creationDate),\n flags,\n version,\n port,\n comment: fields.comment,\n commentURL: fields.commentURL,\n });\n\n return [cookieRow, size];\n}\n\nfunction decodePage(\n buffer: Buffer,\n offset: number,\n pageSize: number,\n): BinaryCookieRow[] {\n // Skip first 5 bytes\n const headerLengthOffset = offset + 5;\n // Next 4 bytes contain header length\n const headerLength = buffer.readUInt32BE(headerLengthOffset);\n\n let currentOffset = offset + headerLength;\n const cookies: BinaryCookieRow[] = [];\n const pageEnd = offset + pageSize;\n\n // Read cookies until we reach the page end\n while (currentOffset < pageEnd - 8) {\n try {\n const [cookie, size] = decodeCookieHeader(buffer, currentOffset);\n cookies.push(cookie);\n currentOffset += size;\n } catch (error) {\n console.warn(`Error decoding cookie at offset ${currentOffset}:`, error);\n break;\n }\n }\n\n return cookies;\n}\n\n/**\n * Decodes a Safari binary cookie file into an array of cookie objects.\n * @param cookieDbPath - Path to the Safari Cookies.binarycookies file\n * @returns Array of decoded cookie objects\n * @throws {Error} If the file cannot be read or has invalid format\n */\nexport function decodeBinaryCookies(cookieDbPath: string): BinaryCookieRow[] {\n const buffer = readFileSync(cookieDbPath);\n\n // Validate magic header\n const magic = buffer.toString(\"utf8\", 0, 4);\n if (magic !== _FILE_HEADER_MAGIC) {\n throw new Error(\"Invalid cookie file format: wrong magic header\");\n }\n\n // Read number of pages\n const numPages = buffer.readUInt32BE(4);\n\n // Read the page sizes array (4 bytes per page)\n const pageSizes: number[] = [];\n for (let i = 0; i < numPages; i++) {\n pageSizes.push(buffer.readUInt32BE(8 + i * 4));\n }\n\n // Skip the page sizes array\n let offset = 8 + numPages * 4;\n const cookies: BinaryCookieRow[] = [];\n\n // Process each page\n for (let i = 0; i < numPages; i++) {\n try {\n const pageCookies = decodePage(buffer, offset, pageSizes[i]);\n cookies.push(...pageCookies);\n offset += pageSizes[i];\n } catch (error) {\n console.warn(`Error decoding page ${i}:`, error);\n offset += pageSizes[i];\n }\n }\n\n // Validate footer\n const footer = Number(buffer.readBigUInt64BE(buffer.length - 8));\n if (footer !== _FILE_FOOTER) {\n console.warn(\"Invalid cookie file format: wrong footer\");\n }\n\n return cookies;\n}\n\n/**\n * Retrieves cookies from Safari's binary cookie store.\n * @returns Array of decoded Safari cookies\n */\nexport function getSafariCookies(): BinaryCookieRow[] {\n const cookieDbPath = join(\n homedir(),\n \"Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies\",\n );\n return decodeBinaryCookies(cookieDbPath);\n}\n","import { join } from \"path\";\n\nimport { logError } from \"@utils/logHelpers\";\n\nimport type {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { decodeBinaryCookies } from \"../decodeBinaryCookies\";\n\n/**\n * Strategy for querying cookies from Safari browser\n */\nexport class SafariCookieQueryStrategy implements CookieQueryStrategy {\n /**\n * The browser name for this strategy\n */\n public readonly browserName: BrowserName = \"Safari\";\n\n /**\n * Gets the user's home directory\n * @returns The home directory path or empty string if not found\n */\n private getHomeDir(): string {\n const homeDir = process.env.HOME;\n if (typeof homeDir !== \"string\" || homeDir.trim().length === 0) {\n logError(\n \"SafariCookieQueryStrategy\",\n \"HOME environment variable not set\",\n );\n return \"\";\n }\n return homeDir;\n }\n\n /**\n * Gets the path to Safari's cookie database\n * @param homeDir - The user's home directory\n * @returns Path to the cookie database\n */\n private getCookieDbPath(homeDir: string): string {\n return join(\n homeDir,\n \"Library\",\n \"Containers\",\n \"com.apple.Safari\",\n \"Data\",\n \"Library\",\n \"Cookies\",\n \"Cookies.binarycookies\",\n );\n }\n\n /**\n * Decodes cookies from Safari's binary cookie file\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @returns Array of exported cookies\n */\n private decodeCookies(\n cookieDbPath: string,\n name: string,\n domain: string,\n ): ExportedCookie[] {\n try {\n const cookies = decodeBinaryCookies(cookieDbPath);\n return cookies\n .filter(\n (cookie) => cookie.name === name && cookie.domain.includes(domain),\n )\n .map((cookie) => ({\n domain: cookie.domain,\n name: cookie.name,\n value: Buffer.isBuffer(cookie.value)\n ? cookie.value.toString()\n : String(cookie.value),\n expiry:\n typeof cookie.expiry === \"number\" && cookie.expiry > 0\n ? new Date(cookie.expiry * 1000)\n : \"Infinity\",\n meta: {\n file: cookieDbPath,\n browser: \"Safari\" as const,\n decrypted: false,\n },\n }));\n } catch (error) {\n if (error instanceof Error) {\n logError(\n \"SafariCookieQueryStrategy\",\n `Error decoding ${cookieDbPath}`,\n { error, name, domain },\n );\n } else {\n logError(\n \"SafariCookieQueryStrategy\",\n `Error decoding ${cookieDbPath}`,\n { error: \"Unknown error\", name, domain },\n );\n }\n return [];\n }\n }\n\n /**\n * Query Safari's cookie storage for cookies matching the given criteria\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @returns Array of matching cookies, or empty array if none found\n */\n public async queryCookies(\n name: string,\n domain: string,\n ): Promise<ExportedCookie[]> {\n const homeDir = this.getHomeDir();\n if (typeof homeDir !== \"string\" || homeDir.length === 0) {\n return Promise.resolve([]);\n }\n\n const cookieDbPath = this.getCookieDbPath(homeDir);\n return Promise.resolve(this.decodeCookies(cookieDbPath, name, domain));\n }\n}\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport { ChromeCookieQueryStrategy } from \"../browsers/chrome/ChromeCookieQueryStrategy\";\nimport { FirefoxCookieQueryStrategy } from \"../browsers/firefox/FirefoxCookieQueryStrategy\";\nimport { SafariCookieQueryStrategy } from \"../browsers/safari/SafariCookieQueryStrategy\";\n\n/**\n * Queries cookies from all available browser strategies (Chrome, Firefox, Safari).\n * This function acts as a unified interface to retrieve cookies across different browsers.\n * @param cookieSpec - The cookie specification to query\n * @param cookieSpec.name - The name pattern to match cookies against (can include '%' as wildcard)\n * @param cookieSpec.domain - The domain to match cookies against\n * @returns Promise resolving to array of exported cookies from all available browsers\n * @remarks\n * - Returns empty array if cookieSpec is invalid or missing required fields\n * - Aggregates results from all available browser strategies\n * - Failed browser queries are gracefully handled and excluded from results\n * - Both name and domain fields are required and must be strings\n * @example\n * ```typescript\n * const cookies = await queryCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n * console.log(cookies); // Array of matching cookies from all browsers\n * ```\n */\nexport async function queryCookies(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n if (!cookieSpec.name || !cookieSpec.domain) {\n return [];\n }\n\n const { name, domain } = cookieSpec;\n if (typeof name !== \"string\" || typeof domain !== \"string\") {\n return [];\n }\n\n /**\n * Initialize all available browser-specific strategies\n * The order of strategies can affect performance but not functionality\n * Each strategy is responsible for its own error handling\n */\n const strategies = [\n new ChromeCookieQueryStrategy(),\n new FirefoxCookieQueryStrategy(),\n new SafariCookieQueryStrategy(),\n ];\n\n /**\n * Query all strategies in parallel and handle failures gracefully\n * Using Promise.allSettled ensures that failures in one strategy\n * don't prevent results from other strategies\n */\n const results = await Promise.allSettled(\n strategies.map((strategy) => strategy.queryCookies(name, domain)),\n );\n\n /**\n * Filter out failed promises and flatten successful results\n * Using PromiseFulfilledResult<ExportedCookie[]> ensures that only successful results are included\n */\n return results\n .filter(\n (result): result is PromiseFulfilledResult<ExportedCookie[]> =>\n result.status === \"fulfilled\",\n )\n .flatMap((result) => result.value);\n}\n\n/**\n * Default export of the queryCookies function.\n * This is the recommended way to import the function for most use cases.\n * @example\n * ```typescript\n * import queryCookies from './queryCookies';\n *\n * // Query cookies with specific name\n * const sessionCookies = await queryCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n *\n * // Query all cookies for a domain using wildcard\n * const allCookies = await queryCookies({\n * name: '%',\n * domain: 'example.com'\n * });\n * ```\n */\nexport default queryCookies;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { queryCookies } from \"./queryCookies\";\n\n/**\n * Retrieves browser cookies that match the specified cookie name and domain criteria.\n * This function provides a way to search and filter cookies based on given specifications.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * // Get all cookies named \"sessionId\"\n * const cookies = await getCookie({ name: \"sessionId\" });\n * // Returns: [{ name: \"sessionId\", value: \"abc123\", domain: \".example.com\", ... }]\n *\n * // Get cookies named \"userPref\" from specific domain\n * const domainCookies = await getCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * // Returns: [{ name: \"userPref\", value: \"darkMode\", domain: \"example.com\", ... }]\n * ```\n */\nexport async function getCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const cookies = await queryCookies(cookieSpec);\n return cookies;\n } catch (error: unknown) {\n logger.warn(\n \"Error querying cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getCookie function.\n * @example\n * ```typescript\n * import getCookie from './getCookie';\n * const authCookies = await getCookie({\n * name: \"auth-token\",\n * domain: \"api.example.com\"\n * });\n * ```\n */\nexport default getCookie;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\nimport { ChromeCookieQueryStrategy } from \"../browsers/chrome/ChromeCookieQueryStrategy\";\n\n/**\n * Retrieves cookies from Chrome browser storage that match the specified criteria.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * // Get all cookies named \"sessionId\" from Chrome\n * const cookies = await getChromeCookie({ name: \"sessionId\" });\n *\n * // Get cookies named \"userPref\" from specific domain in Chrome\n * const domainCookies = await getChromeCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport async function getChromeCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const strategy = new ChromeCookieQueryStrategy();\n const cookies = await strategy.queryCookies(\n cookieSpec.name,\n cookieSpec.domain,\n );\n return cookies;\n } catch (error: unknown) {\n logger.warn(\"Error querying Chrome cookies:\", error);\n return [];\n }\n}\n\n/**\n * Default export of the getChromeCookie function.\n * @example\n * ```typescript\n * import getChromeCookie from './getChromeCookie';\n * const cookies = await getChromeCookie({\n * name: \"sessionId\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport default getChromeCookie;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\nimport { FirefoxCookieQueryStrategy } from \"../browsers/firefox/FirefoxCookieQueryStrategy\";\n\n/**\n * Retrieves cookies from Firefox browser storage that match the specified criteria.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * // Get all cookies named \"sessionId\" from Firefox\n * const cookies = await getFirefoxCookie({ name: \"sessionId\" });\n *\n * // Get cookies named \"userPref\" from specific domain in Firefox\n * const domainCookies = await getFirefoxCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport async function getFirefoxCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const strategy = new FirefoxCookieQueryStrategy();\n const cookies = await strategy.queryCookies(\n cookieSpec.name,\n cookieSpec.domain,\n );\n return cookies;\n } catch (error: unknown) {\n logger.warn(\n \"Error querying Firefox cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getFirefoxCookie function.\n * @example\n * ```typescript\n * import getFirefoxCookie from './getFirefoxCookie';\n * const sessionCookies = await getFirefoxCookie({\n * name: \"PHPSESSID\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport default getFirefoxCookie;\n","import { groupBy } from \"lodash-es\";\n\nimport { ExportedCookie, RenderOptions } from \"../../types/schemas\";\n\n/**\n * Renders cookies as a string or array of strings based on the provided format option.\n * Supports merged format for single string output or grouped format for file-based grouping.\n * @param cookies - The cookies to render\n * @param options - Options for rendering\n * @param options.format - The output format ('merged' or 'grouped')\n * @param options.showFilePaths - Whether to include file paths in grouped output\n * @param options.separator - Custom separator for cookie values\n * @returns A string for merged format, or array of strings for grouped format\n * @example\n * ```typescript\n * // Merged format (default)\n * const cookies = [\n * { value: 'sessionId=abc123' },\n * { value: 'theme=dark' }\n * ];\n * renderCookies(cookies);\n * // Returns: \"sessionId=abc123; theme=dark\"\n *\n * // Grouped format with file paths\n * const groupedCookies = [\n * { value: 'sessionId=abc123', meta: { file: 'auth.ts' } },\n * { value: 'theme=dark', meta: { file: 'preferences.ts' } }\n * ];\n * renderCookies(groupedCookies, { format: 'grouped', showFilePaths: true });\n * // Returns: [\"auth.ts: sessionId=abc123\", \"preferences.ts: theme=dark\"]\n * ```\n */\nexport function renderCookies(\n cookies: ExportedCookie[],\n options: RenderOptions = {},\n): string | string[] {\n const { format = \"merged\", showFilePaths = true, separator = \"; \" } = options;\n\n if (cookies.length === 0) {\n return format === \"merged\" ? \"\" : [];\n }\n\n if (format === \"merged\") {\n return cookies.map((c) => c.value as string).join(separator);\n }\n\n const groupedByFile = groupBy(cookies, (c) => c.meta?.file ?? \"unknown\");\n return Object.entries(groupedByFile).map(([file, fileCookies]) => {\n const values = fileCookies.map((c) => c.value as string).join(separator);\n return showFilePaths ? `${file}: ${values}` : values;\n });\n}\n","import type {\n RenderOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\nimport { ExportedCookieSchema } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { getCookie } from \"./getCookie\";\nimport { renderCookies } from \"./renderCookies\";\n\n/**\n * Retrieves and renders cookies in a grouped format based on their source files.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @param options - Options for rendering the cookies\n * @param options.showFilePaths - Whether to include file paths in the output\n * @param options.separator - Custom separator for cookie values\n * @returns An array of strings, each representing a group of cookies from a source file\n * @example\n * ```typescript\n * // Basic usage - get all cookies named \"sessionId\" grouped by source file\n * const cookies = await getGroupedRenderedCookies({ name: \"sessionId\" });\n *\n * // Get cookies with domain filter and custom rendering options\n * const domainCookies = await getGroupedRenderedCookies(\n * {\n * name: \"userPref\",\n * domain: \"example.com\"\n * },\n * {\n * showFilePaths: true,\n * separator: \" | \"\n * }\n * );\n * ```\n */\nexport async function getGroupedRenderedCookies(\n cookieSpec: CookieSpec,\n options: Omit<RenderOptions, \"format\"> = {},\n): Promise<string[]> {\n try {\n const cookies = await getCookie(cookieSpec);\n if (!Array.isArray(cookies)) {\n return [];\n }\n\n // Validate each cookie against the schema\n const validatedCookies = cookies.filter(\n (cookie): cookie is ExportedCookie => {\n const result = ExportedCookieSchema.safeParse(cookie);\n if (!result.success) {\n logger.warn(\"Invalid cookie format:\", result.error.format());\n return false;\n }\n return true;\n },\n );\n\n return renderCookies(validatedCookies, {\n ...options,\n format: \"grouped\",\n }) as string[];\n } catch (error: unknown) {\n logger.warn(\n \"Error getting grouped rendered cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getGroupedRenderedCookies function\n * @example\n * ```typescript\n * import getGroupedCookies from './getGroupedRenderedCookies';\n *\n * // Get all session cookies with custom separator\n * const sessionCookies = await getGroupedCookies(\n * { name: \"session_*\" },\n * { separator: \"\\n\" }\n * );\n *\n * // Get cookies from multiple domains\n * const multiDomainCookies = await getGroupedCookies({\n * name: \"tracking\",\n * domain: [\"site1.com\", \"site2.com\"]\n * });\n * ```\n */\nexport default getGroupedRenderedCookies;\n","import type {\n RenderOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\nimport { ExportedCookieSchema } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { getCookie } from \"./getCookie\";\nimport { renderCookies } from \"./renderCookies\";\n\n/**\n * Retrieves and renders cookies in a merged format\n * @param cookieSpec - The cookie specification to query\n * @param options - Optional rendering options\n * @returns Promise resolving to rendered cookie string\n * @example\n * ```typescript\n * const cookieString = await getMergedRenderedCookies(\n * { name: 'session', domain: 'example.com' },\n * { separator: '; ' }\n * );\n * console.log(cookieString); // \"session=abc123; auth=xyz789\"\n * ```\n */\nexport async function getMergedRenderedCookies(\n cookieSpec: CookieSpec,\n options?: Omit<RenderOptions, \"format\">,\n): Promise<string> {\n try {\n const cookies = await getCookie(cookieSpec);\n if (!Array.isArray(cookies)) {\n return \"\";\n }\n\n // Validate each cookie against the schema\n const validatedCookies = cookies.filter(\n (cookie): cookie is ExportedCookie => {\n const result = ExportedCookieSchema.safeParse(cookie);\n if (!result.success) {\n logger.warn(\"Invalid cookie format:\", result.error.format());\n return false;\n }\n return true;\n },\n );\n\n const result = renderCookies(validatedCookies, {\n ...options,\n format: \"merged\",\n });\n return typeof result === \"string\" ? result : \"\";\n } catch (error: unknown) {\n logger.warn(\n \"Error getting merged rendered cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return \"\";\n }\n}\n\n/**\n * Default export of the getMergedRenderedCookies function.\n * @example\n * ```typescript\n * import { getMergedRenderedCookies } from './getMergedRenderedCookies';\n * const cookies = await getMergedRenderedCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n * ```\n */\nexport default getMergedRenderedCookies;\n","export * from \"./core/cookies/dynamicImports\";\n","import type {\n RenderOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\n\n/**\n * Dynamic import for the getCookie function.\n * @internal\n * @returns Promise resolving to the getCookie function\n * @example\n * ```typescript\n * const getCookieFn = await getCookie();\n * const cookies = await getCookieFn({ domain: 'example.com' });\n * // Returns: [{ name: 'sessionId', value: 'abc123', domain: 'example.com' }, ...]\n * ```\n */\nexport const getCookie = (): Promise<\n (cookieSpec: CookieSpec) => Promise<ExportedCookie[]>\n> => import(\"./getCookie\").then((module) => module.getCookie);\n\n/**\n * Dynamic import for Chrome-specific cookie retrieval.\n * @internal\n * @returns Promise resolving to the getChromeCookie function\n * @example\n * ```typescript\n * const chromeCookieFn = await getChromeCookie();\n * const cookies = await chromeCookieFn({ domain: 'example.com', secure: true });\n * // Returns Chrome-format cookies: [{ name: 'auth', value: 'xyz789', secure: true }, ...]\n * ```\n */\nexport const getChromeCookie = (): Promise<\n (cookieSpec: CookieSpec) => Promise<ExportedCookie[]>\n> => import(\"./getChromeCookie\").then((module) => module.getChromeCookie);\n\n/**\n * Dynamic import for Firefox-specific cookie retrieval.\n * @internal\n * @returns Promise resolving to the getFirefoxCookie function\n * @example\n * ```typescript\n * const firefoxCookieFn = await getFirefoxCookie();\n * const cookies = await firefoxCookieFn({ path: '/api' });\n * // Returns Firefox-format cookies: [{ name: 'token', value: 'def456', path: '/api' }, ...]\n * ```\n */\nexport const getFirefoxCookie = (): Promise<\n (cookieSpec: CookieSpec) => Promise<ExportedCookie[]>\n> => import(\"./getFirefoxCookie\").then((module) => module.getFirefoxCookie);\n\n/**\n * Dynamic import for retrieving grouped and rendered cookies.\n * @internal\n * @returns Promise resolving to the getGroupedRenderedCookies function\n * @example\n * ```typescript\n * const groupedCookiesFn = await getGroupedRenderedCookies();\n * const cookieStrings = await groupedCookiesFn({ domain: 'example.com' });\n * // Returns: ['sessionId=abc123; Domain=example.com', 'auth=xyz789; Domain=example.com']\n * ```\n */\nexport const getGroupedRenderedCookies = (): Promise<\n (cookieSpec: CookieSpec) => Promise<string[]>\n> =>\n import(\"./getGroupedRenderedCookies\").then(\n (module) => module.getGroupedRenderedCookies,\n );\n\n/**\n * Dynamic import for retrieving merged and rendered cookies.\n * @internal\n * @returns Promise resolving to the getMergedRenderedCookies function\n * @example\n * ```typescript\n * const mergedCookiesFn = await getMergedRenderedCookies();\n * const cookieString = await mergedCookiesFn(\n * { domain: 'example.com' },\n * { separator: '; ' }\n * );\n * // Returns: \"sessionId=abc123; auth=xyz789\"\n * ```\n */\nexport const getMergedRenderedCookies = (): Promise<\n (\n cookieSpec: CookieSpec,\n options?: Omit<RenderOptions, \"format\">,\n ) => Promise<string>\n> =>\n import(\"./getMergedRenderedCookies\").then(\n (module) => module.getMergedRenderedCookies,\n );\n"],"mappings":"wvCAAA,IAAAA,GAWMC,GA4CCC,EAvDPC,GAAAC,EAAA,kBAAAJ,GAA8B,mBAWxBC,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,sCAAqC,KAClCJ,GAAWA,EAAO,wBACrB","names":["import_consola","consola","logger_default","init_logger","__esmMin","logOperationResult","operation","success","context","message","logger_default","logError","error","errorContext","logDebug","component","data","createTaggedLogger","logWarn","init_logHelpers","__esmMin","init_logger","import_lodash_es","env","HOME","init_global","__esmMin","import_path","_a","chromeApplicationSupport","init_ChromeApplicationSupport","__esmMin","init_global","HOME","closeDatabase","db","error","logError","querySqliteThenTransform","file","sql","params","rowFilter","rowTransform","openDatabase","rows","filteredRows","import_better_sqlite3","import_lodash_es","init_QuerySqliteThenTransform","__esmMin","init_logHelpers","BetterSqlite3","isValidFilePath","path","trimmedPath","getCookieFiles","patterns","chromeApplicationSupport","files","pattern","matches","glob","logDebug","buildSqlQuery","name","domain","isWildcard","sql","params","processCookieFile","cookieFile","rows","querySqliteThenTransform","row","logOperationResult","error","logError","getEncryptedChromeCookie","file","cookieFiles","results","cookies","import_fs","import_path","import_fast_glob","init_getEncryptedChromeCookie","__esmMin","init_logHelpers","init_ChromeApplicationSupport","init_QuerySqliteThenTransform","require_balanced_match","__commonJSMin","exports","module","balanced","a","b","str","maybeMatch","r","range","reg","m","begs","beg","left","right","result","ai","bi","i","require_brace_expansion","__commonJSMin","exports","module","balanced","expandTop","escSlash","escOpen","escClose","escComma","escPeriod","numeric","str","escapeBraces","unescapeBraces","parseCommaParts","parts","m","pre","body","post","p","postParts","expand","embrace","isPadded","el","lte","i","y","gte","isTop","expansions","k","expansion","isNumericSequence","isAlphaSequence","isSequence","isOptions","n","N","width","incr","test","reverse","pad","c","need","z","j","assertValidPattern","init_assert_valid_pattern","__esmMin","pattern","posixClasses","braceEscape","regexpEscape","rangesToString","parseClass","init_brace_expressions","__esmMin","s","ranges","glob","position","pos","negs","i","sawStart","uflag","escaping","negate","endPos","rangeStart","WHILE","c","cls","unip","u","neg","r","sranges","snegs","unescape","init_unescape","__esmMin","s","windowsPathsNoEscape","types","isExtglobType","startNoTraversal","startNoDot","addPatternStart","justDots","reSpecials","regExpEscape","qmark","star","starNoEmpty","_root","_hasMagic","_uflag","_parts","_parent","_parentIndex","_negs","_filledNegs","_options","_toString","_emptyExt","_AST_instances","fillNegs_fn","_AST_static","parseAST_fn","partsToRegExp_fn","parseGlob_fn","_AST","AST","init_ast","__esmMin","init_brace_expressions","init_unescape","c","s","type","parent","options","__privateAdd","__publicField","__privateSet","__privateGet","p","parts","_a","ret","pp","_b","_c","pl","part","pattern","ast","__privateMethod","glob","re","body","hasMagic","uflag","flags","allowDot","dot","noEmpty","src","_","start","aps","needNoTrav","needNoDot","end","unescape","repeated","bodyDotAllowed","final","close","n","i","str","pos","opt","escaping","inBrace","braceStart","braceNeg","acc","ext","needUflag","consumed","magic","parseClass","escape","init_escape","__esmMin","s","windowsPathsNoEscape","import_brace_expansion","minimatch","starDotExtRE","starDotExtTest","starDotExtTestDot","starDotExtTestNocase","starDotExtTestNocaseDot","starDotStarRE","starDotStarTest","starDotStarTestDot","dotStarRE","dotStarTest","starRE","starTest","starTestDot","qmarksRE","qmarksTestNocase","qmarksTestNocaseDot","qmarksTestDot","qmarksTest","qmarksTestNoExt","qmarksTestNoExtDot","defaultPlatform","path","sep","GLOBSTAR","qmark","star","twoStarDot","twoStarNoDot","filter","ext","defaults","braceExpand","makeRe","match","globMagic","regExpEscape","Minimatch","init_esm","__esmMin","init_assert_valid_pattern","init_ast","init_escape","init_unescape","p","pattern","options","assertValidPattern","f","$0","noext","len","a","b","def","orig","type","parent","s","list","expand","mm","__publicField","part","_","args","rawGlobParts","set","__","isUNC","isDrive","ss","i","globParts","j","optimizationLevel","parts","gs","prev","didSomething","dd","gss","next","p2","other","splin","matched","emptyGSMatch","ai","bi","result","which","negate","negateOffset","file","partial","fileDrive","fileUNC","patternDrive","patternUNC","fdi","pdi","fd","pd","fi","pi","fl","pl","fr","pr","swallowee","hit","m","fastTest","re","AST","twoStar","flags","pp","open","close","ex","ff","filename","escape","unescape","perf","warned","PROCESS","emitWarning","AC","AS","_a","shouldWarn","TYPE","isPosInt","getUintArray","ZeroArray","_constructing","_Stack","Stack","_b","_max","_maxSize","_dispose","_disposeAfter","_fetchMethod","_memoMethod","_size","_calculatedSize","_keyMap","_keyList","_valList","_next","_prev","_head","_tail","_free","_disposed","_sizes","_starts","_ttls","_hasDispose","_hasFetchMethod","_hasDisposeAfter","_LRUCache_instances","initializeTTLTracking_fn","_updateItemAge","_statusTTL","_setItemTTL","_isStale","initializeSizeTracking_fn","_removeItemSize","_addItemSize","_requireSize","indexes_fn","rindexes_fn","isValidIndex_fn","evict_fn","backgroundFetch_fn","isBackgroundFetch_fn","connect_fn","moveToTail_fn","delete_fn","clear_fn","_LRUCache","LRUCache","init_esm","__esmMin","msg","type","code","fn","__publicField","_","warnACPolyfill","reason","printACPolyfillWarning","n","max","size","HeapCls","__privateGet","__privateSet","s","__privateAdd","options","_i","_s","_st","_k","_v","sizeCalculation","ttl","ttlResolution","ttlAutopurge","updateAgeOnGet","updateAgeOnHas","allowStale","dispose","disposeAfter","noDisposeOnSet","noUpdateTTL","maxSize","maxEntrySize","fetchMethod","memoMethod","noDeleteOnFetchRejection","noDeleteOnStaleGet","allowStaleOnFetchRejection","allowStaleOnFetchAbort","ignoreFetchAbort","UintArray","__privateMethod","c","p","k","index","context","key","i","getOptions","v","value","thisp","deleted","entry","start","remain","arr","age","setOptions","_c","_d","_e","status","__privateWrapper","oldVal","oldValue","dt","task","val","hasOptions","peekOptions","fetchOptions","forceRefresh","signal","stale","isStale","staleVal","memoOptions","vv","fetching","ttls","starts","t","cachedNow","getNow","sizes","free","head","ac","fetchOpts","cb","updateCache","aborted","ignoreAbort","fetchFail","bf","eb","er","allowStaleAborted","noDelete","pcall","res","rej","fmp","b","pi","ni","import_node_events","import_node_stream","import_node_string_decoder","proc","isStream","isReadable","isWritable","EOF","MAYBE_EMIT_END","EMITTED_END","EMITTING_END","EMITTED_ERROR","CLOSED","READ","FLUSH","FLUSHCHUNK","ENCODING","DECODER","FLOWING","PAUSED","RESUME","BUFFER","PIPES","BUFFERLENGTH","BUFFERPUSH","BUFFERSHIFT","OBJECTMODE","DESTROYED","ERROR","EMITDATA","EMITEND","EMITEND2","ASYNC","ABORT","ABORTED","SIGNAL","DATALISTENERS","DISCARDED","defer","nodefer","isEndish","isArrayBufferLike","isArrayBufferView","Pipe","PipeProxyErrors","isObjectModeOptions","isEncodingOptions","_a","_b","_c","_d","_e","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","_p","_q","_r","_s","Minipass","init_esm","__esmMin","s","Stream","fn","ev","b","src","dest","opts","__publicField","_er","er","args","options","signal","_enc","_om","a","_","chunk","encoding","cb","n","ret","c","noDrain","ended","p","handler","h","data","buf","resolve","reject","stopped","stop","res","onerr","ondata","onend","ondestroy","value","rej","next","wc","import_node_path","import_node_url","import_fs","actualFS","import_promises","realpathSync","defaultFS","fsFromOption","uncDriveRegexp","uncToDrive","eitherSep","UNKNOWN","IFIFO","IFCHR","IFDIR","IFBLK","IFREG","IFLNK","IFSOCK","IFMT","IFMT_UNKNOWN","READDIR_CALLED","LSTAT_CALLED","ENOTDIR","ENOENT","ENOREADLINK","ENOREALPATH","ENOCHILD","TYPEMASK","entToType","normalizeCache","normalize","normalizeNocaseCache","normalizeNocase","ResolveCache","ChildrenCache","setAsCwd","_fs","_dev","_mode","_nlink","_uid","_gid","_rdev","_blksize","_ino","_size","_blocks","_atimeMs","_mtimeMs","_ctimeMs","_birthtimeMs","_atime","_mtime","_ctime","_birthtime","_matchName","_depth","_fullpath","_fullpathPosix","_relative","_relativePosix","_type","_children","_linkTarget","_realpath","_PathBase_instances","resolveParts_fn","readdirSuccess_fn","markENOENT_fn","markChildrenENOENT_fn","markENOREALPATH_fn","markENOTDIR_fn","readdirFail_fn","lstatFail_fn","readlinkFail_fn","readdirAddChild_fn","readdirAddNewChild_fn","readdirMaybePromoteChild_fn","readdirPromoteChild_fn","applyStat_fn","_onReaddirCB","_readdirCBInFlight","callOnReaddirCB_fn","_asyncReaddirInFlight","PathBase","PathWin32","PathPosix","_resolveCache","_resolvePosixCache","PathScurryBase","PathScurryWin32","PathScurryPosix","PathScurryDarwin","Path","PathScurry","init_esm","__esmMin","rps","readdirCB","fsOption","rootPath","s","c","n","LRUCache","maxSize","a","name","type","root","roots","nocase","children","opts","__privateAdd","__publicField","__privateSet","__privateGet","path","_a","dirParts","__privateMethod","cached","pathPart","p","fullpath","pchild","pv","fp","pfpp","fpp","ifmt","target","read","linkTarget","er","cb","allowZalgo","entries","e","resolve","res","dirs","walkFilter","rp","_","oldCwd","changed","part","code","ter","child","index","v","st","atime","atimeMs","birthtime","birthtimeMs","blksize","blocks","ctime","ctimeMs","dev","gid","ino","mode","mtime","mtimeMs","nlink","rdev","size","uid","cbs","_PathWin32","compare","_PathPosix","_rootPath","cwd","pathImpl","sep","childrenCacheSize","fs","cwdPath","split","prev","len","joinSep","abs","sawFirst","l","paths","r","i","result","entry","withFileTypes","follow","filter","results","walk","dir","next","start","rej","options","Minipass","queue","processing","process","paused","onReaddir","didRealpaths","promises","sync","_dir","isPatternList","isGlobList","_patternList","_globList","_index","_platform","_rest","_globString","_isDrive","_isUNC","_isAbsolute","_followGlobstar","_Pattern","Pattern","init_pattern","__esmMin","init_esm","pl","gl","patternList","globList","index","platform","__privateAdd","__publicField","__privateSet","__privateGet","p0","p1","p2","p3","prest","g0","g1","g2","g3","grest","p","g","GLOBSTAR","defaultPlatform","Ignore","init_ignore","__esmMin","init_esm","init_pattern","ignored","nobrace","nocase","noext","noglobstar","platform","__publicField","ign","mm","Minimatch","parsed","globParts","p","Pattern","m","children","absolute","fullpath","fullpaths","relative","relatives","HasWalkedCache","MatchRecord","SubWalks","Processor","init_processor","__esmMin","init_esm","_HasWalkedCache","store","__publicField","target","pattern","_a","fullpath","cached","absolute","ifDir","n","current","path","subs","p","k","_Processor","opts","hasWalkedCache","patterns","processingSet","t","root","rest","changed","GLOBSTAR","rp","rrest","tp","parent","entries","results","e","ep","makeIgnore","_onResume","_ignore","_sep","_GlobUtil_instances","ignored_fn","childrenIgnored_fn","GlobUtil","GlobWalker","GlobStream","init_walker","__esmMin","init_esm","init_ignore","init_processor","ignore","opts","Ignore","patterns","path","__privateAdd","__publicField","_a","__privateSet","__privateGet","m","fn","e","ifDir","rpc","s","target","__privateMethod","absolute","ign","abs","mark","rel","pre","p","cb","Processor","processor","tasks","next","t","childrenCached","_","entries","children","_b","res","rej","Minipass","import_node_url","defaultPlatform","Glob","init_glob","__esmMin","init_esm","init_pattern","init_walker","pattern","opts","__publicField","p","Scurry","PathScurryWin32","PathScurryDarwin","PathScurryPosix","PathScurry","nocaseMagicOnly","mmo","mms","Minimatch","matchSet","globParts","set","m","i","g","Pattern","GlobWalker","GlobStream","hasMagic","init_has_magic","__esmMin","init_esm","pattern","options","p","Minimatch","globStreamSync","pattern","options","Glob","globStream","globSync","glob_","globIterateSync","globIterate","streamSync","stream","iterateSync","iterate","sync","glob","init_esm","__esmMin","init_glob","init_has_magic","init_ignore","hasMagic","escape","unescape","listChromeProfilePaths","files","sync","chromeApplicationSupport","consola","import_fs","import_path","init_listChromeProfiles","__esmMin","init_esm","init_logger","init_ChromeApplicationSupport","logger_default","extractValue","decodedString","_a","cleanupPatterns","pattern","match","value","decrypt","encryptedValue","password","resolve","reject","error","key","removeV10Prefix","iv","decipher","decrypted","e","removePadding","import_crypto","import_lodash_es","init_decrypt","__esmMin","padding","handleExecutionError","error","command","CommandExecutionError","logError","commandError","execSimple","options","defaultOptions","stdout","stderr","execPromise","result","import_child_process","import_util","init_execSimple","__esmMin","init_logHelpers","message","originalError","getChromePassword_exports","__export","getChromePassword","import_lodash_es","getChromeSafeStoragePassword","init_getChromePassword","__esmMin","init_execSimple","execSimple","import_lodash_es","getChromePassword","init_getChromePassword","__esmMin","init_logHelpers","logError","getMacOSPassword","password","logDebug","error","getExpiryDate","expiry","createExportedCookie","domain","name","value","file","decrypted","ChromeCookieQueryStrategy","init_ChromeCookieQueryStrategy","__esmMin","init_logHelpers","init_getEncryptedChromeCookie","init_listChromeProfiles","init_decrypt","init_getChromePassword","createTaggedLogger","cookieFiles","listChromeProfilePaths","password","getChromePassword","error","logError","encryptedCookies","getEncryptedChromeCookie","context","cookie","result","decryptedValue","decrypt","findFirefoxCookieFiles","files","homedir","logWarn","patterns","pattern","matches","sync","logDebug","import_path","FirefoxCookieQueryStrategy","init_FirefoxCookieQueryStrategy","__esmMin","init_esm","init_logHelpers","init_QuerySqliteThenTransform","name","domain","results","file","cookies","querySqliteThenTransform","row","error","import_destr","import_zod","CookieDomainSchema","CookieNameSchema","CookiePathSchema","CookieValueSchema","BinaryCookieRowSchema","CookieSpecSchema","CookieMetaSchema","ExportedCookieSchema","CookieRowSchema","RenderOptionsSchema","BrowserNameSchema","CookieQueryStrategySchema","init_schemas","__esmMin","domain","name","path","value","destr","readNullTerminatedString","buffer","offset","end","decodeCookieHeader","size","version","flags","hasPort","urlOffset","nameOffset","pathOffset","valueOffset","commentOffset","commentURLOffset","expiryDate","_SAFARI_DATE_OFFSET","creationDate","currentOffset","port","offsets","a","b","fields","field","stringOffset","value","nextOffset","BinaryCookieRowSchema","decodePage","pageSize","headerLengthOffset","headerLength","cookies","pageEnd","cookie","error","decodeBinaryCookies","cookieDbPath","_FILE_HEADER_MAGIC","numPages","pageSizes","i","pageCookies","_FILE_FOOTER","import_fs","import_os","import_path","init_decodeBinaryCookies","__esmMin","init_schemas","import_path","SafariCookieQueryStrategy","init_SafariCookieQueryStrategy","__esmMin","init_logHelpers","init_decodeBinaryCookies","homeDir","logError","cookieDbPath","name","domain","decodeBinaryCookies","cookie","error","queryCookies","cookieSpec","name","domain","strategies","ChromeCookieQueryStrategy","FirefoxCookieQueryStrategy","SafariCookieQueryStrategy","strategy","result","init_queryCookies","__esmMin","init_ChromeCookieQueryStrategy","init_FirefoxCookieQueryStrategy","init_SafariCookieQueryStrategy","getCookie_exports","__export","getCookie_default","getCookie","cookieSpec","queryCookies","error","logger_default","init_getCookie","__esmMin","init_logger","init_queryCookies","getChromeCookie_exports","__export","getChromeCookie_default","getChromeCookie","cookieSpec","ChromeCookieQueryStrategy","error","logger_default","init_getChromeCookie","__esmMin","init_logger","init_ChromeCookieQueryStrategy","getFirefoxCookie_exports","__export","getFirefoxCookie_default","getFirefoxCookie","cookieSpec","FirefoxCookieQueryStrategy","error","logger_default","init_getFirefoxCookie","__esmMin","init_logger","init_FirefoxCookieQueryStrategy","renderCookies","cookies","options","format","showFilePaths","separator","c","groupedByFile","_a","_b","file","fileCookies","values","import_lodash_es","init_renderCookies","__esmMin","getGroupedRenderedCookies_exports","__export","getGroupedRenderedCookies_default","getGroupedRenderedCookies","cookieSpec","options","cookies","getCookie","validatedCookies","cookie","result","ExportedCookieSchema","logger_default","renderCookies","error","init_getGroupedRenderedCookies","__esmMin","init_schemas","init_logger","init_getCookie","init_renderCookies","getMergedRenderedCookies_exports","__export","getMergedRenderedCookies_default","getMergedRenderedCookies","cookieSpec","options","cookies","getCookie","validatedCookies","cookie","result","ExportedCookieSchema","logger_default","renderCookies","error","init_getMergedRenderedCookies","__esmMin","init_schemas","init_logger","init_getCookie","init_renderCookies","index_exports","__export","getChromeCookie","getCookie","getFirefoxCookie","getGroupedRenderedCookies","getMergedRenderedCookies","__toCommonJS","getCookie","module","getChromeCookie","getFirefoxCookie","getGroupedRenderedCookies","getMergedRenderedCookies"]}
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/utils/logger.ts","../src/utils/logHelpers.ts","../src/utils/execSimple.ts","../src/core/browsers/chrome/macos/getChromePassword.ts","../src/index.ts","../src/core/cookies/getCookie.ts","../src/core/browsers/chrome/ChromeCookieQueryStrategy.ts","../src/core/browsers/getEncryptedChromeCookie.ts","../src/core/browsers/chrome/ChromeApplicationSupport.ts","../src/core/browsers/QuerySqliteThenTransform.ts","../src/core/browsers/listChromeProfiles.ts","../src/core/browsers/chrome/decrypt.ts","../src/core/browsers/chrome/getChromePassword.ts","../src/core/browsers/firefox/FirefoxCookieQueryStrategy.ts","../src/core/browsers/safari/SafariCookieQueryStrategy.ts","../src/core/browsers/safari/BinaryCodableCookies.ts","../src/core/browsers/safari/BinaryCodablePage.ts","../src/core/browsers/safari/BinaryCodableCookie.ts","../src/types/schemas.ts","../src/core/browsers/safari/decodeBinaryCookies.ts","../src/core/cookies/queryCookies.ts","../src/core/cookies/getChromeCookie.ts","../src/core/cookies/getFirefoxCookie.ts","../src/core/cookies/getGroupedRenderedCookies.ts","../src/core/cookies/renderCookies.ts","../src/core/cookies/getMergedRenderedCookies.ts"],"sourcesContent":["import { homedir } from \"os\";\n\nimport { config } from \"dotenv\";\nimport { z } from \"zod\";\n\n// Load environment variables from .env file\nconfig();\n\nconst EnvironmentSchema = z.object({\n LOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\"]).default(\"info\"),\n HOME: z\n .string()\n .optional()\n .transform((val) => val ?? process.env.USERPROFILE ?? \"\")\n .pipe(z.string().min(1)),\n});\n\n/**\n * Validated environment variables with type safety and fallbacks\n * @example\n * // Using the environment variables\n * if (env.LOG_LEVEL === \"debug\") {\n * console.log(\"Debug mode enabled\");\n * }\n *\n * // Accessing home directory\n * const cookiePath = join(env.HOME, \"Library/Cookies\");\n */\nexport const env = EnvironmentSchema.parse({\n LOG_LEVEL: process.env.LOG_LEVEL,\n HOME: homedir(),\n});\n","import { createConsola } from \"consola\";\n\nimport { env } from \"../config\";\n\n/**\n * Standard log levels and their usage:\n * - debug: Detailed information for debugging\n * - info: General operational information\n * - success: Successful operations\n * - warn: Warning conditions\n * - error: Error conditions that might still allow the app to continue\n * - fatal: Critical errors that prevent the app from continuing\n */\nconst consola = createConsola({\n fancy: true,\n formatOptions: {\n showLogLevel: false,\n colors: true,\n date: false,\n compact: true,\n columns:\n typeof process.stdout.columns === \"number\" ? process.stdout.columns : 80,\n },\n level: env.LOG_LEVEL === \"debug\" ? 5 : 2,\n});\n\n/**\n * Indicates whether debug logging is enabled\n * @example\n * if (isDebug) {\n * logger.debug(\"Detailed debugging information\");\n * }\n */\nexport const isDebug = env.LOG_LEVEL === \"debug\";\n\n/**\n * Configured consola logger instance with standardized formatting and colored output.\n * Used for consistent logging throughout the application.\n * @example\n * // Basic usage\n * logger.info('Operation started');\n * logger.success('Task completed');\n * logger.error('Failed to process', error);\n *\n * // Tagged logging for module context\n * const moduleLogger = logger.withTag('ModuleName');\n * moduleLogger.info('Module specific log');\n *\n * // Structured logging\n * logger.info('User action', {\n * userId: '123',\n * action: 'login',\n * timestamp: new Date()\n * });\n *\n * // Error logging with full context\n * logger.error('Operation failed', {\n * error: error,\n * context: 'operation name',\n * input: data\n * });\n */\nexport default consola;\n","import logger from \"./logger\";\n\n/**\n * Helper functions for common logging patterns.\n * @module\n * @example\n * ```typescript\n * import { logOperationResult, logError } from './logHelpers';\n *\n * try {\n * const result = await someOperation();\n * logOperationResult('Operation', true, { data: result });\n * } catch (error) {\n * logError('Operation failed', error);\n * }\n * ```\n */\n\ninterface OperationContext {\n [key: string]: unknown;\n}\n\n/**\n * Logs the result of an operation with consistent formatting.\n * @param operation - Name of the operation.\n * @param success - Whether the operation succeeded.\n * @param [context] - Additional context about the operation.\n * @example\n * ```typescript\n * logOperationResult('Database Backup', true, { size: '1.2GB' });\n * // ✅ Database Backup succeeded\n *\n * logOperationResult('File Upload', false, { error: 'Network timeout' });\n * // ❌ File Upload failed\n * ```\n */\nexport function logOperationResult(\n operation: string,\n success: boolean,\n context?: OperationContext,\n): void {\n const icon = success ? \"✅\" : \"❌\";\n const message = `${icon} ${operation} ${success ? \"succeeded\" : \"failed\"}`;\n\n if (success) {\n logger.success(message, context);\n } else {\n logger.error(message, context);\n }\n}\n\n/**\n * Logs an error with consistent formatting and context.\n * @param message - Error message to display.\n * @param error - Error object or error information.\n * @param [context] - Additional context about the error.\n * @example\n * ```typescript\n * try {\n * throw new Error('Connection failed');\n * } catch (error) {\n * logError('Database error', error, { retries: 3 });\n * }\n * ```\n */\nexport function logError(\n message: string,\n error: unknown,\n context?: OperationContext,\n): void {\n const errorContext = {\n ...(context ?? {}),\n error:\n error instanceof Error\n ? {\n name: error.name,\n message: error.message,\n stack: error.stack,\n }\n : error,\n };\n\n logger.error(message, errorContext);\n}\n\n/**\n * Logs debug information with consistent formatting.\n * @param component - Component or module name.\n * @param message - Debug message to log.\n * @param [data] - Optional debug data to include.\n * @example\n * ```typescript\n * logDebug('AuthService', 'Token refresh started', { userId: '123' });\n * ```\n */\nexport function logDebug(\n component: string,\n message: string,\n data?: unknown,\n): void {\n const componentLogger = logger.withTag(component);\n componentLogger.debug(message, data);\n}\n\n/**\n * Creates a tagged logger with consistent naming.\n * @param component - Component or module name.\n * @returns A tagged logger instance.\n * @example\n * ```typescript\n * const dbLogger = createTaggedLogger('Database');\n * dbLogger.info('Connection established');\n * ```\n */\nexport function createTaggedLogger(\n component: string,\n): ReturnType<typeof logger.withTag> {\n return logger.withTag(component);\n}\n\n/**\n * Logs a warning with consistent formatting.\n * @param component - Component or module name.\n * @param message - Warning message to display.\n * @param [context] - Additional context about the warning.\n * @example\n * ```typescript\n * logWarn('Cache', 'Cache miss', { key: 'user-123' });\n * ```\n */\nexport function logWarn(\n component: string,\n message: string,\n context?: OperationContext,\n): void {\n const componentLogger = logger.withTag(component);\n componentLogger.warn(message, context);\n}\n\n// Re-export the base logger for direct usage\n/**\n * Re-export of the base logger for direct usage.\n */\nexport { default as logger } from \"./logger\";\n","// External imports\nimport { exec, ExecOptions } from \"child_process\";\nimport { promisify } from \"util\";\n\n// Internal imports\nimport { logError } from \"@utils/logHelpers\";\n\nconst execPromise = promisify(exec);\n\n/**\n * Custom error class for command execution failures.\n * @property {string} command - The command that failed to execute\n * @property {Error} [originalError] - The underlying error that caused the failure\n * @throws CommandExecutionError Always throws with appropriate error context\n * @example\n * ```typescript\n * throw new CommandExecutionError(\n * 'Command timed out',\n * 'git status',\n * originalError\n * );\n * ```\n */\nclass CommandExecutionError extends Error {\n public constructor(\n message: string,\n public readonly command: string,\n public readonly originalError?: Error,\n ) {\n super(message);\n this.name = \"CommandExecutionError\";\n }\n}\n\n/**\n * Handles execution errors and throws appropriate CommandExecutionError.\n * @internal\n * @param error - The error that occurred during command execution\n * @param command - The command that was being executed when the error occurred\n * @throws CommandExecutionError Always throws with appropriate error context\n * @example\n * ```typescript\n * try {\n * await execPromise('invalid-command');\n * } catch (error) {\n * handleExecutionError(error, 'invalid-command');\n * }\n * ```\n */\nfunction handleExecutionError(error: unknown, command: string): never {\n if (error instanceof CommandExecutionError) {\n logError(\"Command execution failed\", error, {\n command: error.command,\n originalError: error.originalError,\n });\n throw error;\n }\n\n if (error instanceof Error) {\n const commandError = new CommandExecutionError(\n error.message,\n command,\n error,\n );\n logError(\"Failed to execute command\", error, {\n command,\n stack: error.stack,\n });\n throw commandError;\n }\n\n // Handle unknown error types\n const commandError = new CommandExecutionError(\n \"Unknown error occurred during command execution\",\n command,\n );\n logError(\"Failed to execute command\", null, {\n error,\n command,\n });\n throw commandError;\n}\n\n/**\n * Executes a shell command asynchronously and returns its output as a string.\n * @param command - The shell command to execute\n * @param options - Optional execution options that override the defaults\n * @returns A promise that resolves to the trimmed command output\n * @throws CommandExecutionError if the command returns an empty result, times out, or fails to execute\n * @example\n * ```typescript\n * // Basic usage\n * const gitStatus = await execSimple('git status');\n *\n * // With custom timeout\n * const output = await execSimple('long-running-command', { timeout: 60000 });\n *\n * // Error handling\n * try {\n * const result = await execSimple('git push');\n * } catch (error) {\n * if (error instanceof CommandExecutionError) {\n * console.error('Push failed:', error.message);\n * }\n * }\n * ```\n */\nexport async function execSimple(\n command: string,\n options: Partial<ExecOptions> = {},\n): Promise<string> {\n if (!command || typeof command !== \"string\") {\n throw new CommandExecutionError(\n \"Command must be a non-empty string\",\n command,\n );\n }\n\n const defaultOptions = {\n encoding: \"utf8\" as BufferEncoding,\n maxBuffer: 5 * 1024 * 1024, // 5MB buffer\n timeout: 30000, // 30 second timeout\n };\n\n try {\n const { stdout, stderr } = await execPromise(command, {\n ...defaultOptions,\n ...options,\n });\n const result = stdout.trim();\n\n if (!result) {\n if (stderr) {\n throw new CommandExecutionError(\n `Command failed with stderr: ${stderr}`,\n command,\n );\n }\n throw new CommandExecutionError(\"Command returned empty result\", command);\n }\n\n return result;\n } catch (error) {\n handleExecutionError(error, command);\n }\n}\n","import { memoize } from \"lodash-es\";\n\nimport { execSimple } from \"@utils/execSimple\";\n\n/**\n * Retrieves the Chrome Safe Storage password from the macOS keychain\n * @returns A promise that resolves to the Chrome Safe Storage password\n * @throws {Error} If the password cannot be retrieved from the keychain\n */\nconst getChromeSafeStoragePassword = async (): Promise<string> => {\n const command = 'security find-generic-password -w -s \"Chrome Safe Storage\"';\n return execSimple(command);\n};\n\n/**\n * Memoized version of getChromeSafeStoragePassword that caches the result\n * to avoid repeated keychain queries\n * @returns A promise that resolves to the Chrome Safe Storage password\n * @throws {Error} If the password cannot be retrieved from the keychain\n * @example\n */\nexport const getChromePassword: () => Promise<string> = memoize(\n getChromeSafeStoragePassword,\n);\n","/**\n * Core cookie retrieval and manipulation functions\n */\nexport {\n getCookie,\n getChromeCookie,\n getFirefoxCookie,\n getGroupedRenderedCookies,\n getMergedRenderedCookies,\n} from \"./core/cookies\";\n\n/**\n * Type definitions for cookie-related interfaces and configurations\n */\nexport type {\n CookieSpec,\n ExportedCookie,\n RenderOptions,\n BrowserName,\n CookieQueryStrategy,\n MultiCookieSpec,\n} from \"./types/schemas\";\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { queryCookies } from \"./queryCookies\";\n\n/**\n * Retrieves browser cookies that match the specified cookie name and domain criteria.\n * This function provides a way to search and filter cookies based on given specifications.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * import { getCookie } from \"@mherod/get-cookie\";\n *\n * // Get all cookies named \"sessionId\"\n * const cookies = await getCookie({ name: \"sessionId\" });\n * // Returns: [{ name: \"sessionId\", value: \"abc123\", domain: \".example.com\", ... }]\n *\n * // Get cookies named \"userPref\" from specific domain\n * const domainCookies = await getCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * // Returns: [{ name: \"userPref\", value: \"darkMode\", domain: \"example.com\", ... }]\n * ```\n */\nexport async function getCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const cookies = await queryCookies(cookieSpec);\n return cookies;\n } catch (error: unknown) {\n logger.warn(\n \"Error querying cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getCookie function.\n * @example\n * ```typescript\n * import { getCookie } from \"@mherod/get-cookie\";\n * const authCookies = await getCookie({\n * name: \"auth-token\",\n * domain: \"api.example.com\"\n * });\n * ```\n */\nexport default getCookie;\n","import { createTaggedLogger, logError } from \"@utils/logHelpers\";\n\nimport {\n BrowserName,\n CookieQueryStrategy,\n CookieRow,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { getEncryptedChromeCookie } from \"../getEncryptedChromeCookie\";\nimport { listChromeProfilePaths } from \"../listChromeProfiles\";\n\nimport { decrypt } from \"./decrypt\";\nimport { getChromePassword } from \"./getChromePassword\";\n\ninterface DecryptionContext {\n file: string;\n password: string;\n}\n\nfunction getExpiryDate(expiry: number | undefined | null): Date | \"Infinity\" {\n if (typeof expiry !== \"number\" || expiry <= 0) {\n return \"Infinity\";\n }\n return new Date(expiry);\n}\n\nfunction createExportedCookie(\n domain: string,\n name: string,\n value: string,\n expiry: number | undefined | null,\n file: string,\n decrypted: boolean,\n): ExportedCookie {\n return {\n domain,\n name,\n value,\n expiry: getExpiryDate(expiry),\n meta: {\n file,\n browser: \"Chrome\",\n decrypted,\n },\n };\n}\n\n/**\n * Strategy for querying cookies from Chrome browser\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * ```\n */\nexport class ChromeCookieQueryStrategy implements CookieQueryStrategy {\n private readonly logger = createTaggedLogger(\"ChromeCookieQueryStrategy\");\n\n /**\n * The browser name for this strategy\n */\n public readonly browserName: BrowserName = \"Chrome\";\n\n /**\n * Queries cookies from Chrome's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @returns A promise that resolves to an array of exported cookies\n * @example\n * ```typescript\n * const strategy = new ChromeCookieQueryStrategy();\n * const cookies = await strategy.queryCookies('session', 'example.com');\n * console.log(cookies);\n * ```\n */\n public async queryCookies(\n name: string,\n domain: string,\n ): Promise<ExportedCookie[]> {\n try {\n this.logger.info(\"Querying cookies\", { name, domain });\n\n if (process.platform !== \"darwin\") {\n this.logger.warn(\"Platform not supported\", {\n platform: process.platform,\n });\n return [];\n }\n\n const cookieFiles = listChromeProfilePaths();\n if (cookieFiles.length === 0) {\n this.logger.warn(\"No Chrome cookie files found\");\n return [];\n }\n\n const password = await getChromePassword();\n const results = await Promise.all(\n cookieFiles.map((file) =>\n this.processFile(file, name, domain, password),\n ),\n );\n\n return results.flat();\n } catch (error) {\n if (error instanceof Error) {\n logError(\"Failed to query cookies\", error, { name, domain });\n } else {\n logError(\"Failed to query cookies\", new Error(String(error)), {\n name,\n domain,\n });\n }\n return [];\n }\n }\n\n private async processFile(\n file: string,\n name: string,\n domain: string,\n password: string,\n ): Promise<ExportedCookie[]> {\n try {\n const encryptedCookies = await getEncryptedChromeCookie({\n name,\n domain,\n file,\n });\n\n const context: DecryptionContext = { file, password };\n const results = await Promise.allSettled(\n encryptedCookies.map((cookie) => this.processCookie(cookie, context)),\n );\n\n return results\n .map((result) => (result.status === \"fulfilled\" ? result.value : null))\n .filter((cookie): cookie is ExportedCookie => cookie !== null);\n } catch (error) {\n if (error instanceof Error) {\n this.logger.error(\"Failed to process cookie file\", { error, file });\n } else {\n this.logger.error(\"Failed to process cookie file\", {\n error: String(error),\n file,\n });\n }\n return [];\n }\n }\n\n private async processCookie(\n cookie: CookieRow,\n context: DecryptionContext,\n ): Promise<ExportedCookie> {\n try {\n const value = Buffer.isBuffer(cookie.value)\n ? cookie.value\n : Buffer.from(String(cookie.value));\n\n const decryptedValue = await decrypt(value, context.password);\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n decryptedValue,\n cookie.expiry,\n context.file,\n true,\n );\n } catch (error) {\n if (error instanceof Error) {\n this.logger.warn(\"Failed to decrypt cookie\", { error });\n } else {\n this.logger.warn(\"Failed to decrypt cookie\", { error: String(error) });\n }\n return createExportedCookie(\n cookie.domain,\n cookie.name,\n cookie.value.toString(\"utf-8\"),\n cookie.expiry,\n context.file,\n false,\n );\n }\n }\n}\n","import { existsSync } from \"fs\";\nimport { join } from \"path\";\n\nimport glob from \"fast-glob\";\n\nimport { logError, logDebug, logOperationResult } from \"@utils/logHelpers\";\n\nimport type { CookieRow } from \"../../types/schemas\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\nimport { querySqliteThenTransform } from \"./QuerySqliteThenTransform\";\n\ninterface ChromeCookieRow {\n encrypted_value: Buffer;\n name: string;\n host_key: string;\n expires_utc: number;\n}\n\ninterface GetEncryptedCookieOptions {\n name: string;\n domain: string;\n file?: string;\n}\n\ninterface SqlQuery {\n sql: string;\n params: string[];\n}\n\n/**\n * Validates if a path is a valid, existing file\n * @param path - Path to validate\n * @returns true if path is valid and file exists, false otherwise\n */\nfunction isValidFilePath(path: unknown): path is string {\n if (typeof path !== \"string\") {\n return false;\n }\n\n const trimmedPath = path.trim();\n if (trimmedPath.length === 0) {\n return false;\n }\n\n return existsSync(trimmedPath);\n}\n\n/**\n * Get paths to Chrome cookie files\n * @returns A promise that resolves to an array of file paths\n */\nasync function getCookieFiles(): Promise<string[]> {\n const patterns = [\n join(chromeApplicationSupport, \"Default/Cookies\"),\n join(chromeApplicationSupport, \"Profile */Cookies\"),\n join(chromeApplicationSupport, \"Profile Default/Cookies\"),\n ];\n\n const files: string[] = [];\n for (const pattern of patterns) {\n const matches = await glob(pattern);\n files.push(...matches);\n }\n\n logDebug(\"ChromeCookies\", \"Found cookie files\", {\n count: files.length,\n files,\n });\n return files;\n}\n\n/**\n * Builds the SQL query for retrieving cookies\n * @param name - Cookie name to search for\n * @param domain - Domain to filter by\n * @returns SQL query and parameters\n */\nfunction buildSqlQuery(name: string, domain: string): SqlQuery {\n const isWildcard = name === \"%\";\n const sql = isWildcard\n ? `SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE host_key LIKE ?`\n : `SELECT name, encrypted_value, host_key, expires_utc FROM cookies WHERE name = ? AND host_key LIKE ?`;\n const params = isWildcard ? [`%${domain}%`] : [name, `%${domain}%`];\n\n return { sql, params };\n}\n\n/**\n * Processes a single cookie file to extract matching cookies\n * @param cookieFile - Path to the cookie file\n * @param name - Cookie name to search for\n * @param domain - Domain to filter by\n * @returns Array of matching cookies\n */\nasync function processCookieFile(\n cookieFile: string,\n name: string,\n domain: string,\n): Promise<CookieRow[]> {\n try {\n const { sql, params } = buildSqlQuery(name, domain);\n logDebug(\"ChromeCookies\", \"Executing query\", { sql, params });\n\n const rows = await querySqliteThenTransform<ChromeCookieRow, CookieRow>({\n file: cookieFile,\n sql,\n params,\n rowTransform: (row: ChromeCookieRow): CookieRow => ({\n name: row.name,\n domain: row.host_key,\n value: row.encrypted_value,\n expiry: row.expires_utc,\n }),\n });\n\n logOperationResult(\"QueryCookies\", true, {\n file: cookieFile,\n count: rows.length,\n });\n return rows;\n } catch (error) {\n logError(\"Failed to read cookie file\", error, { file: cookieFile });\n return [];\n }\n}\n\n/**\n * Retrieve encrypted cookies from Chrome's cookie store\n * @param options - Options for querying Chrome cookies\n * @param options.name - The name of the cookie to retrieve\n * @param options.domain - The domain to retrieve cookies from\n * @param options.file - Optional specific cookie file to query\n * @returns Promise resolving to array of encrypted cookies\n */\nexport async function getEncryptedChromeCookie({\n name,\n domain,\n file,\n}: GetEncryptedCookieOptions): Promise<CookieRow[]> {\n const cookieFiles =\n typeof file === \"string\" && file.length > 0\n ? [file]\n : await getCookieFiles();\n\n if (cookieFiles.length === 0) {\n logDebug(\"ChromeCookies\", \"No cookie files found\");\n return [];\n }\n\n const results: CookieRow[] = [];\n for (const cookieFile of cookieFiles) {\n if (!isValidFilePath(cookieFile)) {\n logDebug(\"ChromeCookies\", \"Cookie file missing or invalid\", {\n file: cookieFile,\n });\n continue;\n }\n\n const cookies = await processCookieFile(cookieFile, name, domain);\n results.push(...cookies);\n }\n\n logDebug(\"ChromeCookies\", \"Query complete\", { totalCookies: results.length });\n return results;\n}\n","import { homedir } from \"os\";\nimport { join } from \"path\";\n\n/**\n * The path to Chrome's application support directory on macOS\n * This constant is used to locate Chrome's profile and cookie storage directories\n * @throws {Error} If unable to determine user's home directory\n */\nexport const chromeApplicationSupport = (() => {\n const home = homedir();\n if (!home) {\n throw new Error(\"Unable to determine user home directory\");\n }\n return join(home, \"Library\", \"Application Support\", \"Google\", \"Chrome\");\n})();\n","// External imports\nimport BetterSqlite3, { Database } from \"better-sqlite3\";\n\n// Internal imports\nimport { logError } from \"@utils/logHelpers\";\n\ninterface QuerySqliteThenTransformOptions<TRow, TResult> {\n file: string;\n sql: string;\n params?: unknown[];\n rowFilter?: (row: TRow) => boolean;\n rowTransform?: (row: TRow) => TResult;\n}\n\nfunction openDatabase(file: string): Database {\n try {\n return new BetterSqlite3(file, { readonly: true, fileMustExist: true });\n } catch (error) {\n logError(\"Database open failed\", error, { file });\n throw error;\n }\n}\n\nfunction closeDatabase(db: Database): Promise<void> {\n try {\n db.close();\n return Promise.resolve();\n } catch (error) {\n logError(\"Database close failed\", error);\n return Promise.reject(\n error instanceof Error\n ? error\n : new Error(\"Failed to close database: Unknown error\"),\n );\n }\n}\n\n/**\n * Executes a SQL query on a SQLite database file and transforms the results\n * @param root0 - The options object containing query parameters\n * @param root0.file - The path to the SQLite database file\n * @param root0.sql - The SQL query to execute\n * @param root0.params - Optional parameters for the SQL query\n * @param root0.rowFilter - Optional function to filter rows from the result set\n * @param root0.rowTransform - Optional function to transform each row before returning\n * @returns A promise that resolves to an array of transformed results\n */\nexport async function querySqliteThenTransform<TRow, TResult>({\n file,\n sql,\n params,\n rowFilter,\n rowTransform,\n}: QuerySqliteThenTransformOptions<TRow, TResult>): Promise<TResult[]> {\n let db: Database | undefined;\n\n try {\n db = openDatabase(file);\n const stmt = db.prepare(sql);\n const rows = stmt.all(params) as TRow[];\n\n const filteredRows = rowFilter ? rows.filter(rowFilter) : rows;\n const transformedRows = rowTransform\n ? filteredRows.map(rowTransform)\n : (filteredRows as unknown as TResult[]);\n\n return transformedRows;\n } catch (error) {\n logError(\"Database query failed\", error, { file, sql });\n throw error;\n } finally {\n if (db) {\n await closeDatabase(db);\n }\n }\n}\n","// External imports\nimport { readFileSync } from \"fs\";\nimport { join } from \"path\";\n\nimport fg from \"fast-glob\";\n\n// Internal imports\nimport logger from \"@utils/logger\";\n\nimport { chromeApplicationSupport } from \"./chrome/ChromeApplicationSupport\";\n\nconst consola = logger.withTag(\"listChromeProfiles\");\n\n/**\n * Lists all Chrome profile paths that contain cookie files\n * @internal\n * @returns An array of absolute paths to Chrome cookie files\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome cookie file paths\n * const cookiePaths = listChromeProfilePaths();\n * // Returns: [\n * // '/Users/name/Library/Application Support/Chrome/Profile 1/Cookies',\n * // '/Users/name/Library/Application Support/Chrome/Profile 2/Cookies'\n * // ]\n *\n * // Handle errors\n * try {\n * const paths = listChromeProfilePaths();\n * } catch (error) {\n * console.error('Failed to access Chrome profiles:', error);\n * }\n * ```\n */\nexport function listChromeProfilePaths(): string[] {\n const files: string[] = fg.sync(`./**/Cookies`, {\n cwd: chromeApplicationSupport,\n absolute: true,\n });\n\n consola.debug(\"Found cookie files:\", files);\n return files;\n}\n\n/**\n * Chrome Local State file structure\n * @internal\n */\ninterface ChromeLocalState {\n profile: {\n info_cache: Record<string, ChromeProfileInfo>;\n };\n}\n\n/**\n * Chrome profile information structure\n * @property {string} name - The name of the profile\n * @property {number} active_time - Unix timestamp of last profile activity\n * @property {string} account_id - Unique identifier for the Chrome profile\n * @property {Record<string, unknown>} accountcapabilities - Account feature flags\n * @property {string} email - User's email address\n * @property {string} full_name - User's full name\n * @property {boolean} is_using_default_avatar - Whether using default profile picture\n * @property {boolean} is_using_default_name - Whether using default profile name\n * @property {string} last_downloaded_gaia_picture_url_with_size - Profile picture URL\n * @property {string} local_auth_credentials - Authentication credentials\n * @property {string} shortcut_name - Profile shortcut name\n * @property {string} user_name - Username associated with profile\n */\ninterface ChromeProfileInfo {\n /** The name of the profile */\n name: string;\n /** Unix timestamp of last profile activity */\n active_time: number;\n /** Unique identifier for the Chrome profile */\n account_id: string;\n /** Account feature flags */\n accountcapabilities: Record<string, unknown>;\n /** User's email address */\n email: string;\n /** User's full name */\n full_name: string;\n /** Whether using default profile picture */\n is_using_default_avatar: boolean;\n /** Whether using default profile name */\n is_using_default_name: boolean;\n /** Profile picture URL */\n last_downloaded_gaia_picture_url_with_size: string;\n /** Authentication credentials */\n local_auth_credentials: string;\n /** Profile shortcut name */\n shortcut_name: string;\n /** Username associated with profile */\n user_name: string;\n}\n\n/**\n * Lists all Chrome profiles and their associated information\n * @internal\n * @returns An array of Chrome profile information objects. Returns empty array if profiles cannot be read\n * @throws {Error} If Chrome's application support directory cannot be accessed\n * @example\n * ```typescript\n * // Get all Chrome profiles\n * const profiles = listChromeProfiles();\n * // Returns: [\n * // {\n * // name: \"Default\",\n * // email: \"user@example.com\",\n * // full_name: \"John Doe\",\n * // ...\n * // },\n * // ...\n * // ]\n *\n * // Handle empty or error case\n * const profiles = listChromeProfiles();\n * if (profiles.length === 0) {\n * console.log('No Chrome profiles found or error occurred');\n * }\n * ```\n */\nexport function listChromeProfiles(): ChromeProfileInfo[] {\n try {\n const localStatePath = join(chromeApplicationSupport, \"Local State\");\n const localState = JSON.parse(\n readFileSync(localStatePath, \"utf8\"),\n ) as ChromeLocalState;\n return Object.values(localState.profile.info_cache);\n } catch (error) {\n if (error instanceof Error) {\n consola.error(\"Failed to read Chrome profiles:\", error.message);\n } else {\n consola.error(\"Failed to read Chrome profiles: Unknown error\");\n }\n return [];\n }\n}\n","// External imports\nimport { createDecipheriv, pbkdf2 } from \"crypto\";\n\nimport { memoize } from \"lodash-es\";\n\n/**\n * Removes the v10 prefix from the encrypted value if present\n * @param value - The encrypted value\n * @returns The value without the v10 prefix\n */\nconst removeV10Prefix = memoize(\n (value: Buffer): Buffer => {\n if (\n value.length >= 3 &&\n value[0] === 0x76 && // 'v'\n value[1] === 0x31 && // '1'\n value[2] === 0x30\n ) {\n // '0'\n return value.slice(3);\n }\n return value;\n },\n (value: Buffer) => value.toString(\"hex\"),\n);\n\n/**\n * Removes PKCS7 padding from the decrypted value\n * @param decrypted - The decrypted buffer\n * @returns The buffer without padding\n */\nconst removePadding = memoize(\n (decrypted: Buffer): Buffer => {\n const padding = decrypted[decrypted.length - 1];\n if (padding && padding <= 16) {\n return decrypted.slice(0, -padding);\n }\n return decrypted;\n },\n (decrypted: Buffer) => decrypted.toString(\"hex\"),\n);\n\n/**\n * Extracts the actual value from the decoded string by removing Chrome's prefixes\n * @param decodedString - The decoded string to clean up\n * @returns The cleaned up value\n */\nfunction extractValue(decodedString: string): string {\n const cleanupPatterns = [\n /.*?0t(.+)$/, // Pattern ending in \"0t\" followed by value\n /.*?1e`(.+)$/, // Pattern ending in \"1e`\" followed by value\n /.*?[`'](.+)$/, // Any backtick or quote followed by value\n /[^\\x20-\\x7E]*([\\x20-\\x7E].+)$/, // Non-printable chars followed by printable chars\n ];\n\n for (const pattern of cleanupPatterns) {\n const match = decodedString.match(pattern);\n const value = match?.[1] ?? \"\";\n if (value.length > 0) {\n return value;\n }\n }\n return decodedString;\n}\n\n/**\n * Decrypts Chrome's encrypted cookie values\n * @param encryptedValue - The encrypted cookie value as a Buffer\n * @param password - The Chrome encryption password\n * @returns A promise that resolves to the decrypted cookie value\n * @throws {Error} If decryption fails\n * @example\n */\nexport async function decrypt(\n encryptedValue: Buffer,\n password: string,\n): Promise<string> {\n if (typeof password !== \"string\") {\n throw new Error(\"password must be a string\");\n }\n if (!Buffer.isBuffer(encryptedValue)) {\n throw new Error(\"encryptedData must be a Buffer\");\n }\n\n return new Promise((resolve, reject) => {\n pbkdf2(password, \"saltysalt\", 1003, 16, \"sha1\", (error, key) => {\n try {\n if (error) {\n reject(new Error(\"Failed to derive key: \" + error.message));\n return;\n }\n\n const value = removeV10Prefix(encryptedValue);\n if (value.length % 16 !== 0) {\n reject(new Error(\"Encrypted data length is not a multiple of 16\"));\n return;\n }\n\n // Chrome's encryption parameters\n const iv = Buffer.alloc(16, \" \"); // 16 spaces\n const decipher = createDecipheriv(\"aes-128-cbc\", key, iv);\n decipher.setAutoPadding(false);\n\n // Decrypt the value\n let decrypted = decipher.update(value);\n try {\n decipher.final();\n } catch (e) {\n reject(\n new Error(\"Failed to finalize decryption: \" + (e as Error).message),\n );\n return;\n }\n\n decrypted = removePadding(decrypted);\n const decodedString = decrypted.toString(\"utf8\");\n resolve(extractValue(decodedString));\n } catch (e) {\n reject(new Error(\"Decryption failed: \" + (e as Error).message));\n }\n });\n });\n}\n","import { memoize } from \"lodash-es\";\n\nimport { logError, logDebug } from \"@utils/logHelpers\";\n\n/**\n * Retrieves the Chrome password for decrypting cookies\n * This is only supported on macOS\n * @returns A promise that resolves to the Chrome password\n * @throws {Error} If the platform is not macOS or if password retrieval fails\n * @example\n */\nexport const getChromePassword: () => Promise<string> = memoize(async () => {\n if (process.platform !== \"darwin\") {\n logError(\n \"Chrome password retrieval failed\",\n new Error(\"This only works on macOS\"),\n {\n platform: process.platform,\n },\n );\n throw new Error(\"This only works on macOS\");\n }\n\n try {\n const { getChromePassword: getMacOSPassword } = await import(\n \"./macos/getChromePassword\"\n );\n const password = await getMacOSPassword();\n logDebug(\"ChromePassword\", \"Retrieved password successfully\", {\n platform: \"macOS\",\n });\n return password;\n } catch (error) {\n logError(\"Chrome password retrieval failed\", error, { platform: \"macOS\" });\n throw error;\n }\n});\n","import { homedir } from \"os\";\nimport { join } from \"path\";\n\nimport fg from \"fast-glob\";\n\nimport { logDebug, logWarn } from \"@utils/logHelpers\";\n\nimport {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../../types/schemas\";\nimport { querySqliteThenTransform } from \"../QuerySqliteThenTransform\";\n\ninterface FirefoxCookieRow {\n name: string;\n value: string;\n domain: string;\n expiry: number;\n}\n\n/**\n * Find all Firefox cookie database files\n * @returns An array of file paths to Firefox cookie databases\n */\nfunction findFirefoxCookieFiles(): string[] {\n const home = homedir();\n if (!home) {\n logWarn(\"FirefoxCookieQuery\", \"Failed to get home directory\");\n return [];\n }\n\n const patterns = [\n join(home, \"Library/Application Support/Firefox/Profiles/*/cookies.sqlite\"),\n join(home, \".mozilla/firefox/*/cookies.sqlite\"),\n ];\n\n const files: string[] = [];\n for (const pattern of patterns) {\n const matches = fg.sync(pattern);\n files.push(...matches);\n }\n\n logDebug(\"FirefoxCookieQuery\", \"Found Firefox cookie files\", { files });\n return files;\n}\n\n/**\n * Strategy for querying cookies from Firefox browser\n * @example\n */\nexport class FirefoxCookieQueryStrategy implements CookieQueryStrategy {\n /**\n *\n */\n public readonly browserName: BrowserName = \"Firefox\";\n\n /**\n * Queries cookies from Firefox's cookie store\n * @param name - The name pattern to match cookies against\n * @param domain - The domain pattern to match cookies against\n * @returns A promise that resolves to an array of exported cookies\n */\n public async queryCookies(\n name: string,\n domain: string,\n ): Promise<ExportedCookie[]> {\n const files = findFirefoxCookieFiles();\n const results: ExportedCookie[] = [];\n\n for (const file of files) {\n try {\n const cookies = await querySqliteThenTransform<\n FirefoxCookieRow,\n ExportedCookie\n >({\n file,\n sql: \"SELECT name, value, host as domain, expiry FROM moz_cookies WHERE name = ? AND host LIKE ?\",\n params: [name, `%${domain}%`],\n rowTransform: (row) => ({\n name: row.name,\n value: row.value,\n domain: row.domain,\n expiry: row.expiry > 0 ? new Date(row.expiry * 1000) : \"Infinity\",\n meta: {\n file,\n browser: \"Firefox\",\n decrypted: false,\n },\n }),\n });\n\n results.push(...cookies);\n } catch (error) {\n if (error instanceof Error) {\n logWarn(\n \"FirefoxCookieQuery\",\n `Error reading Firefox cookie file ${file}`,\n { error: error.message },\n );\n } else {\n logWarn(\n \"FirefoxCookieQuery\",\n `Error reading Firefox cookie file ${file}`,\n );\n }\n }\n }\n\n return results;\n }\n}\n","import { homedir } from \"os\";\nimport { join } from \"path\";\n\nimport { logError } from \"@utils/logHelpers\";\n\nimport type {\n BrowserName,\n CookieQueryStrategy,\n ExportedCookie,\n} from \"../../../types/schemas\";\n\nimport { decodeBinaryCookies } from \"./decodeBinaryCookies\";\n\n/**\n * Strategy for querying cookies from Safari browser\n */\nexport class SafariCookieQueryStrategy implements CookieQueryStrategy {\n /**\n * The browser name for this strategy\n */\n public readonly browserName: BrowserName = \"Safari\";\n\n /**\n * Gets the path to Safari's cookie database\n * @param home - The user's home directory\n * @returns Path to the cookie database\n */\n private getCookieDbPath(home: string): string {\n return join(\n home,\n \"Library\",\n \"Containers\",\n \"com.apple.Safari\",\n \"Data\",\n \"Library\",\n \"Cookies\",\n \"Cookies.binarycookies\",\n );\n }\n\n /**\n * Decodes cookies from Safari's binary cookie file\n * @param cookieDbPath - Path to the cookie database\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @returns Array of exported cookies\n */\n private decodeCookies(\n cookieDbPath: string,\n name: string,\n domain: string,\n ): ExportedCookie[] {\n try {\n const cookies = decodeBinaryCookies(cookieDbPath);\n return cookies\n .filter(\n (cookie) =>\n (name === \"%\" || cookie.name === name) &&\n (domain === \"%\" || cookie.domain.includes(domain)),\n )\n .map((cookie) => ({\n domain: cookie.domain,\n name: cookie.name,\n value: Buffer.isBuffer(cookie.value)\n ? cookie.value.toString()\n : String(cookie.value),\n expiry:\n typeof cookie.expiry === \"number\" && cookie.expiry > 0\n ? new Date(cookie.expiry * 1000)\n : \"Infinity\",\n meta: {\n file: cookieDbPath,\n browser: \"Safari\" as const,\n decrypted: false,\n },\n }));\n } catch (error) {\n if (error instanceof Error) {\n logError(\n \"SafariCookieQueryStrategy\",\n `Error decoding ${cookieDbPath}`,\n { error, name, domain },\n );\n } else {\n logError(\n \"SafariCookieQueryStrategy\",\n `Error decoding ${cookieDbPath}`,\n { error: \"Unknown error\", name, domain },\n );\n }\n return [];\n }\n }\n\n /**\n * Query Safari's cookie storage for cookies matching the given criteria\n * @param name - Name of the cookie to find\n * @param domain - Domain to filter cookies by\n * @returns Array of matching cookies, or empty array if none found\n */\n public async queryCookies(\n name: string,\n domain: string,\n ): Promise<ExportedCookie[]> {\n const home = homedir();\n if (typeof home !== \"string\" || home.length === 0) {\n logError(\"SafariCookieQueryStrategy\", \"Failed to get home directory\");\n return Promise.resolve([]);\n }\n\n const cookieDbPath = this.getCookieDbPath(home);\n return Promise.resolve(this.decodeCookies(cookieDbPath, name || \"%\", domain || \"%\"));\n }\n}\n","import { Buffer } from 'buffer';\nimport { readFileSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\n\nimport { BinaryCookieRow } from '../../../types/schemas';\nimport { logWarn } from '../../../utils/logHelpers';\n\nimport { BinaryCodablePage } from './BinaryCodablePage';\nimport { BinaryCodableContainer } from './interfaces/BinaryCodableContainer';\n\n/**\n * Represents a binary cookies file structure used by Safari\n */\nexport class BinaryCodableCookies {\n /**\n *\n */\n public pages: BinaryCodablePage[];\n /**\n *\n */\n public metadata: Record<string, unknown>;\n private static readonly MAGIC = Buffer.from('cook', 'utf8');\n private static readonly FOOTER = BigInt('0x071720050000004b');\n private static readonly DEFAULT_COOKIE_PATH = join(\n homedir(),\n 'Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies'\n );\n\n /**\n * Creates a new BinaryCookies instance from a buffer\n * @param buffer - The raw binary cookie file data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.pages = [];\n this.metadata = {};\n this.decode(container);\n }\n\n /**\n * Creates a BinaryCookies instance from a file path\n * @param path - Path to the Safari Cookies.binarycookies file\n * @returns A new BinaryCookies instance\n */\n public static fromFile(path: string): BinaryCodableCookies {\n const buffer = readFileSync(path);\n return new BinaryCodableCookies(buffer);\n }\n\n /**\n * Creates a BinaryCookies instance from the default Safari cookies location\n * @returns A new BinaryCookies instance\n */\n public static fromDefaultPath(): BinaryCodableCookies {\n return BinaryCodableCookies.fromFile(BinaryCodableCookies.DEFAULT_COOKIE_PATH);\n }\n\n /**\n * Converts the binary cookie data into a validated array of cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const page of this.pages) {\n try {\n const pageCookies = page.toCookieRows();\n if (Array.isArray(pageCookies)) {\n cookies.push(...pageCookies);\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', 'Error converting page cookies', { error: errorMessage });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n try {\n // Check magic value\n const magic = container.buffer.subarray(container.offset, container.offset + 4);\n container.offset += 4;\n if (!magic.equals(BinaryCodableCookies.MAGIC)) {\n throw new Error('Missing magic value');\n }\n\n // Read page count\n const pageCount = container.buffer.readUInt32BE(container.offset);\n container.offset += 4;\n\n // Read page sizes\n const pageSizes: number[] = [];\n for (let i = 0; i < pageCount; i++) {\n pageSizes.push(container.buffer.readUInt32BE(container.offset));\n container.offset += 4;\n }\n\n // Calculate page offsets\n let currentOffset = container.offset;\n for (const pageSize of pageSizes) {\n try {\n const pageBuffer = container.buffer.subarray(currentOffset, currentOffset + pageSize);\n const page = new BinaryCodablePage(pageBuffer);\n this.pages.push(page);\n currentOffset += pageSize;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', `Error decoding page`, { error: errorMessage });\n currentOffset += pageSize; // Skip the problematic page\n }\n }\n container.offset = currentOffset;\n\n // Read checksum\n const _checksum = container.buffer.readUInt32BE(container.offset);\n container.offset += 4;\n\n // Read footer\n const footer = container.buffer.readBigUInt64BE(container.offset);\n container.offset += 8;\n if (footer !== BinaryCodableCookies.FOOTER) {\n logWarn('BinaryCookies', 'Invalid cookie file format: wrong footer');\n }\n\n // Read metadata plist\n const _plistData = container.buffer.subarray(container.offset);\n // Note: You'll need to implement or use a plist parser library here\n this.metadata = {}; // Placeholder for plist data\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', 'Error decoding binary cookies file', { error: errorMessage });\n throw error;\n }\n }\n}\n","import { Buffer } from 'buffer';\n\nimport { BinaryCookieRow } from '../../../types/schemas';\nimport { logWarn } from '../../../utils/logHelpers';\n\nimport { BinaryCodableCookie } from './BinaryCodableCookie';\nimport { BinaryCodableContainer } from './interfaces/BinaryCodableContainer';\n\n/**\n * Represents a page of cookies within the binary cookies file\n */\nexport class BinaryCodablePage {\n /**\n *\n */\n public cookies: BinaryCodableCookie[];\n private static readonly HEADER = 0x00000100;\n private static readonly FOOTER = 0x00000000;\n\n /**\n * Creates a new Page instance from a buffer\n * @param buffer - The raw binary page data\n */\n public constructor(buffer: Buffer) {\n this.cookies = [];\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n /**\n * Converts the page's cookies into validated cookie rows\n * @returns Array of validated cookie objects\n */\n public toCookieRows(): BinaryCookieRow[] {\n const cookies: BinaryCookieRow[] = [];\n\n for (const cookie of this.cookies) {\n try {\n const cookieRow = cookie.toCookieRow();\n if (cookieRow !== null) {\n cookies.push(cookieRow);\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', 'Error converting cookie', { error: errorMessage });\n }\n }\n\n return cookies;\n }\n\n private decode(container: BinaryCodableContainer): void {\n // Read page tag (4 bytes)\n const header = container.buffer.readUInt32BE(container.offset);\n container.offset += 4;\n if (header !== BinaryCodablePage.HEADER) {\n throw new Error('Invalid page header');\n }\n\n // Read number of cookies (4 bytes)\n const cookieCount = container.buffer.readUInt32LE(container.offset);\n container.offset += 4;\n\n // Store the page start offset for calculating absolute cookie positions\n const pageStart = container.offset - 8;\n\n // Read cookie offsets (4 bytes each)\n const cookieOffsets: number[] = [];\n for (let i = 0; i < cookieCount; i++) {\n const cookieOffset = container.buffer.readUInt32LE(container.offset);\n cookieOffsets.push(cookieOffset);\n container.offset += 4;\n }\n\n // Read page end marker (4 bytes)\n const footer = container.buffer.readUInt32BE(container.offset);\n container.offset += 4;\n if (footer !== BinaryCodablePage.FOOTER) {\n throw new Error('Invalid page footer');\n }\n\n // Read cookies at their offsets\n for (let i = 0; i < cookieCount; i++) {\n try {\n const cookieOffset = cookieOffsets[i];\n // Calculate absolute offset from page start\n const absoluteOffset = pageStart + cookieOffset;\n\n // Read cookie size from the cookie header\n const cookieSize = container.buffer.readUInt32LE(absoluteOffset);\n if (cookieSize < 48) { // Minimum cookie size is 48 bytes (header)\n logWarn('BinaryCookies', `Invalid cookie size ${cookieSize} at index ${i}`);\n continue;\n }\n\n // Ensure we don't read past the buffer\n if (absoluteOffset + cookieSize > container.buffer.length) {\n logWarn('BinaryCookies', `Cookie size ${cookieSize} at index ${i} would exceed buffer length`);\n continue;\n }\n\n const cookieBuffer = container.buffer.subarray(absoluteOffset, absoluteOffset + cookieSize);\n const cookie = new BinaryCodableCookie(cookieBuffer);\n this.cookies.push(cookie);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logWarn('BinaryCookies', `Error decoding cookie at index ${i}`, { error: errorMessage });\n }\n }\n }\n}\n","import { Buffer } from 'buffer';\n\nimport { BinaryCookieRow, BinaryCookieRowSchema } from '../../../types/schemas';\n\nimport { BinaryCodableContainer } from './interfaces/BinaryCodableContainer';\nimport { BinaryCodableFlags } from './interfaces/BinaryCodableFlags';\nimport { BinaryCodableOffsets } from './interfaces/BinaryCodableOffsets';\n\n/**\n * Represents a single cookie within a page\n */\nexport class BinaryCodableCookie {\n /**\n *\n */\n public version = 0;\n /**\n *\n */\n public url = '';\n /**\n *\n */\n public port?: number;\n /**\n *\n */\n public name = '';\n /**\n *\n */\n public path = '';\n /**\n *\n */\n public value = '';\n /**\n *\n */\n public comment?: string;\n /**\n *\n */\n public commentURL?: string;\n /**\n *\n */\n public flags: BinaryCodableFlags = {\n isSecure: false,\n isHTTPOnly: false,\n unknown1: false,\n unknown2: false\n };\n /**\n *\n */\n public expiration = 0;\n /**\n *\n */\n public creation = 0;\n\n /**\n * Creates a new Cookie instance from a buffer\n * @param buffer - The raw binary cookie data\n */\n public constructor(buffer: Buffer) {\n const container: BinaryCodableContainer = { offset: 0, buffer };\n this.decode(container);\n }\n\n private decodeUrlValue(value: string): string {\n let processed = value;\n let lastProcessed;\n do {\n lastProcessed = processed;\n try {\n processed = decodeURIComponent(processed);\n } catch {\n return lastProcessed;\n }\n } while (processed !== lastProcessed && processed.includes('%'));\n return processed;\n }\n\n private decodeJwtPayload(token: string): string | null {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n try {\n const payload = Buffer.from(parts[1], 'base64').toString('utf8');\n const parsed = JSON.parse(payload) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n private parseJsonValue(value: string): string | null {\n try {\n const parsed = JSON.parse(value) as Record<string, unknown>;\n return JSON.stringify(parsed);\n } catch {\n return null;\n }\n }\n\n private processValue(value: string): string {\n // First, try URL decoding\n const decoded = this.decodeUrlValue(value);\n\n // Then, try JWT decoding if it looks like a JWT token\n if (decoded.match(/^ey[A-Za-z0-9_-]+\\.ey[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/)) {\n const jwtPayload = this.decodeJwtPayload(decoded);\n if (typeof jwtPayload === 'string' && jwtPayload.length > 0) {\n return jwtPayload;\n }\n }\n\n // Finally, try JSON parsing if it looks like JSON\n if (decoded.startsWith('{') || decoded.startsWith('[')) {\n const jsonValue = this.parseJsonValue(decoded);\n if (typeof jsonValue === 'string' && jsonValue.length > 0) {\n return jsonValue;\n }\n }\n\n return decoded;\n }\n\n /**\n * Converts the cookie to a validated cookie row\n * @returns Validated cookie row object or null if validation fails\n */\n public toCookieRow(): BinaryCookieRow | null {\n try {\n // Convert flags to number\n const flagsValue = this.convertFlags();\n\n // Extract domain from URL\n const domain = this.url.replace(/^https?:\\/\\//, '').replace(/\\/.*$/, '') || 'uk';\n\n // Keep timestamps as they are (seconds since 2001-01-01)\n // The display layer will handle the conversion to human-readable dates\n const cookieRow = BinaryCookieRowSchema.parse({\n name: this.name.replace(/^: /, ''), // Remove leading ': ' if present\n value: this.processValue(this.value) || '', // Process and ensure value is never undefined\n domain,\n path: this.path || '/',\n expiry: this.expiration,\n creation: this.creation,\n flags: flagsValue,\n version: this.version,\n port: this.port,\n comment: this.comment,\n commentURL: this.commentURL\n });\n\n return cookieRow;\n } catch (_error) {\n return null;\n }\n }\n\n private readNullTerminatedString(container: BinaryCodableContainer, offset: number): string {\n let end = offset;\n while (end < container.buffer.length && container.buffer[end] !== 0) {\n end++;\n }\n const value = container.buffer.toString('utf8', offset, end);\n return value || '';\n }\n\n private readHeader(container: BinaryCodableContainer): { size: number; hasPort: number; offsets: BinaryCodableOffsets } {\n // Cookie size (4 bytes)\n const size = container.buffer.readUInt32LE(container.offset);\n container.offset += 4;\n\n // Unknown (4 bytes)\n container.offset += 4;\n\n // Cookie flags (4 bytes)\n const flagsValue = container.buffer.readUInt32LE(container.offset);\n container.offset += 4;\n this.flags = {\n isSecure: (flagsValue & 1) !== 0,\n isHTTPOnly: (flagsValue & 4) !== 0,\n unknown1: (flagsValue & 8) !== 0,\n unknown2: (flagsValue & 16) !== 0\n };\n\n // Unknown (4 bytes)\n const hasPort = container.buffer.readUInt32LE(container.offset);\n container.offset += 4;\n\n // String offsets (24 bytes total)\n const offsets = {\n urlOffset: container.buffer.readUInt32LE(container.offset),\n nameOffset: container.buffer.readUInt32LE(container.offset + 4),\n pathOffset: container.buffer.readUInt32LE(container.offset + 8),\n valueOffset: container.buffer.readUInt32LE(container.offset + 12),\n commentOffset: container.buffer.readUInt32LE(container.offset + 16),\n commentURLOffset: container.buffer.readUInt32LE(container.offset + 20)\n };\n\n return { size, hasPort, offsets };\n }\n\n private readTimestamps(container: BinaryCodableContainer): void {\n // Read expiration time (8 bytes, little-endian double)\n const expirationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n expirationBuffer[i] = container.buffer[container.offset + i];\n }\n const expiration = expirationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Read creation time (8 bytes, little-endian double)\n const creationBuffer = Buffer.alloc(8);\n for (let i = 0; i < 8; i++) {\n creationBuffer[i] = container.buffer[container.offset + i];\n }\n const creation = creationBuffer.readDoubleLE(0);\n container.offset += 8;\n\n // Store raw timestamps (seconds since 2001-01-01)\n // For expiration time, 0 means \"session cookie\" (expires when browser closes)\n // For creation time, 0 means \"no creation time recorded\"\n this.expiration = expiration;\n this.creation = creation;\n }\n\n private readStrings(container: BinaryCodableContainer, size: number, offsets: BinaryCodableOffsets): void {\n // All offsets are relative to the start of the cookie\n const cookieStart = 0; // Offsets are relative to the cookie buffer start\n\n // Read strings in order of their offsets\n const offsetEntries = [\n { field: 'url', offset: offsets.urlOffset },\n { field: 'name', offset: offsets.nameOffset },\n { field: 'path', offset: offsets.pathOffset },\n { field: 'value', offset: offsets.valueOffset },\n { field: 'comment', offset: offsets.commentOffset }\n ].filter(entry => entry.offset > 0)\n .sort((a, b) => a.offset - b.offset);\n\n // Calculate string lengths based on offset differences\n for (let i = 0; i < offsetEntries.length; i++) {\n const { field, offset } = offsetEntries[i];\n const nextOffset = i < offsetEntries.length - 1 ? offsetEntries[i + 1].offset : size;\n const length = nextOffset - offset;\n\n // Read string up to null terminator\n let end = cookieStart + offset;\n while (end < cookieStart + offset + length && container.buffer[end] !== 0) {\n end++;\n }\n const value = container.buffer.toString('utf8', cookieStart + offset, end);\n\n switch (field) {\n case 'url':\n this.url = value;\n break;\n case 'name':\n this.name = value;\n break;\n case 'path':\n this.path = value;\n break;\n case 'value':\n this.value = value;\n break;\n case 'comment':\n this.comment = value;\n break;\n }\n }\n }\n\n private decode(container: BinaryCodableContainer): void {\n const { size, hasPort, offsets } = this.readHeader(container);\n\n // Skip past all offsets (24 bytes)\n const baseOffset = container.offset;\n container.offset = baseOffset + 24;\n\n this.readTimestamps(container);\n\n if (hasPort > 0) {\n this.port = container.buffer.readUInt16LE(container.offset);\n container.offset += 2;\n }\n\n // Reset offset for string reading\n container.offset = baseOffset;\n this.readStrings(container, size, offsets);\n }\n\n private convertFlags(): number {\n return (this.flags.isSecure ? 0x1 : 0) |\n (this.flags.isHTTPOnly ? 0x4 : 0) |\n (this.flags.unknown1 ? 0x8 : 0) |\n (this.flags.unknown2 ? 0x10 : 0);\n }\n}\n","import destr from \"destr\";\nimport { z } from \"zod\";\n\n/**\n * Zod schema for cookie domain validation.\n * Enforces standard cookie domain rules.\n * @example\n * ```typescript\n * // Valid domains\n * CookieDomainSchema.parse(\"example.com\"); // OK\n * CookieDomainSchema.parse(\".example.com\"); // OK - leading dot is valid\n * CookieDomainSchema.parse(\"sub.example.com\"); // OK\n *\n * // Invalid domains\n * CookieDomainSchema.parse(\"\"); // Error: Domain cannot be empty\n * CookieDomainSchema.parse(\"invalid domain\"); // Error: Invalid domain format\n * ```\n */\nexport const CookieDomainSchema = z\n .string()\n .trim()\n .min(1, \"Domain cannot be empty\")\n .refine(\n (domain) =>\n /^\\.?[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(\n domain,\n ),\n \"Invalid domain format\",\n );\n\n/**\n * Zod schema for cookie name validation.\n * Enforces standard cookie name rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid names\n * CookieNameSchema.parse(\"session\"); // OK\n * CookieNameSchema.parse(\"auth_token\"); // OK\n * CookieNameSchema.parse(\"user-preference\"); // OK\n *\n * // Invalid names\n * CookieNameSchema.parse(\"\"); // Error: Cookie name cannot be empty\n * CookieNameSchema.parse(\"session;\"); // Error: Invalid cookie name format\n * CookieNameSchema.parse(\"my cookie\"); // Error: Invalid cookie name format\n * ```\n */\nexport const CookieNameSchema = z\n .string()\n .trim()\n .min(1, \"Cookie name cannot be empty\")\n .refine(\n (name) =>\n name === \"%\" || /^[!#$%&'()*+\\-.:0-9A-Z \\^_`a-z|~]+$/.test(name),\n \"Invalid cookie name format - must contain only valid characters (letters, numbers, and certain symbols) or be '%' for wildcard\",\n );\n\n/**\n * Zod schema for cookie path validation.\n * Enforces standard cookie path rules according to RFC 6265.\n * @example\n * ```typescript\n * // Valid paths\n * CookiePathSchema.parse(\"/\"); // OK\n * CookiePathSchema.parse(\"/api\"); // OK\n * CookiePathSchema.parse(\"/path/to/page\"); // OK\n *\n * // Invalid paths\n * CookiePathSchema.parse(\"\"); // Error: Path cannot be empty\n * CookiePathSchema.parse(\"invalid\"); // Error: Path must start with /\n * CookiePathSchema.parse(\"/path?query\"); // Error: Invalid path format\n * ```\n */\nexport const CookiePathSchema = z\n .string()\n .trim()\n .min(1, \"Path cannot be empty\")\n .refine((path) => path.startsWith(\"/\"), \"Path must start with /\")\n .refine(\n (path) => /^\\/[!#$%&'()*+,\\-./:=@\\w~]*$/.test(path),\n \"Invalid path format - must contain only valid URL path characters\",\n )\n .default(\"/\");\n\n/**\n * Zod schema for cookie value.\n * Attempts to parse JSON values using destr for better readability.\n */\nexport const CookieValueSchema = z\n .string()\n .trim()\n .transform((value) => destr(value))\n .pipe(z.any());\n\n/**\n * Zod schema for Safari binary cookie row.\n * Validates and enforces the structure of cookie data read from Safari's Cookies.binarycookies file.\n * @example\n * ```typescript\n * const cookieData = {\n * name: \"session\",\n * value: \"abc123\",\n * domain: \"example.com\",\n * path: \"/\",\n * expiry: 1735689600,\n * creation: 1672531200,\n * flags: 0x5, // Secure + HTTPOnly\n * };\n * const validCookie = BinaryCookieRowSchema.parse(cookieData);\n * ```\n */\nexport const BinaryCookieRowSchema = z.object({\n name: CookieNameSchema,\n value: CookieValueSchema,\n domain: CookieDomainSchema,\n path: CookiePathSchema,\n expiry: z.number().int(),\n creation: z.number().int(),\n flags: z.number().optional(),\n version: z.number().int().optional(),\n port: z.number().int().optional(),\n comment: z.string().optional(),\n commentURL: z.string().optional(),\n});\n\n/**\n * Type representing a decoded Safari binary cookie.\n * This type is inferred from the BinaryCookieRowSchema and includes all cookie properties.\n * @property name - The name of the cookie (non-empty string)\n * @property value - The value stored in the cookie\n * @property domain - The domain the cookie belongs to (non-empty string)\n * @property path - The path where the cookie is valid (defaults to \"/\")\n * @property expiry - Unix timestamp when the cookie expires\n * @property creation - Unix timestamp when the cookie was created\n * @property flags - Optional bit flags (e.g., Secure, HTTPOnly)\n * @property version - Optional cookie version number\n * @property port - Optional port number restriction\n * @property comment - Optional cookie comment\n * @property commentURL - Optional URL for the cookie's comment\n */\nexport type BinaryCookieRow = z.infer<typeof BinaryCookieRowSchema>;\n\n/**\n * Schema for cookie specification parameters\n * Defines the required fields for identifying a cookie\n * @example\n * ```typescript\n * // Validate a cookie specification\n * const spec = {\n * name: 'session',\n * domain: 'example.com'\n * };\n * const result = CookieSpecSchema.safeParse(spec);\n * if (result.success) {\n * console.log('Valid cookie spec:', result.data);\n * } else {\n * console.error('Invalid cookie spec:', result.error);\n * }\n *\n * // Invalid spec (empty name)\n * const invalidSpec = {\n * name: '',\n * domain: 'example.com'\n * };\n * // Throws: \"Cookie name cannot be empty\"\n * CookieSpecSchema.parse(invalidSpec);\n * ```\n */\nexport const CookieSpecSchema = z\n .object({\n name: CookieNameSchema,\n domain: CookieDomainSchema,\n })\n .strict();\n\n/**\n * Type definition for cookie specification\n * Used for specifying which cookie to query\n * @example\n * ```typescript\n * // Basic cookie spec\n * const spec: CookieSpec = {\n * name: 'auth',\n * domain: 'api.example.com'\n * };\n *\n * // Use in function parameters\n * function queryCookie(spec: CookieSpec): Promise<ExportedCookie[]> {\n * return getCookie(spec);\n * }\n *\n * // Array of specs\n * const specs: CookieSpec[] = [\n * { name: 'session', domain: 'app.example.com' },\n * { name: 'theme', domain: 'example.com' }\n * ];\n * ```\n */\nexport type CookieSpec = z.infer<typeof CookieSpecSchema>;\n\n/**\n * Schema for metadata about a cookie\n */\nexport const CookieMetaSchema = z\n .object({\n file: z.string().trim().min(1, \"File path cannot be empty\").optional(),\n browser: z.string().trim().optional(),\n decrypted: z.boolean().optional(),\n secure: z.boolean().optional(),\n httpOnly: z.boolean().optional(),\n path: CookiePathSchema.optional(),\n })\n .catchall(z.unknown())\n .strict();\n\n/**\n * Type definition for cookie metadata\n */\nexport type CookieMeta = z.infer<typeof CookieMetaSchema>;\n\n/**\n * Schema for exported cookie data\n * Represents a cookie with all its properties and metadata\n * @example\n * ```typescript\n * // Validate an exported cookie\n * const cookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n * const result = ExportedCookieSchema.safeParse(cookie);\n * if (result.success) {\n * console.log('Valid cookie:', result.data);\n * } else {\n * console.error('Invalid cookie:', result.error);\n * }\n *\n * // Cookie with infinite expiry\n * const infiniteCookie = {\n * ...cookie,\n * expiry: \"Infinity\"\n * };\n * ExportedCookieSchema.parse(infiniteCookie); // OK\n * ```\n */\nexport const ExportedCookieSchema = z\n .object({\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: CookieValueSchema,\n expiry: z\n .union([\n z.literal(\"Infinity\"),\n z.date(),\n z.number().int().positive(\"Expiry must be a positive number\"),\n ])\n .optional(),\n meta: CookieMetaSchema.optional(),\n })\n .strict();\n\n/**\n * Type definition for exported cookie data\n * Represents the structure of a cookie after it has been retrieved\n * @example\n * ```typescript\n * // Basic exported cookie\n * const cookie: ExportedCookie = {\n * domain: 'example.com',\n * name: 'session',\n * value: 'abc123',\n * expiry: new Date('2024-12-31'),\n * meta: {\n * file: '/path/to/cookies.db'\n * }\n * };\n *\n * // Process exported cookies\n * function processCookies(cookies: ExportedCookie[]): string[] {\n * return cookies.map(cookie => `${cookie.name}=${cookie.value}`);\n * }\n *\n * // Filter expired cookies\n * function filterExpired(cookies: ExportedCookie[]): ExportedCookie[] {\n * const now = new Date();\n * return cookies.filter(cookie =>\n * cookie.expiry === \"Infinity\" ||\n * (cookie.expiry instanceof Date && cookie.expiry > now)\n * );\n * }\n * ```\n */\nexport type ExportedCookie = z.infer<typeof ExportedCookieSchema>;\n\n/**\n * Schema for raw cookie data from browser stores\n */\nexport const CookieRowSchema = z\n .object({\n expiry: z.number().int().optional(),\n domain: CookieDomainSchema,\n name: CookieNameSchema,\n value: z.union([z.string(), z.instanceof(Buffer)]),\n })\n .strict();\n\n/**\n * Type definition for raw cookie data\n */\nexport type CookieRow = z.infer<typeof CookieRowSchema>;\n\n/**\n * Schema for cookie render options\n */\nexport const RenderOptionsSchema = z\n .object({\n format: z.enum([\"merged\", \"grouped\"]).optional(),\n separator: z.string().optional(),\n showFilePaths: z.boolean().optional(),\n })\n .strict();\n\n/**\n * Type definition for render options\n */\nexport type RenderOptions = z.infer<typeof RenderOptionsSchema>;\n\n/**\n * Schema for browser names\n */\nexport const BrowserNameSchema = z.enum([\n \"Chrome\",\n \"Firefox\",\n \"Safari\",\n \"internal\",\n \"unknown\",\n]);\n\n/**\n * Type definition for browser names\n */\nexport type BrowserName = z.infer<typeof BrowserNameSchema>;\n\n/**\n * Schema for cookie query strategy\n */\nexport const CookieQueryStrategySchema = z\n .object({\n browserName: BrowserNameSchema,\n queryCookies: z\n .function()\n .args(z.string(), z.string())\n .returns(z.promise(z.array(ExportedCookieSchema))),\n })\n .strict();\n\n/**\n * Type definition for cookie query strategy\n */\nexport type CookieQueryStrategy = z.infer<typeof CookieQueryStrategySchema>;\n\n/**\n * Type representing either a single cookie specification or an array of specifications.\n * Useful when you need to query multiple cookies in a single operation.\n * @example\n * ```typescript\n * // Single cookie spec\n * const single: MultiCookieSpec = {\n * domain: \"example.com\",\n * name: \"sessionId\"\n * };\n *\n * // Multiple cookie specs\n * const multiple: MultiCookieSpec = [\n * { domain: \"example.com\", name: \"sessionId\" },\n * { domain: \"api.example.com\", name: \"authToken\" }\n * ];\n * ```\n */\nexport type MultiCookieSpec = CookieSpec | CookieSpec[];\n","import type { BinaryCookieRow } from '../../../types/schemas';\n\nimport { BinaryCodableCookies } from './BinaryCodableCookies';\n\n/**\n * Decodes a Safari binary cookie file into an array of cookie objects.\n * @param cookieDbPath - Path to the Safari Cookies.binarycookies file\n * @returns Array of decoded cookie objects\n * @throws {Error} If the file cannot be read or has invalid format\n */\nexport function decodeBinaryCookies(cookieDbPath: string): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromFile(cookieDbPath);\n return cookies.toCookieRows();\n}\n\n/**\n * Retrieves cookies from Safari's binary cookie store.\n * @returns Array of decoded Safari cookies\n */\nexport function getSafariCookies(): BinaryCookieRow[] {\n const cookies = BinaryCodableCookies.fromDefaultPath();\n return cookies.toCookieRows();\n}\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport { ChromeCookieQueryStrategy } from \"../browsers/chrome/ChromeCookieQueryStrategy\";\nimport { FirefoxCookieQueryStrategy } from \"../browsers/firefox/FirefoxCookieQueryStrategy\";\nimport { SafariCookieQueryStrategy } from \"../browsers/safari/SafariCookieQueryStrategy\";\n\n/**\n * Queries cookies from all available browser strategies (Chrome, Firefox, Safari).\n * This function acts as a unified interface to retrieve cookies across different browsers.\n * @param cookieSpec - The cookie specification to query\n * @param cookieSpec.name - The name pattern to match cookies against (can include '%' as wildcard)\n * @param cookieSpec.domain - The domain to match cookies against\n * @returns Promise resolving to array of exported cookies from all available browsers\n * @remarks\n * - Returns empty array if cookieSpec is invalid or missing required fields\n * - Aggregates results from all available browser strategies\n * - Failed browser queries are gracefully handled and excluded from results\n * - Both name and domain fields are required and must be strings\n * @example\n * ```typescript\n * const cookies = await queryCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n * console.log(cookies); // Array of matching cookies from all browsers\n * ```\n */\nexport async function queryCookies(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n if (!cookieSpec.name || !cookieSpec.domain) {\n return [];\n }\n\n const { name, domain } = cookieSpec;\n if (typeof name !== \"string\" || typeof domain !== \"string\") {\n return [];\n }\n\n /**\n * Initialize all available browser-specific strategies\n * The order of strategies can affect performance but not functionality\n * Each strategy is responsible for its own error handling\n */\n const strategies = [\n new ChromeCookieQueryStrategy(),\n new FirefoxCookieQueryStrategy(),\n new SafariCookieQueryStrategy(),\n ];\n\n /**\n * Query all strategies in parallel and handle failures gracefully\n * Using Promise.allSettled ensures that failures in one strategy\n * don't prevent results from other strategies\n */\n const results = await Promise.allSettled(\n strategies.map((strategy) => strategy.queryCookies(name, domain)),\n );\n\n /**\n * Filter out failed promises and flatten successful results\n * Using PromiseFulfilledResult<ExportedCookie[]> ensures that only successful results are included\n */\n return results\n .filter(\n (result): result is PromiseFulfilledResult<ExportedCookie[]> =>\n result.status === \"fulfilled\",\n )\n .flatMap((result) => result.value);\n}\n\n/**\n * Default export of the queryCookies function.\n * This is the recommended way to import the function for most use cases.\n * @example\n * ```typescript\n * import queryCookies from './queryCookies';\n *\n * // Query cookies with specific name\n * const sessionCookies = await queryCookies({\n * name: 'sessionId',\n * domain: 'example.com'\n * });\n *\n * // Query all cookies for a domain using wildcard\n * const allCookies = await queryCookies({\n * name: '%',\n * domain: 'example.com'\n * });\n * ```\n */\nexport default queryCookies;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\nimport { ChromeCookieQueryStrategy } from \"../browsers/chrome/ChromeCookieQueryStrategy\";\n\n/**\n * Retrieves cookies from Chrome browser storage that match the specified criteria.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * import { getChromeCookie } from \"@mherod/get-cookie\";\n *\n * // Get all cookies named \"sessionId\" from Chrome\n * const cookies = await getChromeCookie({ name: \"sessionId\" });\n *\n * // Get cookies named \"userPref\" from specific domain in Chrome\n * const domainCookies = await getChromeCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport async function getChromeCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const strategy = new ChromeCookieQueryStrategy();\n const cookies = await strategy.queryCookies(\n cookieSpec.name,\n cookieSpec.domain,\n );\n return cookies;\n } catch (error: unknown) {\n logger.warn(\"Error querying Chrome cookies:\", error);\n return [];\n }\n}\n\n/**\n * Default export of the getChromeCookie function.\n * @example\n * ```typescript\n * import { getChromeCookie } from \"@mherod/get-cookie\";\n * const cookies = await getChromeCookie({\n * name: \"sessionId\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport default getChromeCookie;\n","import type { CookieSpec, ExportedCookie } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\nimport { FirefoxCookieQueryStrategy } from \"../browsers/firefox/FirefoxCookieQueryStrategy\";\n\n/**\n * Retrieves cookies from Firefox browser storage that match the specified criteria.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @returns An array of ExportedCookie objects that match the specification\n * @throws Will catch and handle any errors during cookie querying, logging a warning\n * to the console without throwing to the caller\n * @example\n * ```typescript\n * import { getFirefoxCookie } from \"@mherod/get-cookie\";\n *\n * // Get all cookies named \"sessionId\" from Firefox\n * const cookies = await getFirefoxCookie({ name: \"sessionId\" });\n *\n * // Get cookies named \"userPref\" from specific domain in Firefox\n * const domainCookies = await getFirefoxCookie({\n * name: \"userPref\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport async function getFirefoxCookie(\n cookieSpec: CookieSpec,\n): Promise<ExportedCookie[]> {\n try {\n const strategy = new FirefoxCookieQueryStrategy();\n const cookies = await strategy.queryCookies(\n cookieSpec.name,\n cookieSpec.domain,\n );\n return cookies;\n } catch (error: unknown) {\n logger.warn(\n \"Error querying Firefox cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getFirefoxCookie function.\n * @example\n * ```typescript\n * import { getFirefoxCookie } from \"@mherod/get-cookie\";\n * const sessionCookies = await getFirefoxCookie({\n * name: \"PHPSESSID\",\n * domain: \"example.com\"\n * });\n * ```\n */\nexport default getFirefoxCookie;\n","import type {\n RenderOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\nimport { ExportedCookieSchema } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { getCookie } from \"./getCookie\";\nimport { renderCookies } from \"./renderCookies\";\n\n/**\n * Retrieves and renders cookies in a grouped format based on their source files.\n * @param cookieSpec - The cookie specification containing search criteria\n * @param cookieSpec.name - The name of the cookie to search for\n * @param cookieSpec.domain - (optional) The domain to filter cookies by\n * @param options - Options for rendering the cookies\n * @param options.showFilePaths - Whether to include file paths in the output\n * @param options.separator - Custom separator for cookie values\n * @returns An array of strings, each representing a group of cookies from a source file\n * @example\n * ```typescript\n * // Basic usage - get all cookies named \"sessionId\" grouped by source file\n * const cookies = await getGroupedRenderedCookies({ name: \"sessionId\" });\n *\n * // Get cookies with domain filter and custom rendering options\n * const domainCookies = await getGroupedRenderedCookies(\n * {\n * name: \"userPref\",\n * domain: \"example.com\"\n * },\n * {\n * showFilePaths: true,\n * separator: \" | \"\n * }\n * );\n * ```\n */\nexport async function getGroupedRenderedCookies(\n cookieSpec: CookieSpec,\n options: Omit<RenderOptions, \"format\"> = {},\n): Promise<string[]> {\n try {\n const cookies = await getCookie(cookieSpec);\n if (!Array.isArray(cookies)) {\n return [];\n }\n\n // Validate each cookie against the schema\n const validatedCookies = cookies.filter(\n (cookie): cookie is ExportedCookie => {\n const result = ExportedCookieSchema.safeParse(cookie);\n if (!result.success) {\n logger.warn(\"Invalid cookie format:\", result.error.format());\n return false;\n }\n return true;\n },\n );\n\n return renderCookies(validatedCookies, {\n ...options,\n format: \"grouped\",\n }) as string[];\n } catch (error: unknown) {\n logger.warn(\n \"Error getting grouped rendered cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return [];\n }\n}\n\n/**\n * Default export of the getGroupedRenderedCookies function\n * @example\n * ```typescript\n * import getGroupedCookies from './getGroupedRenderedCookies';\n *\n * // Get all session cookies with custom separator\n * const sessionCookies = await getGroupedCookies(\n * { name: \"session_*\" },\n * { separator: \"\\n\" }\n * );\n *\n * // Get cookies from multiple domains\n * const multiDomainCookies = await getGroupedCookies({\n * name: \"tracking\",\n * domain: [\"site1.com\", \"site2.com\"]\n * });\n * ```\n */\nexport default getGroupedRenderedCookies;\n","import { groupBy } from \"lodash-es\";\n\nimport { ExportedCookie, RenderOptions } from \"../../types/schemas\";\n\n/**\n * Renders cookies as a string or array of strings based on the provided format option.\n * Supports merged format for single string output or grouped format for file-based grouping.\n * @param cookies - The cookies to render\n * @param options - Options for rendering\n * @param options.format - The output format ('merged' or 'grouped')\n * @param options.showFilePaths - Whether to include file paths in grouped output\n * @param options.separator - Custom separator for cookie values\n * @returns A string for merged format, or array of strings for grouped format\n * @example\n * ```typescript\n * // Merged format (default)\n * const cookies = [\n * { value: 'sessionId=abc123' },\n * { value: 'theme=dark' }\n * ];\n * renderCookies(cookies);\n * // Returns: \"sessionId=abc123; theme=dark\"\n *\n * // Grouped format with file paths\n * const groupedCookies = [\n * { value: 'sessionId=abc123', meta: { file: 'auth.ts' } },\n * { value: 'theme=dark', meta: { file: 'preferences.ts' } }\n * ];\n * renderCookies(groupedCookies, { format: 'grouped', showFilePaths: true });\n * // Returns: [\"auth.ts: sessionId=abc123\", \"preferences.ts: theme=dark\"]\n * ```\n */\nexport function renderCookies(\n cookies: ExportedCookie[],\n options: RenderOptions = {},\n): string | string[] {\n const { format = \"merged\", showFilePaths = true, separator = \"; \" } = options;\n\n if (cookies.length === 0) {\n return format === \"merged\" ? \"\" : [];\n }\n\n if (format === \"merged\") {\n return cookies.map((c) => c.value as string).join(separator);\n }\n\n const groupedByFile = groupBy(cookies, (c) => c.meta?.file ?? \"unknown\");\n return Object.entries(groupedByFile).map(([file, fileCookies]) => {\n const values = fileCookies.map((c) => c.value as string).join(separator);\n return showFilePaths ? `${file}: ${values}` : values;\n });\n}\n","import type {\n RenderOptions,\n CookieSpec,\n ExportedCookie,\n} from \"../../types/schemas\";\nimport { ExportedCookieSchema } from \"../../types/schemas\";\nimport logger from \"../../utils/logger\";\n\nimport { getCookie } from \"./getCookie\";\nimport { renderCookies } from \"./renderCookies\";\n\n/**\n * Retrieves and renders cookies in a merged format\n * @param cookieSpec - The cookie specification to query\n * @param options - Optional rendering options\n * @returns Promise resolving to rendered cookie string\n * @example\n * ```typescript\n * const cookieString = await getMergedRenderedCookies(\n * { name: 'session', domain: 'example.com' },\n * { separator: '; ' }\n * );\n * console.log(cookieString); // \"session=abc123; auth=xyz789\"\n * ```\n */\nexport async function getMergedRenderedCookies(\n cookieSpec: CookieSpec,\n options?: Omit<RenderOptions, \"format\">,\n): Promise<string> {\n try {\n const cookies = await getCookie(cookieSpec);\n if (!Array.isArray(cookies)) {\n return \"\";\n }\n\n // Validate each cookie against the schema\n const validatedCookies = cookies.filter(\n (cookie): cookie is ExportedCookie => {\n const result = ExportedCookieSchema.safeParse(cookie);\n if (!result.success) {\n logger.warn(\"Invalid cookie format:\", result.error.format());\n return false;\n }\n return true;\n },\n );\n\n const result = renderCookies(validatedCookies, {\n ...options,\n format: \"merged\",\n });\n return typeof result === \"string\" ? result : \"\";\n } catch (error: unknown) {\n logger.warn(\n \"Error getting merged rendered cookies:\",\n error instanceof Error ? error.message : String(error),\n );\n return \"\";\n }\n}\n\n/**\n * Default export of the getMergedRenderedCookies function.\n * @example\n * ```typescript\n * import { getMergedRenderedCookies } from './getMergedRenderedCookies';\n * const cookies = await getMergedRenderedCookies({\n * name: 'sessionId',\n * domain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CAAC,EAIV,IAAME,EAAmBF,EAAQ,OAC9BG,GAAqC,CACpC,IAAMC,EAASC,EAAqB,UAAUF,CAAM,EACpD,OAAKC,EAAO,QAIL,IAHLE,EAAO,KAAK,yBAA0BF,EAAO,MAAM,OAAO,CAAC,EACpD,GAGX,CACF,EAEA,OAAOG,EAAcL,EAAkB,CACrC,GAAGH,EACH,OAAQ,SACV,CAAC,CACH,OAASS,EAAgB,CACvB,OAAAF,EAAO,KACL,0CACAE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CACvD,EACO,CAAC,CACV,CACF,CEjEAC,IAmBA,eAAsBC,EACpBC,EACAC,EACiB,CACjB,GAAI,CACF,IAAMC,EAAU,MAAMC,EAAUH,CAAU,EAC1C,GAAI,CAAC,MAAM,QAAQE,CAAO,EACxB,MAAO,GAIT,IAAME,EAAmBF,EAAQ,OAC9BG,GAAqC,CACpC,IAAMC,EAASC,EAAqB,UAAUF,CAAM,EACpD,OAAKC,EAAO,QAIL,IAHLE,EAAO,KAAK,yBAA0BF,EAAO,MAAM,OAAO,CAAC,EACpD,GAGX,CACF,EAEMA,EAASG,EAAcL,EAAkB,CAC7C,GAAGH,EACH,OAAQ,QACV,CAAC,EACD,OAAO,OAAOK,GAAW,SAAWA,EAAS,EAC/C,OAASI,EAAgB,CACvB,OAAAF,EAAO,KACL,yCACAE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CACvD,EACO,EACT,CACF","names":["import_os","import_dotenv","import_zod","EnvironmentSchema","env","init_config","__esmMin","val","import_consola","consola","isDebug","logger_default","init_logger","__esmMin","init_config","env","logOperationResult","operation","success","context","message","logger_default","logError","error","errorContext","logDebug","component","data","createTaggedLogger","logWarn","init_logHelpers","__esmMin","init_logger","handleExecutionError","error","command","CommandExecutionError","logError","commandError","execSimple","options","defaultOptions","stdout","stderr","execPromise","result","import_child_process","import_util","init_execSimple","__esmMin","init_logHelpers","message","originalError","getChromePassword_exports","__export","getChromePassword","import_lodash_es","getChromeSafeStoragePassword","init_getChromePassword","__esmMin","init_execSimple","execSimple","index_exports","__export","getChromeCookie","getCookie","getFirefoxCookie","getGroupedRenderedCookies","getMergedRenderedCookies","__toCommonJS","init_logger","init_logHelpers","import_fs","import_path","import_fast_glob","init_logHelpers","import_os","import_path","chromeApplicationSupport","home","import_better_sqlite3","init_logHelpers","openDatabase","file","BetterSqlite3","error","logError","closeDatabase","db","querySqliteThenTransform","sql","params","rowFilter","rowTransform","rows","filteredRows","isValidFilePath","path","trimmedPath","getCookieFiles","patterns","chromeApplicationSupport","files","pattern","matches","glob","logDebug","buildSqlQuery","name","domain","isWildcard","sql","params","processCookieFile","cookieFile","rows","querySqliteThenTransform","row","logOperationResult","error","logError","getEncryptedChromeCookie","file","cookieFiles","results","cookies","import_fs","import_path","import_fast_glob","init_logger","consola","logger_default","listChromeProfilePaths","files","fg","chromeApplicationSupport","import_crypto","import_lodash_es","removeV10Prefix","value","removePadding","decrypted","padding","extractValue","decodedString","cleanupPatterns","pattern","decrypt","encryptedValue","password","resolve","reject","error","key","iv","decipher","e","import_lodash_es","init_logHelpers","getChromePassword","logError","getMacOSPassword","password","logDebug","error","getExpiryDate","expiry","createExportedCookie","domain","name","value","file","decrypted","ChromeCookieQueryStrategy","createTaggedLogger","cookieFiles","listChromeProfilePaths","password","getChromePassword","error","logError","encryptedCookies","getEncryptedChromeCookie","context","cookie","result","decryptedValue","decrypt","import_os","import_path","import_fast_glob","init_logHelpers","findFirefoxCookieFiles","home","logWarn","patterns","files","pattern","matches","fg","logDebug","FirefoxCookieQueryStrategy","name","domain","results","file","cookies","querySqliteThenTransform","row","error","import_os","import_path","init_logHelpers","import_buffer","import_fs","import_os","import_path","init_logHelpers","init_logHelpers","import_buffer","import_destr","import_zod","CookieDomainSchema","domain","CookieNameSchema","name","CookiePathSchema","path","CookieValueSchema","value","destr","BinaryCookieRowSchema","CookieSpecSchema","CookieMetaSchema","ExportedCookieSchema","CookieRowSchema","RenderOptionsSchema","BrowserNameSchema","CookieQueryStrategySchema","BinaryCodableCookie","buffer","container","value","processed","lastProcessed","token","parts","payload","parsed","decoded","jwtPayload","jsonValue","flagsValue","domain","BinaryCookieRowSchema","offset","end","size","hasPort","offsets","expirationBuffer","i","expiration","creationBuffer","creation","offsetEntries","entry","a","b","field","length","baseOffset","_BinaryCodablePage","buffer","container","cookies","cookie","cookieRow","error","errorMessage","logWarn","header","cookieCount","pageStart","cookieOffsets","i","cookieOffset","footer","absoluteOffset","cookieSize","cookieBuffer","BinaryCodableCookie","BinaryCodablePage","_BinaryCodableCookies","buffer","container","path","cookies","page","pageCookies","error","errorMessage","logWarn","magic","pageCount","pageSizes","i","currentOffset","pageSize","pageBuffer","BinaryCodablePage","_checksum","footer","_plistData","BinaryCodableCookies","decodeBinaryCookies","cookieDbPath","BinaryCodableCookies","SafariCookieQueryStrategy","home","cookieDbPath","name","domain","decodeBinaryCookies","cookie","error","logError","queryCookies","cookieSpec","name","domain","strategies","ChromeCookieQueryStrategy","FirefoxCookieQueryStrategy","SafariCookieQueryStrategy","strategy","result","getCookie","cookieSpec","queryCookies","error","logger_default","init_logger","getChromeCookie","cookieSpec","ChromeCookieQueryStrategy","error","logger_default","init_logger","getFirefoxCookie","cookieSpec","FirefoxCookieQueryStrategy","error","logger_default","init_logger","import_lodash_es","renderCookies","cookies","options","format","showFilePaths","separator","c","groupedByFile","file","fileCookies","values","getGroupedRenderedCookies","cookieSpec","options","cookies","getCookie","validatedCookies","cookie","result","ExportedCookieSchema","logger_default","renderCookies","error","init_logger","getMergedRenderedCookies","cookieSpec","options","cookies","getCookie","validatedCookies","cookie","result","ExportedCookieSchema","logger_default","renderCookies","error"]}
|