@j0hanz/filesystem-mcp 2.9.0 → 2.9.1
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/README.md +1 -1
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +7 -1
- package/dist/core/errors.js.map +1 -1
- package/dist/core/file-uri.d.ts.map +1 -1
- package/dist/core/file-uri.js +2 -2
- package/dist/core/file-uri.js.map +1 -1
- package/dist/core/glob.d.ts +7 -0
- package/dist/core/glob.d.ts.map +1 -1
- package/dist/core/glob.js +35 -3
- package/dist/core/glob.js.map +1 -1
- package/dist/core/search.d.ts.map +1 -1
- package/dist/core/search.js +2 -0
- package/dist/core/search.js.map +1 -1
- package/dist/core/util.d.ts +6 -0
- package/dist/core/util.d.ts.map +1 -1
- package/dist/core/util.js +8 -0
- package/dist/core/util.js.map +1 -1
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +2 -2
- package/dist/resources.js.map +1 -1
- package/dist/tools/list.d.ts.map +1 -1
- package/dist/tools/list.js +9 -6
- package/dist/tools/list.js.map +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +7 -11
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/replace-text.d.ts.map +1 -1
- package/dist/tools/replace-text.js +1 -0
- package/dist/tools/replace-text.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
Read, search, edit, and patch files in the folders you choose.<br>
|
|
8
8
|
Secret files stay hidden, and risky changes wait for your OK.
|
|
9
9
|
|
|
10
|
-
[](https://www.npmjs.com/package/@j0hanz/filesystem-mcp) [](https://github.com/j0hanz/filesystem-mcp/actions/workflows/ci.yml) [](LICENSE) [](https://github.com/j0hanz/filesystem-mcp/stargazers)
|
|
10
|
+
[](https://www.npmjs.com/package/@j0hanz/filesystem-mcp) [](https://github.com/j0hanz/filesystem-mcp/actions/workflows/ci.yml) [](LICENSE) [](https://github.com/j0hanz/filesystem-mcp/stargazers) [](https://hol.org/registry/plugins/j0hanz%2Ffilesystem-mcp)
|
|
11
11
|
|
|
12
12
|
[](https://vscode.dev/redirect/mcp/install?name=filesystem&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40j0hanz%2Ffilesystem-mcp%40latest%22%5D%7D) [](https://insiders.vscode.dev/redirect/mcp/install?name=filesystem&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40j0hanz%2Ffilesystem-mcp%40latest%22%5D%7D&quality=insiders) [](https://vs-open.link/mcp-install?%7B%22filesystem-mcp%22%3A%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40j0hanz%2Ffilesystem-mcp%40latest%22%5D%7D%7D) [](https://cursor.com/en/install-mcp?name=filesystem&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkBqMGhhbnovZmlsZXN5c3RlbS1tY3BAbGF0ZXN0Il19) [](https://github.com/j0hanz/filesystem-mcp/releases/latest/download/filesystem-mcp.mcpb)
|
|
13
13
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,SAAS;;;;;;;;;;;;;;CAcZ,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,SAAS,CAAC,CAAC,MAAM,OAAO,SAAS,CAAC,CAAC;AAEnE,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,UAAU,qBAAqB;IAC7B,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC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,CAAC;AAkDH,gFAAgF;AAChF,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAS1D;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,OAAO,CAE1D;AAoBD,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,cAAc,CAK1E;AAED,mFAAmF;AACnF,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,cAAc,CAE9E;AAED,mFAAmF;AACnF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,cAAc,CAE/E;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAMrD;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAQhE;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,CAE3D;AAeD,qBAAa,OAAQ,SAAQ,KAAK;IAChC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B,8FAA8F;gBAE5F,IAAI,EAAE,SAAS,EACf,OAAO,EAAE,MAAM,EACf,IAAI,CAAC,EAAE,MAAM,EACb,KAAK,CAAC,EAAE,OAAO,EACf,UAAU,GAAE,MAAM,GAAG,SAAqC;IAO5D,IAAI,IAAI,IAAI,SAAS,CAEpB;CACF"}
|
package/dist/core/errors.js
CHANGED
|
@@ -77,7 +77,13 @@ export const SKIPPABLE_FS_CODES = new Set([
|
|
|
77
77
|
ErrorCode.PERMISSION_DENIED,
|
|
78
78
|
ErrorCode.SYMLINK_NOT_ALLOWED,
|
|
79
79
|
]);
|
|
80
|
-
|
|
80
|
+
// Derived, not hand-maintained: an errno is skippable exactly when the code
|
|
81
|
+
// ERRNO_MAP classifies it as a code in SKIPPABLE_FS_CODES. EPERM maps to
|
|
82
|
+
// PERMISSION_DENIED, so OS-level EPERM is as skippable as EACCES — the hand-
|
|
83
|
+
// maintained list above omitted it and diverged from its own comment.
|
|
84
|
+
const SKIPPABLE_ERRNOS = new Set(Object.entries(ERRNO_MAP)
|
|
85
|
+
.filter(([, code]) => SKIPPABLE_FS_CODES.has(code))
|
|
86
|
+
.map(([errno]) => errno));
|
|
81
87
|
/**
|
|
82
88
|
* Walk `error` and its `cause` chain once for the three facts error handling
|
|
83
89
|
* needs: an abort anywhere, a timeout anywhere, and the FIRST errno seen.
|
package/dist/core/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,aAAa,EAAE,eAAe;IAC9B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;IACpB,aAAa,EAAE,eAAe;IAC9B,SAAS,EAAE,WAAW;IACtB,OAAO,EAAE,SAAS;IAClB,SAAS,EAAE,WAAW;IACtB,eAAe,EAAE,iBAAiB;IAClC,aAAa,EAAE,eAAe;IAC9B,iBAAiB,EAAE,mBAAmB;IACtC,mBAAmB,EAAE,qBAAqB;IAC1C,QAAQ,EAAE,UAAU;IACpB,OAAO,EAAE,SAAS;CACV,CAAC;AAgBX,SAAS,KAAK,CAAC,IAAe,EAAE,OAAe,EAAE,OAA8B,EAAE;IAC/E,OAAO;QACL,IAAI;QACJ,OAAO;QACP,GAAG,CAAC,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvD,GAAG,CAAC,IAAI,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC1E,CAAC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EACf,OAAe,EACf,IAAa,EACb,KAAe,EACf,aAAiC,mBAAmB,CAAC,IAAI,CAAC;QAE1D,KAAK,CAAC,OAAO,EAAE,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QACrD,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;QAC1D,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC;IACxB,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC3B,CAAC;CACF","sourcesContent":["export const ErrorCode = {\n ACCESS_DENIED: 'ACCESS_DENIED',\n NOT_FOUND: 'NOT_FOUND',\n NOT_FILE: 'NOT_FILE',\n NOT_DIRECTORY: 'NOT_DIRECTORY',\n TOO_LARGE: 'TOO_LARGE',\n TIMEOUT: 'TIMEOUT',\n CANCELLED: 'CANCELLED',\n INVALID_PATTERN: 'INVALID_PATTERN',\n INVALID_INPUT: 'INVALID_INPUT',\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n SYMLINK_NOT_ALLOWED: 'SYMLINK_NOT_ALLOWED',\n IO_ERROR: 'IO_ERROR',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\nexport interface Problem {\n readonly code: ErrorCode;\n readonly message: string;\n readonly path?: string;\n readonly suggestion?: string;\n}\n\ninterface ProblemFactoryOptions {\n path?: string | undefined;\n suggestion?: string | undefined;\n}\n\nfunction build(code: ErrorCode, message: string, opts: ProblemFactoryOptions = {}): Problem {\n return {\n code,\n message,\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n ...(opts.suggestion !== undefined ? { suggestion: opts.suggestion } : {}),\n };\n}\n\nexport const Problem = {\n invalidInput: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.INVALID_INPUT, msg, o),\n accessDenied: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.ACCESS_DENIED, msg, o),\n cancelled: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.CANCELLED, msg, o),\n fromUnknown(error: unknown, defaultCode: ErrorCode, path?: string): Problem {\n const problem = classify(error);\n const shouldOverride =\n problem.code === ErrorCode.UNKNOWN || problem.code === ErrorCode.IO_ERROR;\n const code = shouldOverride ? defaultCode : problem.code;\n const suggestion =\n (shouldOverride ? DEFAULT_SUGGESTIONS[code] : undefined) ??\n problem.suggestion ??\n DEFAULT_SUGGESTIONS[problem.code];\n return build(code, problem.message, { path: path ?? problem.path, suggestion });\n },\n toText(error: unknown, defaultCode: ErrorCode): string {\n return formatDetailedError(Problem.fromUnknown(error, defaultCode));\n },\n} as const;\n\nconst DEFAULT_SUGGESTIONS: Readonly<Partial<Record<ErrorCode, string>>> = {\n [ErrorCode.ACCESS_DENIED]: 'Run list_roots to list allowed directories.',\n [ErrorCode.NOT_FOUND]: 'Run list or find_files to verify the path.',\n [ErrorCode.NOT_FILE]: 'Target is a directory, not a file.',\n [ErrorCode.NOT_DIRECTORY]: 'Target is a file, not a directory.',\n [ErrorCode.TOO_LARGE]: 'Use head/tail or line ranges to read partially.',\n [ErrorCode.TIMEOUT]: 'Reduce scope, depth, or maxResults.',\n [ErrorCode.INVALID_PATTERN]: 'Check syntax and escape special characters.',\n [ErrorCode.PERMISSION_DENIED]: 'Check OS file permissions.',\n [ErrorCode.SYMLINK_NOT_ALLOWED]: 'Symlink escapes allowed directories.',\n};\n\nconst ERRNO_MAP: Readonly<Record<string, ErrorCode>> = {\n ENOENT: ErrorCode.NOT_FOUND,\n EACCES: ErrorCode.PERMISSION_DENIED,\n EPERM: ErrorCode.PERMISSION_DENIED,\n ENOTDIR: ErrorCode.NOT_DIRECTORY,\n EISDIR: ErrorCode.NOT_FILE,\n ELOOP: ErrorCode.SYMLINK_NOT_ALLOWED,\n ENAMETOOLONG: ErrorCode.INVALID_INPUT,\n ETIMEDOUT: ErrorCode.TIMEOUT,\n EMFILE: ErrorCode.IO_ERROR,\n ENFILE: ErrorCode.IO_ERROR,\n EBUSY: ErrorCode.IO_ERROR,\n ENOTEMPTY: ErrorCode.NOT_DIRECTORY,\n EEXIST: ErrorCode.INVALID_INPUT,\n EINVAL: ErrorCode.INVALID_INPUT,\n};\n\nconst ERRNO_RE = /^E[A-Z]+$/;\n\n// NOT_FOUND is in here (not just ENOENT) because a dangling symlink whose\n// target sits inside an allowed root surfaces as an FsError NOT_FOUND. Skipping\n// the entry is the point of a listing; rethrowing would fail the whole listing.\nexport const SKIPPABLE_FS_CODES: ReadonlySet<ErrorCode> = new Set([\n ErrorCode.ACCESS_DENIED,\n ErrorCode.NOT_FOUND,\n // OS-level EACCES/EPERM on a symlink target during a listing is exactly as\n // skippable as the other three codes.\n ErrorCode.PERMISSION_DENIED,\n ErrorCode.SYMLINK_NOT_ALLOWED,\n]);\n\nconst SKIPPABLE_ERRNOS: ReadonlySet<string> = new Set(['ENOENT', 'EACCES', 'ELOOP']);\n\n/**\n * Walk `error` and its `cause` chain once for the three facts error handling\n * needs: an abort anywhere, a timeout anywhere, and the FIRST errno seen.\n * `visited` guards a cyclic chain. A node that reads as an abort or a timeout\n * never also contributes its errno.\n */\nfunction scanCauseChain(error: unknown): {\n aborted: boolean;\n timedOut: boolean;\n errno: { code: string; path?: string } | undefined;\n} {\n const visited = new Set<unknown>();\n let aborted = false;\n let timedOut = false;\n let errno: { code: string; path?: string } | undefined;\n\n for (\n let current: unknown = error;\n current !== undefined && current !== null && !visited.has(current);\n current = (current as { cause?: unknown }).cause\n ) {\n visited.add(current);\n if (!(current instanceof Error)) continue;\n const raw = (current as { code?: unknown }).code;\n const code = typeof raw === 'string' ? raw : undefined;\n if (current.name === 'AbortError' || code === 'ABORT_ERR') {\n aborted = true;\n } else if (current.name === 'TimeoutError' || code === 'ETIMEDOUT') {\n timedOut = true;\n } else if (errno === undefined && code !== undefined && ERRNO_RE.test(code)) {\n const { path } = current as NodeJS.ErrnoException;\n errno = { code, ...(typeof path === 'string' ? { path } : {}) };\n }\n }\n\n return { aborted, timedOut, errno };\n}\n\n/** The scan's facts as a Problem: an abort wins, then a timeout, then errno. */\nexport function classifyCauseChain(error: unknown): Problem {\n const message = formatUnknownErrorMessage(error);\n const { aborted, timedOut, errno } = scanCauseChain(error);\n if (aborted) return Problem.cancelled(message);\n if (timedOut) return build(ErrorCode.TIMEOUT, message);\n if (errno !== undefined) {\n return build(ERRNO_MAP[errno.code] ?? ErrorCode.IO_ERROR, message, { path: errno.path });\n }\n return build(ErrorCode.UNKNOWN, message);\n}\n\nexport function isFsError(error: unknown): error is FsError {\n return error instanceof FsError;\n}\n\nfunction classify(error: unknown): Problem {\n if (error === null || error === undefined) {\n return build(ErrorCode.UNKNOWN, 'Unknown error');\n }\n if (isFsError(error)) return error.problem;\n // No `ZodError` branch, deliberately. Tool arguments are validated by the\n // SDK from the zod schema `defineTool` hands it (tools/define.ts); the SDK\n // formats issues itself and never throws a ZodError into a handler, and\n // nothing in `src/` calls `.parse()`. A ZodError reaching here would fall\n // through to UNKNOWN with Zod's raw JSON-dump `.message`, so if a\n // `.parse()` is ever added, add the branch back with it rather than\n // discovering this.\n if (!(error instanceof Error)) {\n return build(ErrorCode.UNKNOWN, typeof error === 'string' ? error : '[non-Error thrown]');\n }\n return classifyCauseChain(error);\n}\n\nexport function isNodeError(error: unknown): error is NodeJS.ErrnoException {\n if (!(error instanceof Error)) return false;\n if (!('code' in error)) return false;\n const { code } = error as { code?: unknown };\n return typeof code === 'string';\n}\n\n/** True when `error` is a Node errno error with code `ENOENT` (path not found). */\nexport function isNotFoundErrno(error: unknown): error is NodeJS.ErrnoException {\n return isNodeError(error) && error.code === 'ENOENT';\n}\n\n/** True when `error` is a Node errno error whose code is in `SKIPPABLE_ERRNOS`. */\nexport function isSkippableErrno(error: unknown): error is NodeJS.ErrnoException {\n return isNodeError(error) && error.code !== undefined && SKIPPABLE_ERRNOS.has(error.code);\n}\n\n/**\n * Rethrow when `error` reads as cancelled. Answers the question directly rather\n * than through `classify`, which allocated a Problem — and ran\n * `formatUnknownErrorMessage`, i.e. a `JSON.stringify` on a non-Error — for a\n * boolean. This sits in eight catch blocks, several inside per-entry scan loops.\n */\nexport function rethrowIfAborted(error: unknown): void {\n if (isFsError(error)) {\n if (error.code === ErrorCode.CANCELLED) throw error;\n return;\n }\n if (scanCauseChain(error).aborted) throw error;\n}\n\nexport function formatUnknownErrorMessage(error: unknown): string {\n if (typeof error === 'string') return error;\n if (error instanceof Error) return error.message;\n try {\n return JSON.stringify(error);\n } catch {\n return `[non-serializable: ${Object.prototype.toString.call(error)}]`;\n }\n}\n\nexport function normalizeUnknownError(error: unknown): Error {\n return error instanceof Error ? error : new Error(formatUnknownErrorMessage(error));\n}\n\nfunction formatDetailedError(\n error: Pick<Problem, 'code' | 'message' | 'path' | 'suggestion'>,\n): string {\n const lines: string[] = [`${error.code}: ${error.message}`];\n if (error.path && !error.message.includes(error.path)) {\n lines.push(error.path);\n }\n if (error.suggestion) {\n lines.push(error.suggestion);\n }\n return lines.join('\\n');\n}\n\nexport class FsError extends Error {\n readonly problem: Problem;\n\n /** `suggestion` replaces the code's default for a thrower that knows the better next step. */\n constructor(\n code: ErrorCode,\n message: string,\n path?: string,\n cause?: unknown,\n suggestion: string | undefined = DEFAULT_SUGGESTIONS[code],\n ) {\n super(message, cause === undefined ? {} : { cause });\n this.problem = build(code, message, { path, suggestion });\n this.name = 'FsError';\n }\n\n get code(): ErrorCode {\n return this.problem.code;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/core/errors.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,aAAa,EAAE,eAAe;IAC9B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;IACpB,aAAa,EAAE,eAAe;IAC9B,SAA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,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC3B,CAAC;CACF","sourcesContent":["export const ErrorCode = {\n ACCESS_DENIED: 'ACCESS_DENIED',\n NOT_FOUND: 'NOT_FOUND',\n NOT_FILE: 'NOT_FILE',\n NOT_DIRECTORY: 'NOT_DIRECTORY',\n TOO_LARGE: 'TOO_LARGE',\n TIMEOUT: 'TIMEOUT',\n CANCELLED: 'CANCELLED',\n INVALID_PATTERN: 'INVALID_PATTERN',\n INVALID_INPUT: 'INVALID_INPUT',\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n SYMLINK_NOT_ALLOWED: 'SYMLINK_NOT_ALLOWED',\n IO_ERROR: 'IO_ERROR',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];\n\nexport interface Problem {\n readonly code: ErrorCode;\n readonly message: string;\n readonly path?: string;\n readonly suggestion?: string;\n}\n\ninterface ProblemFactoryOptions {\n path?: string | undefined;\n suggestion?: string | undefined;\n}\n\nfunction build(code: ErrorCode, message: string, opts: ProblemFactoryOptions = {}): Problem {\n return {\n code,\n message,\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n ...(opts.suggestion !== undefined ? { suggestion: opts.suggestion } : {}),\n };\n}\n\nexport const Problem = {\n invalidInput: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.INVALID_INPUT, msg, o),\n accessDenied: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.ACCESS_DENIED, msg, o),\n cancelled: (msg: string, o?: ProblemFactoryOptions): Problem =>\n build(ErrorCode.CANCELLED, msg, o),\n fromUnknown(error: unknown, defaultCode: ErrorCode, path?: string): Problem {\n const problem = classify(error);\n const shouldOverride =\n problem.code === ErrorCode.UNKNOWN || problem.code === ErrorCode.IO_ERROR;\n const code = shouldOverride ? defaultCode : problem.code;\n const suggestion =\n (shouldOverride ? DEFAULT_SUGGESTIONS[code] : undefined) ??\n problem.suggestion ??\n DEFAULT_SUGGESTIONS[problem.code];\n return build(code, problem.message, { path: path ?? problem.path, suggestion });\n },\n toText(error: unknown, defaultCode: ErrorCode): string {\n return formatDetailedError(Problem.fromUnknown(error, defaultCode));\n },\n} as const;\n\nconst DEFAULT_SUGGESTIONS: Readonly<Partial<Record<ErrorCode, string>>> = {\n [ErrorCode.ACCESS_DENIED]: 'Run list_roots to list allowed directories.',\n [ErrorCode.NOT_FOUND]: 'Run list or find_files to verify the path.',\n [ErrorCode.NOT_FILE]: 'Target is a directory, not a file.',\n [ErrorCode.NOT_DIRECTORY]: 'Target is a file, not a directory.',\n [ErrorCode.TOO_LARGE]: 'Use head/tail or line ranges to read partially.',\n [ErrorCode.TIMEOUT]: 'Reduce scope, depth, or maxResults.',\n [ErrorCode.INVALID_PATTERN]: 'Check syntax and escape special characters.',\n [ErrorCode.PERMISSION_DENIED]: 'Check OS file permissions.',\n [ErrorCode.SYMLINK_NOT_ALLOWED]: 'Symlink escapes allowed directories.',\n};\n\nconst ERRNO_MAP: Readonly<Record<string, ErrorCode>> = {\n ENOENT: ErrorCode.NOT_FOUND,\n EACCES: ErrorCode.PERMISSION_DENIED,\n EPERM: ErrorCode.PERMISSION_DENIED,\n ENOTDIR: ErrorCode.NOT_DIRECTORY,\n EISDIR: ErrorCode.NOT_FILE,\n ELOOP: ErrorCode.SYMLINK_NOT_ALLOWED,\n ENAMETOOLONG: ErrorCode.INVALID_INPUT,\n ETIMEDOUT: ErrorCode.TIMEOUT,\n EMFILE: ErrorCode.IO_ERROR,\n ENFILE: ErrorCode.IO_ERROR,\n EBUSY: ErrorCode.IO_ERROR,\n ENOTEMPTY: ErrorCode.NOT_DIRECTORY,\n EEXIST: ErrorCode.INVALID_INPUT,\n EINVAL: ErrorCode.INVALID_INPUT,\n};\n\nconst ERRNO_RE = /^E[A-Z]+$/;\n\n// NOT_FOUND is in here (not just ENOENT) because a dangling symlink whose\n// target sits inside an allowed root surfaces as an FsError NOT_FOUND. Skipping\n// the entry is the point of a listing; rethrowing would fail the whole listing.\nexport const SKIPPABLE_FS_CODES: ReadonlySet<ErrorCode> = new Set([\n ErrorCode.ACCESS_DENIED,\n ErrorCode.NOT_FOUND,\n // OS-level EACCES/EPERM on a symlink target during a listing is exactly as\n // skippable as the other three codes.\n ErrorCode.PERMISSION_DENIED,\n ErrorCode.SYMLINK_NOT_ALLOWED,\n]);\n\n// Derived, not hand-maintained: an errno is skippable exactly when the code\n// ERRNO_MAP classifies it as a code in SKIPPABLE_FS_CODES. EPERM maps to\n// PERMISSION_DENIED, so OS-level EPERM is as skippable as EACCES — the hand-\n// maintained list above omitted it and diverged from its own comment.\nconst SKIPPABLE_ERRNOS: ReadonlySet<string> = new Set(\n Object.entries(ERRNO_MAP)\n .filter(([, code]) => SKIPPABLE_FS_CODES.has(code))\n .map(([errno]) => errno),\n);\n\n/**\n * Walk `error` and its `cause` chain once for the three facts error handling\n * needs: an abort anywhere, a timeout anywhere, and the FIRST errno seen.\n * `visited` guards a cyclic chain. A node that reads as an abort or a timeout\n * never also contributes its errno.\n */\nfunction scanCauseChain(error: unknown): {\n aborted: boolean;\n timedOut: boolean;\n errno: { code: string; path?: string } | undefined;\n} {\n const visited = new Set<unknown>();\n let aborted = false;\n let timedOut = false;\n let errno: { code: string; path?: string } | undefined;\n\n for (\n let current: unknown = error;\n current !== undefined && current !== null && !visited.has(current);\n current = (current as { cause?: unknown }).cause\n ) {\n visited.add(current);\n if (!(current instanceof Error)) continue;\n const raw = (current as { code?: unknown }).code;\n const code = typeof raw === 'string' ? raw : undefined;\n if (current.name === 'AbortError' || code === 'ABORT_ERR') {\n aborted = true;\n } else if (current.name === 'TimeoutError' || code === 'ETIMEDOUT') {\n timedOut = true;\n } else if (errno === undefined && code !== undefined && ERRNO_RE.test(code)) {\n const { path } = current as NodeJS.ErrnoException;\n errno = { code, ...(typeof path === 'string' ? { path } : {}) };\n }\n }\n\n return { aborted, timedOut, errno };\n}\n\n/** The scan's facts as a Problem: an abort wins, then a timeout, then errno. */\nexport function classifyCauseChain(error: unknown): Problem {\n const message = formatUnknownErrorMessage(error);\n const { aborted, timedOut, errno } = scanCauseChain(error);\n if (aborted) return Problem.cancelled(message);\n if (timedOut) return build(ErrorCode.TIMEOUT, message);\n if (errno !== undefined) {\n return build(ERRNO_MAP[errno.code] ?? ErrorCode.IO_ERROR, message, { path: errno.path });\n }\n return build(ErrorCode.UNKNOWN, message);\n}\n\nexport function isFsError(error: unknown): error is FsError {\n return error instanceof FsError;\n}\n\nfunction classify(error: unknown): Problem {\n if (error === null || error === undefined) {\n return build(ErrorCode.UNKNOWN, 'Unknown error');\n }\n if (isFsError(error)) return error.problem;\n // No `ZodError` branch, deliberately. Tool arguments are validated by the\n // SDK from the zod schema `defineTool` hands it (tools/define.ts); the SDK\n // formats issues itself and never throws a ZodError into a handler, and\n // nothing in `src/` calls `.parse()`. A ZodError reaching here would fall\n // through to UNKNOWN with Zod's raw JSON-dump `.message`, so if a\n // `.parse()` is ever added, add the branch back with it rather than\n // discovering this.\n if (!(error instanceof Error)) {\n return build(ErrorCode.UNKNOWN, typeof error === 'string' ? error : '[non-Error thrown]');\n }\n return classifyCauseChain(error);\n}\n\nexport function isNodeError(error: unknown): error is NodeJS.ErrnoException {\n if (!(error instanceof Error)) return false;\n if (!('code' in error)) return false;\n const { code } = error as { code?: unknown };\n return typeof code === 'string';\n}\n\n/** True when `error` is a Node errno error with code `ENOENT` (path not found). */\nexport function isNotFoundErrno(error: unknown): error is NodeJS.ErrnoException {\n return isNodeError(error) && error.code === 'ENOENT';\n}\n\n/** True when `error` is a Node errno error whose code is in `SKIPPABLE_ERRNOS`. */\nexport function isSkippableErrno(error: unknown): error is NodeJS.ErrnoException {\n return isNodeError(error) && error.code !== undefined && SKIPPABLE_ERRNOS.has(error.code);\n}\n\n/**\n * Rethrow when `error` reads as cancelled. Answers the question directly rather\n * than through `classify`, which allocated a Problem — and ran\n * `formatUnknownErrorMessage`, i.e. a `JSON.stringify` on a non-Error — for a\n * boolean. This sits in eight catch blocks, several inside per-entry scan loops.\n */\nexport function rethrowIfAborted(error: unknown): void {\n if (isFsError(error)) {\n if (error.code === ErrorCode.CANCELLED) throw error;\n return;\n }\n if (scanCauseChain(error).aborted) throw error;\n}\n\nexport function formatUnknownErrorMessage(error: unknown): string {\n if (typeof error === 'string') return error;\n if (error instanceof Error) return error.message;\n try {\n return JSON.stringify(error);\n } catch {\n return `[non-serializable: ${Object.prototype.toString.call(error)}]`;\n }\n}\n\nexport function normalizeUnknownError(error: unknown): Error {\n return error instanceof Error ? error : new Error(formatUnknownErrorMessage(error));\n}\n\nfunction formatDetailedError(\n error: Pick<Problem, 'code' | 'message' | 'path' | 'suggestion'>,\n): string {\n const lines: string[] = [`${error.code}: ${error.message}`];\n if (error.path && !error.message.includes(error.path)) {\n lines.push(error.path);\n }\n if (error.suggestion) {\n lines.push(error.suggestion);\n }\n return lines.join('\\n');\n}\n\nexport class FsError extends Error {\n readonly problem: Problem;\n\n /** `suggestion` replaces the code's default for a thrower that knows the better next step. */\n constructor(\n code: ErrorCode,\n message: string,\n path?: string,\n cause?: unknown,\n suggestion: string | undefined = DEFAULT_SUGGESTIONS[code],\n ) {\n super(message, cause === undefined ? {} : { cause });\n this.problem = build(code, message, { path, suggestion });\n this.name = 'FsError';\n }\n\n get code(): ErrorCode {\n return this.problem.code;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-uri.d.ts","sourceRoot":"","sources":["../../src/core/file-uri.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAKjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"file-uri.d.ts","sourceRoot":"","sources":["../../src/core/file-uri.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAKjE,OAAO,KAAK,EAAE,Q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avD;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE;IAC5C,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC7B,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,SAAS,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAAC;CAC1C,GAAG,eAAe,CAmBlB"}
|
package/dist/core/file-uri.js
CHANGED
|
@@ -2,7 +2,7 @@ import { basename } from 'node:path';
|
|
|
2
2
|
import { detectMimeFromContent } from "./mime.js";
|
|
3
3
|
import { IS_WINDOWS, toPosixPath } from "./path-utils.js";
|
|
4
4
|
import { countLines } from "./read.js";
|
|
5
|
-
import { getMaxTextFileSize, jsonBytesOver, MAX_OUTBOUND_RESULT_BYTES } from "./util.js";
|
|
5
|
+
import { base64EncodedBytes, getMaxTextFileSize, jsonBytesOver, MAX_OUTBOUND_RESULT_BYTES, } from "./util.js";
|
|
6
6
|
const KIB = 1024;
|
|
7
7
|
// Single owner of the `filesystem-mcp://file/` URI scheme — the template string,
|
|
8
8
|
// the path→URI encoder, the URI→path decoder, the link blocks built from them,
|
|
@@ -75,7 +75,7 @@ function overStdioRead(validPath, mimeType, size, written) {
|
|
|
75
75
|
return 6 * size > MAX_OUTBOUND_RESULT_BYTES - 64 * KIB;
|
|
76
76
|
// readRaw returns any non-text kind as base64 (`isBinary: kind !== 'text'`).
|
|
77
77
|
if (written.kind !== 'text') {
|
|
78
|
-
return
|
|
78
|
+
return base64EncodedBytes(size) > MAX_OUTBOUND_RESULT_BYTES - 64 * KIB;
|
|
79
79
|
}
|
|
80
80
|
const result = {
|
|
81
81
|
contents: [{ uri: buildFileResourceUri(validPath), mimeType, text: written.content }],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-uri.js","sourceRoot":"","sources":["../../src/core/file-uri.ts"],"names":[],"mapp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AACJ,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport { detectMimeFromContent } from './mime.ts';\nimport type { FileKind } from './mime.ts';\nimport { IS_WINDOWS, toPosixPath } from './path-utils.ts';\nimport { countLines } from './read.ts';\nimport { getMaxTextFileSize, jsonBytesOver, MAX_OUTBOUND_RESULT_BYTES } from './util.ts';\n\nconst KIB = 1024;\n\n// Single owner of the `filesystem-mcp://file/` URI scheme — the template string,\n// the path→URI encoder, the URI→path decoder, the link blocks built from them,\n// and the post-write metadata block every write tool reports alongside them.\n\nexport const FILESYSTEM_FILE_URI_TEMPLATE = 'filesystem-mcp://file/{+path}';\n\n/**\n * The `{+path}` template-variable form of a path — what `completion/complete`\n * must return, since a client expands a suggestion into the template verbatim.\n * Unescaped, a '#' or '?' in a filename truncates the URI into a fragment or\n * query (silently naming a different path) and a '%' makes the decode throw.\n * Separators are restored so the value still reads as a path. A backslash is\n * a separator only on Windows; on POSIX it is part of a name and stays `%5C`,\n * or `a\\b.txt` and `a/b.txt` would share one URI.\n */\nexport function encodeFileUriPath(validPath: string): string {\n const posix = IS_WINDOWS ? toPosixPath(validPath) : validPath;\n return encodeURIComponent(posix).replace(/%2F/gi, '/');\n}\n\n/** Inverse of {@link encodeFileUriPath}; `undefined` on invalid percent-encoding. */\nexport function decodeFileUriPath(encoded: string): string | undefined {\n try {\n return decodeURIComponent(encoded);\n } catch {\n return undefined;\n }\n}\n\nexport function buildFileResourceUri(validPath: string): string {\n return `filesystem-mcp://file/${encodeFileUriPath(validPath)}`;\n}\n\n/**\n * The link block for a URI already built by `buildFileResourceUri`. Callers that\n * hold the URI must use this rather than rebuilding from a path: a path that\n * differs only in case (the drive letter, on Windows) yields a *different* URI\n * string, and watchers key on that string — a link and a `resourceUri` that\n * disagree hand the client two subscriptions for one file.\n */\nexport function buildFileResourceLinkFor(\n uri: string,\n name: string,\n mimeType: string,\n size: number,\n /** ISO-8601 mtime of the file the link names, when the caller has one. */\n lastModified?: string,\n): ContentBlock {\n return {\n type: 'resource_link',\n uri,\n name,\n mimeType,\n size,\n annotations: {\n audience: ['user', 'assistant'],\n ...(lastModified !== undefined ? { lastModified } : {}),\n },\n };\n}\n\nfunction buildFileResourceLink(\n validPath: string,\n mimeType: string,\n size: number,\n lastModified?: string,\n): ContentBlock {\n return buildFileResourceLinkFor(\n buildFileResourceUri(validPath),\n basename(validPath),\n mimeType,\n size,\n lastModified,\n );\n}\n\nexport function extractPath(uri: string): string | undefined {\n const url = URL.parse(uri);\n if (url?.protocol !== 'filesystem-mcp:' || url.host !== 'file') return undefined;\n return decodeFileUriPath(url.pathname.slice(1));\n}\n\nexport interface WrittenFileMeta {\n size: number;\n lineCount: number;\n mimeType: string;\n kind: FileKind;\n /** Undefined unless {@link writtenFileLinks} allows it: see there for when. */\n resourceUri: string | undefined;\n /** Undefined unless {@link writtenFileLinks} allows it: see there for when. */\n resourceLink: ContentBlock | undefined;\n}\n\n/**\n * Whether stdio's resources/read would refuse this file: it measures the\n * JSON-encoded result, so escaping counts, and a file it reads as binary\n * comes back base64. Without the content, assume the worst escape (6 bytes\n * per byte) so a link is never one the read refuses.\n */\nfunction overStdioRead(\n validPath: string,\n mimeType: string,\n size: number,\n written: { content: string; kind: FileKind } | undefined,\n): boolean {\n if (written === undefined) return 6 * size > MAX_OUTBOUND_RESULT_BYTES - 64 * KIB;\n // readRaw returns any non-text kind as base64 (`isBinary: kind !== 'text'`).\n if (written.kind !== 'text') {\n return 4 * Math.ceil(size / 3) > MAX_OUTBOUND_RESULT_BYTES - 64 * KIB;\n }\n const result = {\n contents: [{ uri: buildFileResourceUri(validPath), mimeType, text: written.content }],\n };\n return jsonBytesOver(result, MAX_OUTBOUND_RESULT_BYTES) !== undefined;\n}\n\n/**\n * The URI and link a write tool may advertise for the file it wrote. None on a\n * dry run — nothing was written, so the file on disk is still the one the\n * caller already has. None when the size is unknown or over the text-size cap —\n * the store serves the URI via readRaw, which would reject it with TOO_LARGE.\n * File resources are read directly from disk, not from the result store.\n * `lastModified` is the post-write mtime when the caller stat'd the file; a\n * link without it is still valid. None over stdio when the read would refuse\n * it: the JSON-encoded result past `MAX_OUTBOUND_RESULT_BYTES` (escaping\n * counts, binary is base64), or, with no content to measure, any file whose\n * worst-case escape could be.\n */\nexport function writtenFileLinks(\n validPath: string,\n mimeType: string,\n size: number | undefined,\n dryRun = false,\n lastModified?: string,\n transport?: 'stdio' | 'http',\n written?: { content: string; kind: FileKind },\n): Pick<WrittenFileMeta, 'resourceUri' | 'resourceLink'> {\n if (\n dryRun ||\n size === undefined ||\n size > getMaxTextFileSize() ||\n (transport === 'stdio' && overStdioRead(validPath, mimeType, size, written))\n ) {\n return { resourceUri: undefined, resourceLink: undefined };\n }\n return {\n resourceUri: buildFileResourceUri(validPath),\n resourceLink: buildFileResourceLink(validPath, mimeType, size, lastModified),\n };\n}\n\n/**\n * The block every write tool reports for the content it wrote (or, with\n * `dryRun`, would have written): size, line count, MIME, and whatever\n * {@link writtenFileLinks} allows it to advertise. Named fields, because\n * `validPath` and `content` are both strings and a positional swap type-checks.\n */\nexport function buildWrittenFileMeta(options: {\n validPath: string;\n content: string;\n dryRun?: boolean | undefined;\n lastModified?: string | undefined;\n transport?: 'stdio' | 'http' | undefined;\n}): WrittenFileMeta {\n const { validPath, content } = options;\n const size = Buffer.byteLength(content, 'utf-8');\n const { mimeType, kind } = detectMimeFromContent(validPath, content);\n return {\n size,\n lineCount: countLines(content),\n mimeType,\n kind,\n ...writtenFileLinks(\n validPath,\n mimeType,\n size,\n options.dryRun,\n options.lastModified,\n options.transport,\n { content, kind },\n ),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"file-uri.js","sourceRoot":"","sources":["../../src/core/file-uri.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,UAAU,EAAE,WAA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AgB,EAChB,IAAwB,EACxB,MAAM,GAAG,KAAK,EACd,YAAqB,EACrB,SAA4B,EAC5B,OAA6C;IAE7C,IACE,MAAM;QACN,IAAI,KAAK,SAAS;QAClB,IAAI,GAAG,kBAAkB,EAAE;QAC3B,CAAC,SAAS,KAAK,OAAO,IAAI,aAAa,CAAC,SAAS,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,EAC5E,CAAC;QACD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;IAC7D,CAAC;IACD,OAAO;QACL,WAAW,EAAE,oBAAoB,CAAC,SAAS,CAAC;QAC5C,YAAY,EAAE,qBAAqB,CAAC,SAAS,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,CAAC;KAC7E,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAMpC;IACC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACvC,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACjD,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,qBAAqB,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IACrE,OAAO;QACL,IAAI;QACJ,SAAS,EAAE,UAAU,CAAC,OAAO,CAAC;QAC9B,QAAQ;QACR,IAAI;QACJ,GAAG,gBAAgB,CACjB,SAAS,EACT,QAAQ,EACR,IAAI,EACJ,OAAO,CAAC,MAAM,EACd,OAAO,CAAC,YAAY,EACpB,OAAO,CAAC,SAAS,EACjB,EAAE,OAAO,EAAE,IAAI,EAAE,CAClB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { basename } from 'node:path';\n\nimport { detectMimeFromContent } from './mime.ts';\nimport type { FileKind } from './mime.ts';\nimport { IS_WINDOWS, toPosixPath } from './path-utils.ts';\nimport { countLines } from './read.ts';\nimport {\n base64EncodedBytes,\n getMaxTextFileSize,\n jsonBytesOver,\n MAX_OUTBOUND_RESULT_BYTES,\n} from './util.ts';\n\nconst KIB = 1024;\n\n// Single owner of the `filesystem-mcp://file/` URI scheme — the template string,\n// the path→URI encoder, the URI→path decoder, the link blocks built from them,\n// and the post-write metadata block every write tool reports alongside them.\n\nexport const FILESYSTEM_FILE_URI_TEMPLATE = 'filesystem-mcp://file/{+path}';\n\n/**\n * The `{+path}` template-variable form of a path — what `completion/complete`\n * must return, since a client expands a suggestion into the template verbatim.\n * Unescaped, a '#' or '?' in a filename truncates the URI into a fragment or\n * query (silently naming a different path) and a '%' makes the decode throw.\n * Separators are restored so the value still reads as a path. A backslash is\n * a separator only on Windows; on POSIX it is part of a name and stays `%5C`,\n * or `a\\b.txt` and `a/b.txt` would share one URI.\n */\nexport function encodeFileUriPath(validPath: string): string {\n const posix = IS_WINDOWS ? toPosixPath(validPath) : validPath;\n return encodeURIComponent(posix).replace(/%2F/gi, '/');\n}\n\n/** Inverse of {@link encodeFileUriPath}; `undefined` on invalid percent-encoding. */\nexport function decodeFileUriPath(encoded: string): string | undefined {\n try {\n return decodeURIComponent(encoded);\n } catch {\n return undefined;\n }\n}\n\nexport function buildFileResourceUri(validPath: string): string {\n return `filesystem-mcp://file/${encodeFileUriPath(validPath)}`;\n}\n\n/**\n * The link block for a URI already built by `buildFileResourceUri`. Callers that\n * hold the URI must use this rather than rebuilding from a path: a path that\n * differs only in case (the drive letter, on Windows) yields a *different* URI\n * string, and watchers key on that string — a link and a `resourceUri` that\n * disagree hand the client two subscriptions for one file.\n */\nexport function buildFileResourceLinkFor(\n uri: string,\n name: string,\n mimeType: string,\n size: number,\n /** ISO-8601 mtime of the file the link names, when the caller has one. */\n lastModified?: string,\n): ContentBlock {\n return {\n type: 'resource_link',\n uri,\n name,\n mimeType,\n size,\n annotations: {\n audience: ['user', 'assistant'],\n ...(lastModified !== undefined ? { lastModified } : {}),\n },\n };\n}\n\nfunction buildFileResourceLink(\n validPath: string,\n mimeType: string,\n size: number,\n lastModified?: string,\n): ContentBlock {\n return buildFileResourceLinkFor(\n buildFileResourceUri(validPath),\n basename(validPath),\n mimeType,\n size,\n lastModified,\n );\n}\n\nexport function extractPath(uri: string): string | undefined {\n const url = URL.parse(uri);\n if (url?.protocol !== 'filesystem-mcp:' || url.host !== 'file') return undefined;\n return decodeFileUriPath(url.pathname.slice(1));\n}\n\nexport interface WrittenFileMeta {\n size: number;\n lineCount: number;\n mimeType: string;\n kind: FileKind;\n /** Undefined unless {@link writtenFileLinks} allows it: see there for when. */\n resourceUri: string | undefined;\n /** Undefined unless {@link writtenFileLinks} allows it: see there for when. */\n resourceLink: ContentBlock | undefined;\n}\n\n/**\n * Whether stdio's resources/read would refuse this file: it measures the\n * JSON-encoded result, so escaping counts, and a file it reads as binary\n * comes back base64. Without the content, assume the worst escape (6 bytes\n * per byte) so a link is never one the read refuses.\n */\nfunction overStdioRead(\n validPath: string,\n mimeType: string,\n size: number,\n written: { content: string; kind: FileKind } | undefined,\n): boolean {\n if (written === undefined) return 6 * size > MAX_OUTBOUND_RESULT_BYTES - 64 * KIB;\n // readRaw returns any non-text kind as base64 (`isBinary: kind !== 'text'`).\n if (written.kind !== 'text') {\n return base64EncodedBytes(size) > MAX_OUTBOUND_RESULT_BYTES - 64 * KIB;\n }\n const result = {\n contents: [{ uri: buildFileResourceUri(validPath), mimeType, text: written.content }],\n };\n return jsonBytesOver(result, MAX_OUTBOUND_RESULT_BYTES) !== undefined;\n}\n\n/**\n * The URI and link a write tool may advertise for the file it wrote. None on a\n * dry run — nothing was written, so the file on disk is still the one the\n * caller already has. None when the size is unknown or over the text-size cap —\n * the store serves the URI via readRaw, which would reject it with TOO_LARGE.\n * File resources are read directly from disk, not from the result store.\n * `lastModified` is the post-write mtime when the caller stat'd the file; a\n * link without it is still valid. None over stdio when the read would refuse\n * it: the JSON-encoded result past `MAX_OUTBOUND_RESULT_BYTES` (escaping\n * counts, binary is base64), or, with no content to measure, any file whose\n * worst-case escape could be.\n */\nexport function writtenFileLinks(\n validPath: string,\n mimeType: string,\n size: number | undefined,\n dryRun = false,\n lastModified?: string,\n transport?: 'stdio' | 'http',\n written?: { content: string; kind: FileKind },\n): Pick<WrittenFileMeta, 'resourceUri' | 'resourceLink'> {\n if (\n dryRun ||\n size === undefined ||\n size > getMaxTextFileSize() ||\n (transport === 'stdio' && overStdioRead(validPath, mimeType, size, written))\n ) {\n return { resourceUri: undefined, resourceLink: undefined };\n }\n return {\n resourceUri: buildFileResourceUri(validPath),\n resourceLink: buildFileResourceLink(validPath, mimeType, size, lastModified),\n };\n}\n\n/**\n * The block every write tool reports for the content it wrote (or, with\n * `dryRun`, would have written): size, line count, MIME, and whatever\n * {@link writtenFileLinks} allows it to advertise. Named fields, because\n * `validPath` and `content` are both strings and a positional swap type-checks.\n */\nexport function buildWrittenFileMeta(options: {\n validPath: string;\n content: string;\n dryRun?: boolean | undefined;\n lastModified?: string | undefined;\n transport?: 'stdio' | 'http' | undefined;\n}): WrittenFileMeta {\n const { validPath, content } = options;\n const size = Buffer.byteLength(content, 'utf-8');\n const { mimeType, kind } = detectMimeFromContent(validPath, content);\n return {\n size,\n lineCount: countLines(content),\n mimeType,\n kind,\n ...writtenFileLinks(\n validPath,\n mimeType,\n size,\n options.dryRun,\n options.lastModified,\n options.transport,\n { content, kind },\n ),\n };\n}\n"]}
|
package/dist/core/glob.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DirentLike } from './path-utils.ts';
|
|
2
|
+
import type { PathGuard } from './path.ts';
|
|
2
3
|
/**
|
|
3
4
|
* More brace alternatives than this is not a file filter. fs.glob's matcher
|
|
4
5
|
* dedupes its alternatives pairwise, synchronously: `{1..100000}` pins the
|
|
@@ -36,6 +37,12 @@ export interface GlobEntriesOptions {
|
|
|
36
37
|
* consulted; nothing above it is ever read. Ignored without `skipIgnored`.
|
|
37
38
|
*/
|
|
38
39
|
ignoreCeiling?: string;
|
|
40
|
+
/**
|
|
41
|
+
* Prune directories whose own name the sensitive denylist covers: the walk
|
|
42
|
+
* never descends into them nor yields them. Opt-in — a walk that must see
|
|
43
|
+
* sensitive entries (the move-protection check) does not pass it.
|
|
44
|
+
*/
|
|
45
|
+
pathGuard?: Pick<PathGuard, 'isSensitive'>;
|
|
39
46
|
/** Bounds the `.gitignore` discovery `skipIgnored` runs before the walk. */
|
|
40
47
|
signal?: AbortSignal;
|
|
41
48
|
}
|
package/dist/core/glob.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../src/core/glob.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../src/core/glob.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAElD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAG3C;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,OAAO,CAAC;AAE3C,qFAAqF;AACrF,eAAO,MAAM,sBAAsB,OAAO,CAAC;AAE3C;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,IAAI,CAAC;AAqKvC,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAyBzD;AA8ND,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,UAAU,CAAC;CACpB;AAED,MAAM,WAAW,kBAAkB;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,kFAAkF;IAClF,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,SAAS,CAAC,EAAE,IAAI,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IAC3C,4EAA4E;IAC5E,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAyRD,wBAAuB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,cAAc,CAAC,SAAS,CAAC,CA0BzF"}
|
package/dist/core/glob.js
CHANGED
|
@@ -535,7 +535,7 @@ function* processDirentMatch(match, cwd, maxDepth, seen, onlyFiles) {
|
|
|
535
535
|
return;
|
|
536
536
|
yield { path: absolutePath, dirent: match };
|
|
537
537
|
}
|
|
538
|
-
function createWalkFilter(cwd, skipIgnored, gitignoreMatcher, maxDepth, signal) {
|
|
538
|
+
function createWalkFilter(cwd, skipIgnored, gitignoreMatcher, maxDepth, signal, pathGuard) {
|
|
539
539
|
// fs.glob can hand the predicate a dirent whose parentPath is "." — the walk
|
|
540
540
|
// root, not the process cwd — when it re-visits a directory under `**` whose
|
|
541
541
|
// name also exists in the process cwd. Resolving against `cwd` names the
|
|
@@ -547,6 +547,33 @@ function createWalkFilter(cwd, skipIgnored, gitignoreMatcher, maxDepth, signal)
|
|
|
547
547
|
const excluded = (posixRel, isDir) => skipIgnored &&
|
|
548
548
|
(posixRel.split('/').some((segment) => DEFAULT_EXCLUDED_NAMES.has(segment)) ||
|
|
549
549
|
(gitignoreMatcher?.isIgnored(posixRel, isDir) ?? false));
|
|
550
|
+
// A sensitive directory's subtree is hidden with the directory: pruning
|
|
551
|
+
// stops descent, and the yielded dirent is dropped below. The guard checks
|
|
552
|
+
// the directory's own path, so this never fires on a clean-named entry inside
|
|
553
|
+
// a denylisted tree — the tree never gets walked.
|
|
554
|
+
const sensitiveDir = (match) => pathGuard !== undefined && match.isDirectory() && pathGuard.isSensitive(absoluteOf(match));
|
|
555
|
+
// A sensitive directory anywhere above an entry hides the entry, whatever
|
|
556
|
+
// the pattern spelled: a literal prefix (`vault.key/*.txt`) never asks the
|
|
557
|
+
// descent prune, and a sensitive-named symlink is not isDirectory() so the
|
|
558
|
+
// prune misses it — but every yielded path names its ancestors. The entry's
|
|
559
|
+
// own final name stays with the per-entry guard every caller already runs.
|
|
560
|
+
const sensitiveTreeCache = new Map();
|
|
561
|
+
const sensitiveTree = (posixRel) => {
|
|
562
|
+
if (pathGuard === undefined)
|
|
563
|
+
return false;
|
|
564
|
+
const segments = posixRel.split('/');
|
|
565
|
+
for (let i = 1; i < segments.length; i++) {
|
|
566
|
+
const prefix = segments.slice(0, i).join('/');
|
|
567
|
+
let hit = sensitiveTreeCache.get(prefix);
|
|
568
|
+
if (hit === undefined) {
|
|
569
|
+
hit = pathGuard.isSensitive(resolve(cwd, prefix));
|
|
570
|
+
sensitiveTreeCache.set(prefix, hit);
|
|
571
|
+
}
|
|
572
|
+
if (hit)
|
|
573
|
+
return true;
|
|
574
|
+
}
|
|
575
|
+
return false;
|
|
576
|
+
};
|
|
550
577
|
return {
|
|
551
578
|
prune: (match) => {
|
|
552
579
|
// fs.glob takes no signal and calls this for every entry it visits, so
|
|
@@ -563,6 +590,8 @@ function createWalkFilter(cwd, skipIgnored, gitignoreMatcher, maxDepth, signal)
|
|
|
563
590
|
const isDir = match.isDirectory();
|
|
564
591
|
if (excluded(posixRel, isDir))
|
|
565
592
|
return true;
|
|
593
|
+
if (sensitiveDir(match) || sensitiveTree(posixRel))
|
|
594
|
+
return true;
|
|
566
595
|
// Stop descent one level past the depth bound. Pruning a directory *at*
|
|
567
596
|
// the bound would drop it where fs.glob treats it as top-level, so prune
|
|
568
597
|
// its children instead; processDirentMatch drops that extra level.
|
|
@@ -570,7 +599,10 @@ function createWalkFilter(cwd, skipIgnored, gitignoreMatcher, maxDepth, signal)
|
|
|
570
599
|
return false;
|
|
571
600
|
return posixRel.split('/').length - 1 > maxDepth;
|
|
572
601
|
},
|
|
573
|
-
isExcluded: (match) =>
|
|
602
|
+
isExcluded: (match) => {
|
|
603
|
+
const posixRel = relativeOf(match);
|
|
604
|
+
return (excluded(posixRel, match.isDirectory()) || sensitiveDir(match) || sensitiveTree(posixRel));
|
|
605
|
+
},
|
|
574
606
|
};
|
|
575
607
|
}
|
|
576
608
|
async function* processGlobPatterns(patterns, plan, seen, onlyFiles, filter, signal) {
|
|
@@ -616,7 +648,7 @@ export async function* globEntries(options) {
|
|
|
616
648
|
const plan = normalizeGlobOptions(options);
|
|
617
649
|
const seen = new Set();
|
|
618
650
|
const onlyFiles = options.onlyFiles ?? true;
|
|
619
|
-
const filter = createWalkFilter(plan.cwd, options.skipIgnored ?? false, gitignoreMatcher, plan.maxDepth, options.signal);
|
|
651
|
+
const filter = createWalkFilter(plan.cwd, options.skipIgnored ?? false, gitignoreMatcher, plan.maxDepth, options.signal, options.pathGuard);
|
|
620
652
|
// One walk for every variant: fs.glob reads each directory once and matches
|
|
621
653
|
// all of them, where a walk per variant re-read the tree for each.
|
|
622
654
|
yield* processGlobPatterns(plan.patterns, plan, seen, onlyFiles, filter, options.signal);
|
package/dist/core/glob.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/core/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,IAAI,UAAU,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAG3F,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OA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,CAAC,MAAM,EACd,OAAO,CAAC,QAAQ,EAChB,OAAO,CAAC,aAAa,CACtB;QACH,CAAC,CAAC,IAAI,CAAC;IAET,MAAM,IAAI,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC;IAC5C,MAAM,MAAM,GAAG,gBAAgB,CAC7B,IAAI,CAAC,GAAG,EACR,OAAO,CAAC,WAAW,IAAI,KAAK,EAC5B,gBAAgB,EAChB,IAAI,CAAC,QAAQ,EACb,OAAO,CAAC,MAAM,CACf,CAAC;IAEF,4EAA4E;IAC5E,mEAAmE;IACnE,KAAK,CAAC,CAAC,mBAAmB,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;AAC3F,CAAC;AAED,uEAAuE;AACvE,MAAM,sBAAsB,GAAwB,IAAI,GAAG,CAAC;IAC1D,cAAc;IACd,MAAM;IACN,OAAO;IACP,UAAU;IACV,MAAM;IACN,SAAS;IACT,OAAO;IACP,WAAW;IACX,OAAO;IACP,OAAO;IACP,SAAS;IACT,aAAa;IACb,QAAQ;IACR,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,KAAK;IACL,KAAK;IACL,OAAO;IACP,eAAe;IACf,gBAAgB;IAChB,gBAAgB;IAChB,WAAW;CACZ,CAAC,CAAC","sourcesContent":["import { glob as fsGlob, readFile as fsReadFile, lstat } from 'node:fs/promises';\nimport { basename, dirname, join, matchesGlob, relative, resolve, win32 } from 'node:path';\n\nimport type { Ignore } from 'ignore';\nimport ignore from 'ignore';\n\nimport { processInParallel } from './concurrency.ts';\nimport { formatUnknownErrorMessage } from './errors.ts';\nimport { Logger } from './observability.ts';\nimport type { DirentLike } from './path-utils.ts';\nimport { IS_WINDOWS, isPathInsideDirectory, toPosixPath } from './path-utils.ts';\nimport { MIB } from './util.ts';\n\n/**\n * More brace alternatives than this is not a file filter. fs.glob's matcher\n * dedupes its alternatives pairwise, synchronously: `{1..100000}` pins the\n * event loop for most of a minute, where 1024 costs tens of milliseconds.\n */\nexport const MAX_BRACE_ALTERNATIVES = 1024;\n\n/** Bound synchronous glob compilation when checking candidate traversal segments. */\nexport const MAX_DOTDOT_CHECK_CHARS = 4096;\n\n/**\n * fs.glob tests each name against a regex compiled from the segment,\n * synchronously. Every run of `*` and every extglob group (`?(`, `+(`, `@(`,\n * `!(`, `*(`) adds a degree of backtracking: on a 255-character name three cost\n * under 100 ms, four about 1 s, and five do not finish; a chain of `?(a|aa)`\n * groups grows the same way.\n */\nexport const MAX_SEGMENT_WILDCARDS = 3;\n\n// The range bodies fs.glob's brace expansion recognises, as it writes them.\nconst NUMERIC_RANGE_RE = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/u;\nconst ALPHA_RANGE_RE = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/u;\n\n/** The values a range body (`x..y`, `x..y..step`) expands to, or `undefined` past the cap. */\nfunction rangeValues(body: string): string[] | undefined {\n const alpha = ALPHA_RANGE_RE.test(body);\n const [from = '', to = '', step = '1'] = body.split('..');\n const bound = (end: string): number => (alpha ? end.charCodeAt(0) : Number.parseInt(end, 10));\n const start = bound(from);\n const stop = bound(to);\n const stride = Math.max(Math.abs(Number.parseInt(step, 10)), 1);\n // Past 2^53 a step no longer moves the number (2^53 + 1 === 2^53), and past\n // Number.MAX_VALUE it reads as Infinity: either way the loop below would\n // never end. Refuse them like any other long range.\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(stop)) return undefined;\n if (Math.floor(Math.abs(stop - start) / stride) >= MAX_BRACE_ALTERNATIVES) return undefined;\n const values: string[] = [];\n const direction = stop < start ? -1 : 1;\n for (let i = start; (stop - i) * direction >= 0; i += stride * direction) {\n // The engine drops a `\\` a letter range passes through (`{Z..a}`), and\n // digits can never spell a root or a `..`, so their padding is moot.\n const char = String.fromCharCode(i);\n values.push(alpha ? (char === '\\\\' ? '' : char) : String(i));\n }\n return values;\n}\n\ninterface BraceSet {\n pre: string;\n /** `undefined` when the set alone expands past the cap. */\n alternatives: string[] | undefined;\n post: string;\n}\n\n/**\n * The leftmost `{…}` that fs.glob would expand: a comma list or a range.\n * The expansion is textual, as fs.glob's is: a brace inside `[…]` still\n * counts (unlike SensitiveMatcher's own glob dialect in sensitive.ts).\n */\nfunction firstBraceSet(pattern: string): BraceSet | undefined {\n const open: { at: number; commas: number[] }[] = [];\n let first: { at: number; commas: number[]; close: number } | undefined;\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n if (char === '{') open.push({ at: i, commas: [] });\n else if (char === ',') open.at(-1)?.commas.push(i);\n else if (char === '}') {\n const set = open.pop();\n if (!set || (first && first.at < set.at)) continue;\n const body = pattern.slice(set.at + 1, i);\n if (set.commas.length > 0 || NUMERIC_RANGE_RE.test(body) || ALPHA_RANGE_RE.test(body)) {\n first = { ...set, close: i };\n }\n }\n }\n if (!first) return undefined;\n let alternatives: string[] | undefined;\n if (first.commas.length > 0) {\n alternatives = [];\n let start = first.at + 1;\n for (const end of [...first.commas, first.close]) {\n alternatives.push(pattern.slice(start, end));\n start = end + 1;\n }\n } else {\n alternatives = rangeValues(pattern.slice(first.at + 1, first.close));\n }\n return { pre: pattern.slice(0, first.at), alternatives, post: pattern.slice(first.close + 1) };\n}\n\n/** Every brace alternative of `pattern`, or `undefined` past the cap. */\nfunction expandBraceSets(pattern: string, out: string[] = []): string[] | undefined {\n const set = firstBraceSet(pattern);\n if (!set) {\n out.push(pattern);\n return out.length > MAX_BRACE_ALTERNATIVES ? undefined : out;\n }\n if (!set.alternatives) return undefined;\n for (const alternative of set.alternatives) {\n if (!expandBraceSets(`${set.pre}${alternative}${set.post}`, out)) return undefined;\n }\n return out;\n}\n\n/** The characters minimatch can spell a literal `..` with: dots and one-character classes. */\nconst DOTDOT_SPELLING_RE = /^[.[\\]-]+$/u;\n\n/**\n * Whether the glob engine reads this brace-free segment as `..`. readdir never\n * yields `..`, so only a literal reaches it, and minimatch spells a literal dot\n * as `.`, `[.]` or `[.-.]`. Any other character (`*`, `?`, an extglob, a\n * letter) either makes the segment a pattern the walk never follows to `..`,\n * or puts that character in the name. Only the rest is worth asking the engine\n * about, so a long or exotic segment costs no compile; one the engine cannot\n * compile is refused.\n */\nconst isTraversalSegment = (segment: string): boolean => {\n try {\n return matchesGlob('..', segment);\n } catch {\n return true;\n }\n};\n\n/**\n * An alternative that starts at a root: `/x`, `//host/share`, `C:/x`, `C:x`,\n * on any host. On Windows fs.glob also reads a literal first segment ending in\n * `:` as a drive (`[C]:/x`); elsewhere that is an ordinary name (`logs:`).\n */\nconst isRooted = (alternative: string): boolean =>\n win32.parse(alternative).root !== '' ||\n (IS_WINDOWS && (alternative.split('/')[0] ?? '').endsWith(':'));\n\n/**\n * Index of the `)` that closes the group opened at `open`, or -1. A `[...]`\n * class is skipped whole: a `)` or `|` inside one is a literal, not syntax.\n */\nfunction groupClose(segment: string, open: number): number {\n let depth = 0;\n for (let i = open; i < segment.length; i++) {\n const c = segment[i];\n if (c === '[') {\n // A `]` first in the class (or after `!`/`^`) is literal, so search past it.\n const first = segment[i + 1] === '!' || segment[i + 1] === '^' ? i + 2 : i + 1;\n const end = segment.indexOf(']', first + 1);\n if (end !== -1) {\n i = end;\n continue;\n }\n }\n if (c === '(') depth++;\n else if (c === ')' && --depth === 0) return i;\n }\n return -1;\n}\n\n/**\n * Whether matching this brace-free segment can backtrack for seconds on one\n * long name. Two shapes do: a repeated group (`*(…)`, `+(…)`) whose body can\n * match more than one way (`|`, `*`, or a nested group), and more than\n * MAX_SEGMENT_WILDCARDS `*` runs and extglob groups together.\n */\nfunction canBacktrack(segment: string): boolean {\n if (segment === '**') return false;\n let wildcards = (segment.match(/\\*+/gu) ?? []).length;\n for (let i = segment.indexOf('('); i !== -1; i = segment.indexOf('(', i + 1)) {\n const opener = segment[i - 1];\n if (opener === undefined || !'*+?@!'.includes(opener)) continue;\n // Each group can match more than one way, so it adds a degree of\n // backtracking like a `*` run does (`*(` is already counted as one).\n if (opener !== '*') wildcards++;\n if (opener !== '*' && opener !== '+') continue;\n const close = groupClose(segment, i);\n // Classes are literals: only `|`, `*` or a group outside one can backtrack.\n const body = segment\n .slice(i + 1, close === -1 ? undefined : close)\n .replace(/\\[[!^]?\\]?[^\\]]*\\]/gu, '');\n if (/[|*(]/u.test(body)) return true;\n }\n return wildcards > MAX_SEGMENT_WILDCARDS;\n}\n\nexport function isSafeGlobSyntax(pattern: string): boolean {\n if (!pattern || pattern.trim().length === 0) {\n return false;\n }\n // The walk sees the pattern with `\\` as `/` (normalizePattern), so check\n // that form: `\\etc\\x` is `/etc/x` there, an absolute walk on any host.\n // Brace sets can build a root or a `..` from parts (`{/etc,x}`, `..{,x}`,\n // `.{Z..a}.`), so check every alternative, not the pattern as written.\n // globEntries still drops any match outside its cwd: this check is what\n // turns such a pattern into an error rather than a quietly narrower walk.\n const alternatives = expandBraceSets(toPosixPath(pattern));\n if (!alternatives) return false;\n const segments = new Set<string>();\n for (const alternative of alternatives) {\n if (isRooted(alternative)) return false;\n for (const segment of alternative.split('/')) segments.add(segment);\n }\n let dotdotCheckChars = 0;\n for (const segment of segments) {\n if (canBacktrack(segment)) return false;\n if (!segment.includes('.') || !DOTDOT_SPELLING_RE.test(segment)) continue;\n dotdotCheckChars += segment.length;\n if (dotdotCheckChars > MAX_DOTDOT_CHECK_CHARS || isTraversalSegment(segment)) return false;\n }\n return true;\n}\n\n/** A .gitignore past this size is not a .gitignore; skip it rather than read it. */\nconst MAX_GITIGNORE_BYTES = MIB;\n\nasync function loadGitignoreFiles(\n root: string,\n gitignorePaths: readonly string[],\n manager: GitignoreManager,\n signal?: AbortSignal,\n): Promise<void> {\n await processInParallel(\n gitignorePaths,\n async (relPath) => {\n const absPath = join(root, relPath);\n try {\n // lstat, not stat: a symlinked .gitignore may point at a device, a\n // FIFO or a huge file outside the root. Only a plain, small file is a\n // rule set worth reading.\n const info = await lstat(absPath);\n if (!info.isFile() || info.size > MAX_GITIGNORE_BYTES) return;\n const contents = await fsReadFile(absPath, { encoding: 'utf-8', signal });\n const matcher = ignore();\n matcher.add(contents);\n const dir = toPosixPath(dirname(relPath));\n manager.addMatcher(dir === '.' ? '' : dir, matcher);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(`Failed to read .gitignore at ${absPath}: ${formatUnknownErrorMessage(error)}`);\n }\n },\n GLOB_BATCH_CONCURRENCY,\n signal,\n );\n}\n\n/**\n * Load `.gitignore` from each ancestor of `root` up to and including `ceiling`,\n * farthest first. A rule set that ignores `root` itself is skipped: the caller\n * named that directory on purpose, and applying the rule would empty the walk.\n */\nasync function loadAncestorGitignores(\n root: string,\n ceiling: string,\n manager: GitignoreManager,\n signal?: AbortSignal,\n): Promise<void> {\n const normalizedCeiling = resolve(ceiling);\n const chain: string[] = [];\n for (let dir = dirname(resolve(root)); ; dir = dirname(dir)) {\n if (!isPathInsideDirectory(normalizedCeiling, dir)) break;\n chain.push(dir);\n if (\n (isPathInsideDirectory(dir, normalizedCeiling) &&\n isPathInsideDirectory(normalizedCeiling, dir)) ||\n dirname(dir) === dir\n ) {\n break;\n }\n }\n for (const dir of chain.reverse()) {\n signal?.throwIfAborted();\n const file = join(dir, '.gitignore');\n try {\n const info = await lstat(file);\n if (!info.isFile() || info.size > MAX_GITIGNORE_BYTES) continue;\n const matcher = ignore().add(await fsReadFile(file, { encoding: 'utf-8', signal }));\n const prefix = toPosixPath(relative(dir, root));\n if (matcher.test(`${prefix}/`).ignored) continue;\n manager.addAncestorMatcher(prefix, matcher);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n // ENOENT is the normal case (no .gitignore at this level); anything else is not worth a warning per walk\n }\n }\n}\n\nclass GitignoreManager {\n private matchers = new Map<string, Ignore>();\n /** Rules from directories above the walk root, farthest first; `prefix` re-bases a walk-relative path to that directory. */\n private ancestors: { prefix: string; matcher: Ignore }[] = [];\n private dirCache = new Map<string, boolean>();\n\n addMatcher(dir: string, matcher: Ignore): void {\n this.matchers.set(dir, matcher);\n }\n\n addAncestorMatcher(prefix: string, matcher: Ignore): void {\n this.ancestors.push({ prefix, matcher });\n }\n\n /** `null` when no `.gitignore` was found, so callers skip the filter entirely. */\n static async load(\n root: string,\n includeHidden: boolean,\n signal?: AbortSignal,\n maxDepth?: number,\n ignoreCeiling?: string,\n ): Promise<GitignoreManager | null> {\n const manager = new GitignoreManager();\n try {\n const gitignorePaths: string[] = [];\n // Search dot-directories (.venv, .terraform, ...) for rules only when the\n // walk includes hidden entries; for any other walk, enumerating every\n // hidden tree would cost more than the walk itself.\n const gitignorePatterns = includeHidden\n ? [...buildHiddenPatterns('**/.gitignore')]\n : ['**/.gitignore'];\n const gitignoreEntries = fsGlob(gitignorePatterns, {\n cwd: root,\n // Skip what the walk itself skips, and stop one level past its depth\n // bound: a .gitignore at depth d only affects entries at depth >= d.\n exclude: (entry: string) => {\n if (signal?.aborted) return true;\n const name = basename(entry);\n if (name === '.hg' || name === '.svn' || DEFAULT_EXCLUDED_NAMES.has(name)) return true;\n return maxDepth !== undefined && toPosixPath(entry).split('/').length - 1 > maxDepth;\n },\n });\n for await (const match of gitignoreEntries) {\n if (signal?.aborted) break;\n gitignorePaths.push(match);\n }\n\n await loadGitignoreFiles(root, gitignorePaths, manager, signal);\n if (ignoreCeiling !== undefined) {\n await loadAncestorGitignores(root, ignoreCeiling, manager, signal);\n }\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(\n `Failed to enumerate .gitignore files under ${root}: ${formatUnknownErrorMessage(error)}`,\n );\n }\n return manager.matchers.size === 0 && manager.ancestors.length === 0 ? null : manager;\n }\n\n isIgnored(relativePath: string, isDirectory: boolean): boolean {\n const normalized = toPosixPath(relativePath);\n if (normalized === '' || normalized === '.') return false;\n const parts = normalized.split('/');\n\n // 1. Check parent directories first\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n if (this.checkDir(currentDir)) {\n return true;\n }\n }\n\n // 2. Check the file/directory itself\n return isDirectory ? this.checkDir(normalized) : this.checkPath(normalized, false);\n }\n\n private checkDir(dir: string): boolean {\n const cached = this.dirCache.get(dir);\n if (cached !== undefined) return cached;\n const res = this.checkPath(dir, true);\n this.dirCache.set(dir, res);\n return res;\n }\n\n private checkPath(posixPath: string, isDirectory: boolean): boolean {\n const parts = posixPath.split('/');\n const pathToCheck = isDirectory\n ? posixPath.endsWith('/')\n ? posixPath\n : `${posixPath}/`\n : posixPath;\n\n let ignored = false;\n\n for (const { prefix, matcher } of this.ancestors) {\n const res = matcher.test(`${prefix}/${pathToCheck}`);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n\n // Check root level\n const rootMatcher = this.matchers.get('');\n if (rootMatcher) {\n const res = rootMatcher.test(pathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n\n // Check subdirectories\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n const matcher = this.matchers.get(currentDir);\n if (matcher) {\n const relParts = parts.slice(i + 1);\n const relPath = relParts.join('/');\n const relPathToCheck = isDirectory\n ? relPath.endsWith('/')\n ? relPath\n : `${relPath}/`\n : relPath;\n\n const res = matcher.test(relPathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n }\n\n return ignored;\n }\n}\n\ninterface GlobDirentLike extends DirentLike {\n name: string;\n parentPath: string;\n}\n\nexport interface GlobEntry {\n path: string;\n dirent: DirentLike;\n}\n\nexport interface GlobEntriesOptions {\n cwd: string;\n pattern: string;\n includeHidden?: boolean;\n baseNameMatch?: boolean;\n maxDepth?: number;\n onlyFiles?: boolean;\n suppressErrors?: boolean;\n /** Skip what a walk should not surface: DEFAULT_EXCLUDED_NAMES and .gitignore. */\n skipIgnored?: boolean;\n /**\n * Topmost directory whose `.gitignore` may apply to this walk — the allowed\n * root containing `cwd`. Ancestors of `cwd` up to and including it are\n * consulted; nothing above it is ever read. Ignored without `skipIgnored`.\n */\n ignoreCeiling?: string;\n /** Bounds the `.gitignore` discovery `skipIgnored` runs before the walk. */\n signal?: AbortSignal;\n}\n\ninterface NormalizedGlob {\n cwd: string;\n patterns: readonly string[];\n suppressErrors: boolean;\n maxDepth?: number;\n}\n\nconst GLOB_MAGIC_RE = /[*?[\\]{}!]/u;\nconst GLOB_BATCH_CONCURRENCY = 64;\nconst SEP = '/';\nfunction normalizePattern(pattern: string, baseNameMatch: boolean): string {\n const normalized = toPosixPath(pattern);\n\n if (!baseNameMatch) return normalized;\n if (normalized.includes(SEP)) return normalized;\n return `**/${normalized}`;\n}\n\nfunction splitPatternPrefix(normalizedPattern: string): {\n prefix: string;\n remainder: string;\n} {\n if (!GLOB_MAGIC_RE.test(normalizedPattern)) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n const segments = normalizedPattern.split(SEP);\n const splitIndex = segments.findIndex((seg) => GLOB_MAGIC_RE.test(seg));\n\n if (splitIndex <= 0) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n return {\n prefix: segments.slice(0, splitIndex).join(SEP) + SEP,\n remainder: segments.slice(splitIndex).join(SEP),\n };\n}\n\n/**\n * The segment matching the dot-prefixed names `segment` would match if fs.glob\n * did not skip them, or `undefined` when there are none. Only a leading `*` or `?`\n * stands for that dot: a literal never does, and a character class or a\n * brace set is left as written rather than parsed.\n */\nfunction dotVariant(segment: string): string | undefined {\n // `*(…)`, `?(…)` and `!(…)` are extglobs, not wildcards.\n if (segment[1] === '(') return undefined;\n if (segment.startsWith('*')) return `.${segment}`;\n if (!segment.startsWith('?')) return undefined;\n // `?` is exactly one character, so the dot replaces it, unless what follows\n // could leave just `.` or `..` (`?`, `?.`, `?{.,x}`, `?[.]`): the directory\n // and its parent, not a dot-prefixed entry.\n const rest = segment.slice(1);\n return rest === '' || /^[.[{]/u.test(rest) ? undefined : `.${rest}`;\n}\n\nfunction addFirstDotSegment(patterns: Set<string>, prefix: string, remainder: string): void {\n if (remainder.length === 0) return;\n const segments = remainder.split(SEP);\n const idx = segments.findIndex((seg) => seg !== '**' && seg.length > 0);\n\n if (idx !== -1) {\n const original = segments[idx];\n const dotted = original ? dotVariant(original) : undefined;\n if (dotted) {\n const newSegments = [...segments];\n newSegments[idx] = dotted;\n patterns.add(`${prefix}${newSegments.join(SEP)}`);\n }\n }\n}\n\nfunction expandHiddenGlobstars(patterns: Set<string>, prefix: string, remainder: string): void {\n // Trailing bare globstar — `src/**`, `**` (remainder is exactly `**`, no\n // following segment). The pattern itself already matches every non-dot\n // entry under the prefix; add the two hidden complements fs.glob skips:\n // dotfiles/dot-dirs anywhere, and the contents of dot-dirs anywhere.\n if (remainder === '**') {\n patterns.add(`${prefix}**/.*`);\n patterns.add(`${prefix}**/.*/**`);\n return;\n }\n\n if (!remainder.startsWith('**/')) return;\n\n const afterGlobstar = remainder.slice(3);\n // Node fs.glob skips leading-dot entries unless the matching segment itself\n // starts with '.', and its `dot` option is not honored. So `**/*` alone misses\n // hidden files. Two depth-agnostic patterns cover everything the per-depth\n // unroll did: contents of dot-directories anywhere, and dotfiles/dotdirs\n // anywhere (when the first segment after the globstar can match a dot).\n patterns.add(`${prefix}**/.*/**/${afterGlobstar}`);\n const [firstSegment = '', ...rest] = afterGlobstar.split(SEP);\n const dotted = dotVariant(firstSegment);\n if (dotted) patterns.add(`${prefix}**/${[dotted, ...rest].join(SEP)}`);\n}\n\nfunction buildHiddenPatterns(normalizedPattern: string): readonly string[] {\n const patterns = new Set<string>([normalizedPattern]);\n const { prefix, remainder } = splitPatternPrefix(normalizedPattern);\n\n addFirstDotSegment(patterns, prefix, remainder);\n expandHiddenGlobstars(patterns, prefix, remainder);\n\n return Array.from(patterns);\n}\n\nfunction normalizeGlobOptions(options: GlobEntriesOptions): NormalizedGlob {\n const cwd = resolve(options.cwd);\n const normalizedPattern = normalizePattern(options.pattern, options.baseNameMatch ?? false);\n\n const patterns = options.includeHidden\n ? buildHiddenPatterns(normalizedPattern)\n : [normalizedPattern];\n\n const normalized: NormalizedGlob = {\n cwd,\n patterns,\n suppressErrors: options.suppressErrors ?? false,\n };\n\n if (options.maxDepth !== undefined) {\n normalized.maxDepth = options.maxDepth;\n }\n\n return normalized;\n}\n\nfunction* processDirentMatch(\n match: GlobDirentLike,\n cwd: string,\n maxDepth: number | undefined,\n seen: Set<string>,\n onlyFiles: boolean,\n): Generator<GlobEntry> {\n const absolutePath = resolve(cwd, match.parentPath, match.name);\n // The walk's scope is its cwd, whatever the pattern spells: a `..` or a root\n // the validator did not foresee must not reach a caller, where it would be\n // read, rewritten, or counted and named as inaccessible.\n if (!isPathInsideDirectory(cwd, absolutePath)) return;\n\n if (maxDepth !== undefined) {\n const rel = relative(cwd, absolutePath);\n if (rel.split(/[/\\\\]/u).length - 1 > maxDepth) return;\n }\n\n if (seen.has(absolutePath)) return;\n seen.add(absolutePath);\n\n if (onlyFiles && !match.isFile()) return;\n yield { path: absolutePath, dirent: match };\n}\n\ninterface WalkFilter {\n /** Given to fs.glob: true stops descent into a directory. */\n prune: (match: GlobDirentLike) => boolean;\n /** Re-applied to yielded entries: the ignore rules only, never the depth bound. */\n isExcluded: (match: GlobDirentLike) => boolean;\n}\n\nfunction createWalkFilter(\n cwd: string,\n skipIgnored: boolean,\n gitignoreMatcher: GitignoreManager | null,\n maxDepth: number | undefined,\n signal: AbortSignal | undefined,\n): WalkFilter {\n // fs.glob can hand the predicate a dirent whose parentPath is \".\" — the walk\n // root, not the process cwd — when it re-visits a directory under `**` whose\n // name also exists in the process cwd. Resolving against `cwd` names the\n // entry the dirent describes; `join` would resolve it against the process.\n const absoluteOf = (match: GlobDirentLike): string => resolve(cwd, match.parentPath, match.name);\n const relativeOf = (match: GlobDirentLike): string =>\n toPosixPath(relative(cwd, absoluteOf(match)));\n // Every default exclude is a bare name that applies at any depth, so a Set\n // lookup per segment replaces compiling dozens of globs per entry.\n const excluded = (posixRel: string, isDir: boolean): boolean =>\n skipIgnored &&\n (posixRel.split('/').some((segment) => DEFAULT_EXCLUDED_NAMES.has(segment)) ||\n (gitignoreMatcher?.isIgnored(posixRel, isDir) ?? false));\n\n return {\n prune: (match) => {\n // fs.glob takes no signal and calls this for every entry it visits, so\n // pruning everything is the only way to stop a walk that yields nothing.\n if (signal?.aborted) return true;\n // fs.glob asks before it queues a directory, so a walk that would\n // climb to `../` or start at `/` stops at the edge instead of reading\n // there. Not every climb asks (`**/..` does not): processDirentMatch is\n // the gate, this only saves the walk.\n if (!isPathInsideDirectory(cwd, absoluteOf(match))) return true;\n const posixRel = relativeOf(match);\n const isDir = match.isDirectory();\n if (excluded(posixRel, isDir)) return true;\n // Stop descent one level past the depth bound. Pruning a directory *at*\n // the bound would drop it where fs.glob treats it as top-level, so prune\n // its children instead; processDirentMatch drops that extra level.\n if (maxDepth === undefined || !isDir) return false;\n return posixRel.split('/').length - 1 > maxDepth;\n },\n isExcluded: (match) => excluded(relativeOf(match), match.isDirectory()),\n };\n}\n\nasync function* processGlobPatterns(\n patterns: readonly string[],\n plan: NormalizedGlob,\n seen: Set<string>,\n onlyFiles: boolean,\n filter: WalkFilter,\n signal: AbortSignal | undefined,\n): AsyncGenerator<GlobEntry> {\n const { cwd, maxDepth, suppressErrors } = plan;\n let iterable: AsyncIterable<GlobDirentLike>;\n try {\n iterable = fsGlob([...patterns], {\n cwd,\n exclude: filter.prune,\n withFileTypes: true,\n }) as AsyncIterable<GlobDirentLike>;\n } catch (error) {\n if (suppressErrors) return;\n throw error;\n }\n\n try {\n for await (const match of iterable) {\n if (signal?.aborted) break;\n // A function `exclude` only prunes descent in fs.glob — it still yields\n // the rejected dirent itself, and any rejected entry below the top level.\n // Re-apply the ignore rules (not the depth bound) to drop those.\n if (filter.isExcluded(match)) continue;\n yield* processDirentMatch(match, cwd, maxDepth, seen, onlyFiles);\n }\n } catch (error) {\n if (!suppressErrors) throw error;\n Logger.warn(\n `globEntries: suppressed mid-walk error for pattern \"${patterns.join(', ')}\": ${formatUnknownErrorMessage(error)}`,\n );\n }\n // A pruned walk ends like a finished one. Say it was cut short, so no caller\n // reads \"the walk ended\" as \"the whole tree was seen\".\n signal?.throwIfAborted();\n}\n\nexport async function* globEntries(options: GlobEntriesOptions): AsyncGenerator<GlobEntry> {\n const gitignoreMatcher = options.skipIgnored\n ? await GitignoreManager.load(\n options.cwd,\n options.includeHidden ?? false,\n options.signal,\n options.maxDepth,\n options.ignoreCeiling,\n )\n : null;\n\n const plan = normalizeGlobOptions(options);\n const seen = new Set<string>();\n const onlyFiles = options.onlyFiles ?? true;\n const filter = createWalkFilter(\n plan.cwd,\n options.skipIgnored ?? false,\n gitignoreMatcher,\n plan.maxDepth,\n options.signal,\n );\n\n // One walk for every variant: fs.glob reads each directory once and matches\n // all of them, where a walk per variant re-read the tree for each.\n yield* processGlobPatterns(plan.patterns, plan, seen, onlyFiles, filter, options.signal);\n}\n\n/** Names a `skipIgnored` walk never enters or yields, at any depth. */\nconst DEFAULT_EXCLUDED_NAMES: ReadonlySet<string> = new Set([\n 'node_modules',\n 'dist',\n 'build',\n 'coverage',\n '.git',\n '.vscode',\n '.idea',\n '.DS_Store',\n '.next',\n '.nuxt',\n '.output',\n '.svelte-kit',\n '.cache',\n '.yarn',\n 'jspm_packages',\n 'bower_components',\n 'out',\n 'tmp',\n '.temp',\n 'npm-debug.log',\n 'yarn-debug.log',\n 'yarn-error.log',\n 'Thumbs.db',\n]);\n"]}
|
|
1
|
+
{"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/core/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,IAAI,UAAU,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACjF,OA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QAAQ;IACR,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,KAAK;IACL,KAAK;IACL,OAAO;IACP,eAAe;IACf,gBAAgB;IAChB,gBAAgB;IAChB,WAAW;CACZ,CAAC,CAAC","sourcesContent":["import { glob as fsGlob, readFile as fsReadFile, lstat } from 'node:fs/promises';\nimport { basename, dirname, join, matchesGlob, relative, resolve, win32 } from 'node:path';\n\nimport type { Ignore } from 'ignore';\nimport ignore from 'ignore';\n\nimport { processInParallel } from './concurrency.ts';\nimport { formatUnknownErrorMessage } from './errors.ts';\nimport { Logger } from './observability.ts';\nimport type { DirentLike } from './path-utils.ts';\nimport { IS_WINDOWS, isPathInsideDirectory, toPosixPath } from './path-utils.ts';\nimport type { PathGuard } from './path.ts';\nimport { MIB } from './util.ts';\n\n/**\n * More brace alternatives than this is not a file filter. fs.glob's matcher\n * dedupes its alternatives pairwise, synchronously: `{1..100000}` pins the\n * event loop for most of a minute, where 1024 costs tens of milliseconds.\n */\nexport const MAX_BRACE_ALTERNATIVES = 1024;\n\n/** Bound synchronous glob compilation when checking candidate traversal segments. */\nexport const MAX_DOTDOT_CHECK_CHARS = 4096;\n\n/**\n * fs.glob tests each name against a regex compiled from the segment,\n * synchronously. Every run of `*` and every extglob group (`?(`, `+(`, `@(`,\n * `!(`, `*(`) adds a degree of backtracking: on a 255-character name three cost\n * under 100 ms, four about 1 s, and five do not finish; a chain of `?(a|aa)`\n * groups grows the same way.\n */\nexport const MAX_SEGMENT_WILDCARDS = 3;\n\n// The range bodies fs.glob's brace expansion recognises, as it writes them.\nconst NUMERIC_RANGE_RE = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/u;\nconst ALPHA_RANGE_RE = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/u;\n\n/** The values a range body (`x..y`, `x..y..step`) expands to, or `undefined` past the cap. */\nfunction rangeValues(body: string): string[] | undefined {\n const alpha = ALPHA_RANGE_RE.test(body);\n const [from = '', to = '', step = '1'] = body.split('..');\n const bound = (end: string): number => (alpha ? end.charCodeAt(0) : Number.parseInt(end, 10));\n const start = bound(from);\n const stop = bound(to);\n const stride = Math.max(Math.abs(Number.parseInt(step, 10)), 1);\n // Past 2^53 a step no longer moves the number (2^53 + 1 === 2^53), and past\n // Number.MAX_VALUE it reads as Infinity: either way the loop below would\n // never end. Refuse them like any other long range.\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(stop)) return undefined;\n if (Math.floor(Math.abs(stop - start) / stride) >= MAX_BRACE_ALTERNATIVES) return undefined;\n const values: string[] = [];\n const direction = stop < start ? -1 : 1;\n for (let i = start; (stop - i) * direction >= 0; i += stride * direction) {\n // The engine drops a `\\` a letter range passes through (`{Z..a}`), and\n // digits can never spell a root or a `..`, so their padding is moot.\n const char = String.fromCharCode(i);\n values.push(alpha ? (char === '\\\\' ? '' : char) : String(i));\n }\n return values;\n}\n\ninterface BraceSet {\n pre: string;\n /** `undefined` when the set alone expands past the cap. */\n alternatives: string[] | undefined;\n post: string;\n}\n\n/**\n * The leftmost `{…}` that fs.glob would expand: a comma list or a range.\n * The expansion is textual, as fs.glob's is: a brace inside `[…]` still\n * counts (unlike SensitiveMatcher's own glob dialect in sensitive.ts).\n */\nfunction firstBraceSet(pattern: string): BraceSet | undefined {\n const open: { at: number; commas: number[] }[] = [];\n let first: { at: number; commas: number[]; close: number } | undefined;\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n if (char === '{') open.push({ at: i, commas: [] });\n else if (char === ',') open.at(-1)?.commas.push(i);\n else if (char === '}') {\n const set = open.pop();\n if (!set || (first && first.at < set.at)) continue;\n const body = pattern.slice(set.at + 1, i);\n if (set.commas.length > 0 || NUMERIC_RANGE_RE.test(body) || ALPHA_RANGE_RE.test(body)) {\n first = { ...set, close: i };\n }\n }\n }\n if (!first) return undefined;\n let alternatives: string[] | undefined;\n if (first.commas.length > 0) {\n alternatives = [];\n let start = first.at + 1;\n for (const end of [...first.commas, first.close]) {\n alternatives.push(pattern.slice(start, end));\n start = end + 1;\n }\n } else {\n alternatives = rangeValues(pattern.slice(first.at + 1, first.close));\n }\n return { pre: pattern.slice(0, first.at), alternatives, post: pattern.slice(first.close + 1) };\n}\n\n/** Every brace alternative of `pattern`, or `undefined` past the cap. */\nfunction expandBraceSets(pattern: string, out: string[] = []): string[] | undefined {\n const set = firstBraceSet(pattern);\n if (!set) {\n out.push(pattern);\n return out.length > MAX_BRACE_ALTERNATIVES ? undefined : out;\n }\n if (!set.alternatives) return undefined;\n for (const alternative of set.alternatives) {\n if (!expandBraceSets(`${set.pre}${alternative}${set.post}`, out)) return undefined;\n }\n return out;\n}\n\n/** The characters minimatch can spell a literal `..` with: dots and one-character classes. */\nconst DOTDOT_SPELLING_RE = /^[.[\\]-]+$/u;\n\n/**\n * Whether the glob engine reads this brace-free segment as `..`. readdir never\n * yields `..`, so only a literal reaches it, and minimatch spells a literal dot\n * as `.`, `[.]` or `[.-.]`. Any other character (`*`, `?`, an extglob, a\n * letter) either makes the segment a pattern the walk never follows to `..`,\n * or puts that character in the name. Only the rest is worth asking the engine\n * about, so a long or exotic segment costs no compile; one the engine cannot\n * compile is refused.\n */\nconst isTraversalSegment = (segment: string): boolean => {\n try {\n return matchesGlob('..', segment);\n } catch {\n return true;\n }\n};\n\n/**\n * An alternative that starts at a root: `/x`, `//host/share`, `C:/x`, `C:x`,\n * on any host. On Windows fs.glob also reads a literal first segment ending in\n * `:` as a drive (`[C]:/x`); elsewhere that is an ordinary name (`logs:`).\n */\nconst isRooted = (alternative: string): boolean =>\n win32.parse(alternative).root !== '' ||\n (IS_WINDOWS && (alternative.split('/')[0] ?? '').endsWith(':'));\n\n/**\n * Index of the `)` that closes the group opened at `open`, or -1. A `[...]`\n * class is skipped whole: a `)` or `|` inside one is a literal, not syntax.\n */\nfunction groupClose(segment: string, open: number): number {\n let depth = 0;\n for (let i = open; i < segment.length; i++) {\n const c = segment[i];\n if (c === '[') {\n // A `]` first in the class (or after `!`/`^`) is literal, so search past it.\n const first = segment[i + 1] === '!' || segment[i + 1] === '^' ? i + 2 : i + 1;\n const end = segment.indexOf(']', first + 1);\n if (end !== -1) {\n i = end;\n continue;\n }\n }\n if (c === '(') depth++;\n else if (c === ')' && --depth === 0) return i;\n }\n return -1;\n}\n\n/**\n * Whether matching this brace-free segment can backtrack for seconds on one\n * long name. Two shapes do: a repeated group (`*(…)`, `+(…)`) whose body can\n * match more than one way (`|`, `*`, or a nested group), and more than\n * MAX_SEGMENT_WILDCARDS `*` runs and extglob groups together.\n */\nfunction canBacktrack(segment: string): boolean {\n if (segment === '**') return false;\n let wildcards = (segment.match(/\\*+/gu) ?? []).length;\n for (let i = segment.indexOf('('); i !== -1; i = segment.indexOf('(', i + 1)) {\n const opener = segment[i - 1];\n if (opener === undefined || !'*+?@!'.includes(opener)) continue;\n // Each group can match more than one way, so it adds a degree of\n // backtracking like a `*` run does (`*(` is already counted as one).\n if (opener !== '*') wildcards++;\n if (opener !== '*' && opener !== '+') continue;\n const close = groupClose(segment, i);\n // Classes are literals: only `|`, `*` or a group outside one can backtrack.\n const body = segment\n .slice(i + 1, close === -1 ? undefined : close)\n .replace(/\\[[!^]?\\]?[^\\]]*\\]/gu, '');\n if (/[|*(]/u.test(body)) return true;\n }\n return wildcards > MAX_SEGMENT_WILDCARDS;\n}\n\nexport function isSafeGlobSyntax(pattern: string): boolean {\n if (!pattern || pattern.trim().length === 0) {\n return false;\n }\n // The walk sees the pattern with `\\` as `/` (normalizePattern), so check\n // that form: `\\etc\\x` is `/etc/x` there, an absolute walk on any host.\n // Brace sets can build a root or a `..` from parts (`{/etc,x}`, `..{,x}`,\n // `.{Z..a}.`), so check every alternative, not the pattern as written.\n // globEntries still drops any match outside its cwd: this check is what\n // turns such a pattern into an error rather than a quietly narrower walk.\n const alternatives = expandBraceSets(toPosixPath(pattern));\n if (!alternatives) return false;\n const segments = new Set<string>();\n for (const alternative of alternatives) {\n if (isRooted(alternative)) return false;\n for (const segment of alternative.split('/')) segments.add(segment);\n }\n let dotdotCheckChars = 0;\n for (const segment of segments) {\n if (canBacktrack(segment)) return false;\n if (!segment.includes('.') || !DOTDOT_SPELLING_RE.test(segment)) continue;\n dotdotCheckChars += segment.length;\n if (dotdotCheckChars > MAX_DOTDOT_CHECK_CHARS || isTraversalSegment(segment)) return false;\n }\n return true;\n}\n\n/** A .gitignore past this size is not a .gitignore; skip it rather than read it. */\nconst MAX_GITIGNORE_BYTES = MIB;\n\nasync function loadGitignoreFiles(\n root: string,\n gitignorePaths: readonly string[],\n manager: GitignoreManager,\n signal?: AbortSignal,\n): Promise<void> {\n await processInParallel(\n gitignorePaths,\n async (relPath) => {\n const absPath = join(root, relPath);\n try {\n // lstat, not stat: a symlinked .gitignore may point at a device, a\n // FIFO or a huge file outside the root. Only a plain, small file is a\n // rule set worth reading.\n const info = await lstat(absPath);\n if (!info.isFile() || info.size > MAX_GITIGNORE_BYTES) return;\n const contents = await fsReadFile(absPath, { encoding: 'utf-8', signal });\n const matcher = ignore();\n matcher.add(contents);\n const dir = toPosixPath(dirname(relPath));\n manager.addMatcher(dir === '.' ? '' : dir, matcher);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(`Failed to read .gitignore at ${absPath}: ${formatUnknownErrorMessage(error)}`);\n }\n },\n GLOB_BATCH_CONCURRENCY,\n signal,\n );\n}\n\n/**\n * Load `.gitignore` from each ancestor of `root` up to and including `ceiling`,\n * farthest first. A rule set that ignores `root` itself is skipped: the caller\n * named that directory on purpose, and applying the rule would empty the walk.\n */\nasync function loadAncestorGitignores(\n root: string,\n ceiling: string,\n manager: GitignoreManager,\n signal?: AbortSignal,\n): Promise<void> {\n const normalizedCeiling = resolve(ceiling);\n const chain: string[] = [];\n for (let dir = dirname(resolve(root)); ; dir = dirname(dir)) {\n if (!isPathInsideDirectory(normalizedCeiling, dir)) break;\n chain.push(dir);\n if (\n (isPathInsideDirectory(dir, normalizedCeiling) &&\n isPathInsideDirectory(normalizedCeiling, dir)) ||\n dirname(dir) === dir\n ) {\n break;\n }\n }\n for (const dir of chain.reverse()) {\n signal?.throwIfAborted();\n const file = join(dir, '.gitignore');\n try {\n const info = await lstat(file);\n if (!info.isFile() || info.size > MAX_GITIGNORE_BYTES) continue;\n const matcher = ignore().add(await fsReadFile(file, { encoding: 'utf-8', signal }));\n const prefix = toPosixPath(relative(dir, root));\n if (matcher.test(`${prefix}/`).ignored) continue;\n manager.addAncestorMatcher(prefix, matcher);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n // ENOENT is the normal case (no .gitignore at this level); anything else is not worth a warning per walk\n }\n }\n}\n\nclass GitignoreManager {\n private matchers = new Map<string, Ignore>();\n /** Rules from directories above the walk root, farthest first; `prefix` re-bases a walk-relative path to that directory. */\n private ancestors: { prefix: string; matcher: Ignore }[] = [];\n private dirCache = new Map<string, boolean>();\n\n addMatcher(dir: string, matcher: Ignore): void {\n this.matchers.set(dir, matcher);\n }\n\n addAncestorMatcher(prefix: string, matcher: Ignore): void {\n this.ancestors.push({ prefix, matcher });\n }\n\n /** `null` when no `.gitignore` was found, so callers skip the filter entirely. */\n static async load(\n root: string,\n includeHidden: boolean,\n signal?: AbortSignal,\n maxDepth?: number,\n ignoreCeiling?: string,\n ): Promise<GitignoreManager | null> {\n const manager = new GitignoreManager();\n try {\n const gitignorePaths: string[] = [];\n // Search dot-directories (.venv, .terraform, ...) for rules only when the\n // walk includes hidden entries; for any other walk, enumerating every\n // hidden tree would cost more than the walk itself.\n const gitignorePatterns = includeHidden\n ? [...buildHiddenPatterns('**/.gitignore')]\n : ['**/.gitignore'];\n const gitignoreEntries = fsGlob(gitignorePatterns, {\n cwd: root,\n // Skip what the walk itself skips, and stop one level past its depth\n // bound: a .gitignore at depth d only affects entries at depth >= d.\n exclude: (entry: string) => {\n if (signal?.aborted) return true;\n const name = basename(entry);\n if (name === '.hg' || name === '.svn' || DEFAULT_EXCLUDED_NAMES.has(name)) return true;\n return maxDepth !== undefined && toPosixPath(entry).split('/').length - 1 > maxDepth;\n },\n });\n for await (const match of gitignoreEntries) {\n if (signal?.aborted) break;\n gitignorePaths.push(match);\n }\n\n await loadGitignoreFiles(root, gitignorePaths, manager, signal);\n if (ignoreCeiling !== undefined) {\n await loadAncestorGitignores(root, ignoreCeiling, manager, signal);\n }\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(\n `Failed to enumerate .gitignore files under ${root}: ${formatUnknownErrorMessage(error)}`,\n );\n }\n return manager.matchers.size === 0 && manager.ancestors.length === 0 ? null : manager;\n }\n\n isIgnored(relativePath: string, isDirectory: boolean): boolean {\n const normalized = toPosixPath(relativePath);\n if (normalized === '' || normalized === '.') return false;\n const parts = normalized.split('/');\n\n // 1. Check parent directories first\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n if (this.checkDir(currentDir)) {\n return true;\n }\n }\n\n // 2. Check the file/directory itself\n return isDirectory ? this.checkDir(normalized) : this.checkPath(normalized, false);\n }\n\n private checkDir(dir: string): boolean {\n const cached = this.dirCache.get(dir);\n if (cached !== undefined) return cached;\n const res = this.checkPath(dir, true);\n this.dirCache.set(dir, res);\n return res;\n }\n\n private checkPath(posixPath: string, isDirectory: boolean): boolean {\n const parts = posixPath.split('/');\n const pathToCheck = isDirectory\n ? posixPath.endsWith('/')\n ? posixPath\n : `${posixPath}/`\n : posixPath;\n\n let ignored = false;\n\n for (const { prefix, matcher } of this.ancestors) {\n const res = matcher.test(`${prefix}/${pathToCheck}`);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n\n // Check root level\n const rootMatcher = this.matchers.get('');\n if (rootMatcher) {\n const res = rootMatcher.test(pathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n\n // Check subdirectories\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n const matcher = this.matchers.get(currentDir);\n if (matcher) {\n const relParts = parts.slice(i + 1);\n const relPath = relParts.join('/');\n const relPathToCheck = isDirectory\n ? relPath.endsWith('/')\n ? relPath\n : `${relPath}/`\n : relPath;\n\n const res = matcher.test(relPathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n }\n\n return ignored;\n }\n}\n\ninterface GlobDirentLike extends DirentLike {\n name: string;\n parentPath: string;\n}\n\nexport interface GlobEntry {\n path: string;\n dirent: DirentLike;\n}\n\nexport interface GlobEntriesOptions {\n cwd: string;\n pattern: string;\n includeHidden?: boolean;\n baseNameMatch?: boolean;\n maxDepth?: number;\n onlyFiles?: boolean;\n suppressErrors?: boolean;\n /** Skip what a walk should not surface: DEFAULT_EXCLUDED_NAMES and .gitignore. */\n skipIgnored?: boolean;\n /**\n * Topmost directory whose `.gitignore` may apply to this walk — the allowed\n * root containing `cwd`. Ancestors of `cwd` up to and including it are\n * consulted; nothing above it is ever read. Ignored without `skipIgnored`.\n */\n ignoreCeiling?: string;\n /**\n * Prune directories whose own name the sensitive denylist covers: the walk\n * never descends into them nor yields them. Opt-in — a walk that must see\n * sensitive entries (the move-protection check) does not pass it.\n */\n pathGuard?: Pick<PathGuard, 'isSensitive'>;\n /** Bounds the `.gitignore` discovery `skipIgnored` runs before the walk. */\n signal?: AbortSignal;\n}\n\ninterface NormalizedGlob {\n cwd: string;\n patterns: readonly string[];\n suppressErrors: boolean;\n maxDepth?: number;\n}\n\nconst GLOB_MAGIC_RE = /[*?[\\]{}!]/u;\nconst GLOB_BATCH_CONCURRENCY = 64;\nconst SEP = '/';\nfunction normalizePattern(pattern: string, baseNameMatch: boolean): string {\n const normalized = toPosixPath(pattern);\n\n if (!baseNameMatch) return normalized;\n if (normalized.includes(SEP)) return normalized;\n return `**/${normalized}`;\n}\n\nfunction splitPatternPrefix(normalizedPattern: string): {\n prefix: string;\n remainder: string;\n} {\n if (!GLOB_MAGIC_RE.test(normalizedPattern)) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n const segments = normalizedPattern.split(SEP);\n const splitIndex = segments.findIndex((seg) => GLOB_MAGIC_RE.test(seg));\n\n if (splitIndex <= 0) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n return {\n prefix: segments.slice(0, splitIndex).join(SEP) + SEP,\n remainder: segments.slice(splitIndex).join(SEP),\n };\n}\n\n/**\n * The segment matching the dot-prefixed names `segment` would match if fs.glob\n * did not skip them, or `undefined` when there are none. Only a leading `*` or `?`\n * stands for that dot: a literal never does, and a character class or a\n * brace set is left as written rather than parsed.\n */\nfunction dotVariant(segment: string): string | undefined {\n // `*(…)`, `?(…)` and `!(…)` are extglobs, not wildcards.\n if (segment[1] === '(') return undefined;\n if (segment.startsWith('*')) return `.${segment}`;\n if (!segment.startsWith('?')) return undefined;\n // `?` is exactly one character, so the dot replaces it, unless what follows\n // could leave just `.` or `..` (`?`, `?.`, `?{.,x}`, `?[.]`): the directory\n // and its parent, not a dot-prefixed entry.\n const rest = segment.slice(1);\n return rest === '' || /^[.[{]/u.test(rest) ? undefined : `.${rest}`;\n}\n\nfunction addFirstDotSegment(patterns: Set<string>, prefix: string, remainder: string): void {\n if (remainder.length === 0) return;\n const segments = remainder.split(SEP);\n const idx = segments.findIndex((seg) => seg !== '**' && seg.length > 0);\n\n if (idx !== -1) {\n const original = segments[idx];\n const dotted = original ? dotVariant(original) : undefined;\n if (dotted) {\n const newSegments = [...segments];\n newSegments[idx] = dotted;\n patterns.add(`${prefix}${newSegments.join(SEP)}`);\n }\n }\n}\n\nfunction expandHiddenGlobstars(patterns: Set<string>, prefix: string, remainder: string): void {\n // Trailing bare globstar — `src/**`, `**` (remainder is exactly `**`, no\n // following segment). The pattern itself already matches every non-dot\n // entry under the prefix; add the two hidden complements fs.glob skips:\n // dotfiles/dot-dirs anywhere, and the contents of dot-dirs anywhere.\n if (remainder === '**') {\n patterns.add(`${prefix}**/.*`);\n patterns.add(`${prefix}**/.*/**`);\n return;\n }\n\n if (!remainder.startsWith('**/')) return;\n\n const afterGlobstar = remainder.slice(3);\n // Node fs.glob skips leading-dot entries unless the matching segment itself\n // starts with '.', and its `dot` option is not honored. So `**/*` alone misses\n // hidden files. Two depth-agnostic patterns cover everything the per-depth\n // unroll did: contents of dot-directories anywhere, and dotfiles/dotdirs\n // anywhere (when the first segment after the globstar can match a dot).\n patterns.add(`${prefix}**/.*/**/${afterGlobstar}`);\n const [firstSegment = '', ...rest] = afterGlobstar.split(SEP);\n const dotted = dotVariant(firstSegment);\n if (dotted) patterns.add(`${prefix}**/${[dotted, ...rest].join(SEP)}`);\n}\n\nfunction buildHiddenPatterns(normalizedPattern: string): readonly string[] {\n const patterns = new Set<string>([normalizedPattern]);\n const { prefix, remainder } = splitPatternPrefix(normalizedPattern);\n\n addFirstDotSegment(patterns, prefix, remainder);\n expandHiddenGlobstars(patterns, prefix, remainder);\n\n return Array.from(patterns);\n}\n\nfunction normalizeGlobOptions(options: GlobEntriesOptions): NormalizedGlob {\n const cwd = resolve(options.cwd);\n const normalizedPattern = normalizePattern(options.pattern, options.baseNameMatch ?? false);\n\n const patterns = options.includeHidden\n ? buildHiddenPatterns(normalizedPattern)\n : [normalizedPattern];\n\n const normalized: NormalizedGlob = {\n cwd,\n patterns,\n suppressErrors: options.suppressErrors ?? false,\n };\n\n if (options.maxDepth !== undefined) {\n normalized.maxDepth = options.maxDepth;\n }\n\n return normalized;\n}\n\nfunction* processDirentMatch(\n match: GlobDirentLike,\n cwd: string,\n maxDepth: number | undefined,\n seen: Set<string>,\n onlyFiles: boolean,\n): Generator<GlobEntry> {\n const absolutePath = resolve(cwd, match.parentPath, match.name);\n // The walk's scope is its cwd, whatever the pattern spells: a `..` or a root\n // the validator did not foresee must not reach a caller, where it would be\n // read, rewritten, or counted and named as inaccessible.\n if (!isPathInsideDirectory(cwd, absolutePath)) return;\n\n if (maxDepth !== undefined) {\n const rel = relative(cwd, absolutePath);\n if (rel.split(/[/\\\\]/u).length - 1 > maxDepth) return;\n }\n\n if (seen.has(absolutePath)) return;\n seen.add(absolutePath);\n\n if (onlyFiles && !match.isFile()) return;\n yield { path: absolutePath, dirent: match };\n}\n\ninterface WalkFilter {\n /** Given to fs.glob: true stops descent into a directory. */\n prune: (match: GlobDirentLike) => boolean;\n /** Re-applied to yielded entries: the ignore rules only, never the depth bound. */\n isExcluded: (match: GlobDirentLike) => boolean;\n}\n\nfunction createWalkFilter(\n cwd: string,\n skipIgnored: boolean,\n gitignoreMatcher: GitignoreManager | null,\n maxDepth: number | undefined,\n signal: AbortSignal | undefined,\n pathGuard: Pick<PathGuard, 'isSensitive'> | undefined,\n): WalkFilter {\n // fs.glob can hand the predicate a dirent whose parentPath is \".\" — the walk\n // root, not the process cwd — when it re-visits a directory under `**` whose\n // name also exists in the process cwd. Resolving against `cwd` names the\n // entry the dirent describes; `join` would resolve it against the process.\n const absoluteOf = (match: GlobDirentLike): string => resolve(cwd, match.parentPath, match.name);\n const relativeOf = (match: GlobDirentLike): string =>\n toPosixPath(relative(cwd, absoluteOf(match)));\n // Every default exclude is a bare name that applies at any depth, so a Set\n // lookup per segment replaces compiling dozens of globs per entry.\n const excluded = (posixRel: string, isDir: boolean): boolean =>\n skipIgnored &&\n (posixRel.split('/').some((segment) => DEFAULT_EXCLUDED_NAMES.has(segment)) ||\n (gitignoreMatcher?.isIgnored(posixRel, isDir) ?? false));\n // A sensitive directory's subtree is hidden with the directory: pruning\n // stops descent, and the yielded dirent is dropped below. The guard checks\n // the directory's own path, so this never fires on a clean-named entry inside\n // a denylisted tree — the tree never gets walked.\n const sensitiveDir = (match: GlobDirentLike): boolean =>\n pathGuard !== undefined && match.isDirectory() && pathGuard.isSensitive(absoluteOf(match));\n // A sensitive directory anywhere above an entry hides the entry, whatever\n // the pattern spelled: a literal prefix (`vault.key/*.txt`) never asks the\n // descent prune, and a sensitive-named symlink is not isDirectory() so the\n // prune misses it — but every yielded path names its ancestors. The entry's\n // own final name stays with the per-entry guard every caller already runs.\n const sensitiveTreeCache = new Map<string, boolean>();\n const sensitiveTree = (posixRel: string): boolean => {\n if (pathGuard === undefined) return false;\n const segments = posixRel.split('/');\n for (let i = 1; i < segments.length; i++) {\n const prefix = segments.slice(0, i).join('/');\n let hit = sensitiveTreeCache.get(prefix);\n if (hit === undefined) {\n hit = pathGuard.isSensitive(resolve(cwd, prefix));\n sensitiveTreeCache.set(prefix, hit);\n }\n if (hit) return true;\n }\n return false;\n };\n\n return {\n prune: (match) => {\n // fs.glob takes no signal and calls this for every entry it visits, so\n // pruning everything is the only way to stop a walk that yields nothing.\n if (signal?.aborted) return true;\n // fs.glob asks before it queues a directory, so a walk that would\n // climb to `../` or start at `/` stops at the edge instead of reading\n // there. Not every climb asks (`**/..` does not): processDirentMatch is\n // the gate, this only saves the walk.\n if (!isPathInsideDirectory(cwd, absoluteOf(match))) return true;\n const posixRel = relativeOf(match);\n const isDir = match.isDirectory();\n if (excluded(posixRel, isDir)) return true;\n if (sensitiveDir(match) || sensitiveTree(posixRel)) return true;\n // Stop descent one level past the depth bound. Pruning a directory *at*\n // the bound would drop it where fs.glob treats it as top-level, so prune\n // its children instead; processDirentMatch drops that extra level.\n if (maxDepth === undefined || !isDir) return false;\n return posixRel.split('/').length - 1 > maxDepth;\n },\n isExcluded: (match) => {\n const posixRel = relativeOf(match);\n return (\n excluded(posixRel, match.isDirectory()) || sensitiveDir(match) || sensitiveTree(posixRel)\n );\n },\n };\n}\n\nasync function* processGlobPatterns(\n patterns: readonly string[],\n plan: NormalizedGlob,\n seen: Set<string>,\n onlyFiles: boolean,\n filter: WalkFilter,\n signal: AbortSignal | undefined,\n): AsyncGenerator<GlobEntry> {\n const { cwd, maxDepth, suppressErrors } = plan;\n let iterable: AsyncIterable<GlobDirentLike>;\n try {\n iterable = fsGlob([...patterns], {\n cwd,\n exclude: filter.prune,\n withFileTypes: true,\n }) as AsyncIterable<GlobDirentLike>;\n } catch (error) {\n if (suppressErrors) return;\n throw error;\n }\n\n try {\n for await (const match of iterable) {\n if (signal?.aborted) break;\n // A function `exclude` only prunes descent in fs.glob — it still yields\n // the rejected dirent itself, and any rejected entry below the top level.\n // Re-apply the ignore rules (not the depth bound) to drop those.\n if (filter.isExcluded(match)) continue;\n yield* processDirentMatch(match, cwd, maxDepth, seen, onlyFiles);\n }\n } catch (error) {\n if (!suppressErrors) throw error;\n Logger.warn(\n `globEntries: suppressed mid-walk error for pattern \"${patterns.join(', ')}\": ${formatUnknownErrorMessage(error)}`,\n );\n }\n // A pruned walk ends like a finished one. Say it was cut short, so no caller\n // reads \"the walk ended\" as \"the whole tree was seen\".\n signal?.throwIfAborted();\n}\n\nexport async function* globEntries(options: GlobEntriesOptions): AsyncGenerator<GlobEntry> {\n const gitignoreMatcher = options.skipIgnored\n ? await GitignoreManager.load(\n options.cwd,\n options.includeHidden ?? false,\n options.signal,\n options.maxDepth,\n options.ignoreCeiling,\n )\n : null;\n\n const plan = normalizeGlobOptions(options);\n const seen = new Set<string>();\n const onlyFiles = options.onlyFiles ?? true;\n const filter = createWalkFilter(\n plan.cwd,\n options.skipIgnored ?? false,\n gitignoreMatcher,\n plan.maxDepth,\n options.signal,\n options.pathGuard,\n );\n\n // One walk for every variant: fs.glob reads each directory once and matches\n // all of them, where a walk per variant re-read the tree for each.\n yield* processGlobPatterns(plan.patterns, plan, seen, onlyFiles, filter, options.signal);\n}\n\n/** Names a `skipIgnored` walk never enters or yields, at any depth. */\nconst DEFAULT_EXCLUDED_NAMES: ReadonlySet<string> = new Set([\n 'node_modules',\n 'dist',\n 'build',\n 'coverage',\n '.git',\n '.vscode',\n '.idea',\n '.DS_Store',\n '.next',\n '.nuxt',\n '.output',\n '.svelte-kit',\n '.cache',\n '.yarn',\n 'jspm_packages',\n 'bower_components',\n 'out',\n 'tmp',\n '.temp',\n 'npm-debug.log',\n 'yarn-debug.log',\n 'yarn-error.log',\n 'Thumbs.db',\n]);\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version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