@poe-platform/safe-bash 0.1.660 → 0.1.661
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/dist/safe-bash/chunks/{chunk-STBTGG6M.js → chunk-2GRCWCMW.js} +4 -3
- package/dist/safe-bash/chunks/chunk-2GRCWCMW.js.map +7 -0
- package/dist/safe-bash/commands/node/index.browser.js +1 -1
- package/dist/safe-bash/core.browser.js +1 -1
- package/package.json +2 -2
- package/dist/safe-bash/chunks/chunk-STBTGG6M.js.map +0 -7
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../src/commands/node/browser.ts", "../../src/commands/node/safejs.ts", "../../src/integrations/safejs/values.ts", "../../src/commands/safejs/runtime.ts", "../../src/integrations/safejs/index.ts", "../../src/integrations/safejs/filesystem.ts", "../../../safe-js/dist/browser/safe-fs.js", "../../../safe-fs/src/platform/browser.ts", "../../../safe-fs/src/contracts/errors.ts", "../../../safe-fs/src/contracts/filesystem.ts", "../../../safe-fs/src/contracts/cleanup.ts", "../../../safe-fs/src/contracts/io.ts", "../../../safe-fs/src/fs/descriptor.ts", "../../../safe-fs/src/contracts/virtual-path.ts", "../../../safe-fs/src/contracts/portable-path.ts", "../../../safe-fs/src/fs/mount/identity.ts", "../../../safe-fs/src/fs/mount/comparison.ts", "../../../safe-fs/src/fs/s3/registry.ts", "../../../safe-fs/src/fs/webdav/resource-id.ts", "../../../safe-fs/src/fs/directory-admission.ts", "../../../safe-fs/src/fs/memory/missing-target.ts", "../../../safe-fs/src/fs/memory/ledger.ts", "../../../safe-fs/src/config.ts", "../../../safe-fs/src/fs/memory/limits.ts", "../../../safe-fs/src/fs/memory/index.ts", "../../../safe-fs/src/fs/path-namespace.ts", "../../../safe-fs/src/fs/devices/path.ts", "../../../safe-fs/src/fs/devices/stream.ts", "../../../safe-fs/src/fs/capabilities.ts", "../../../safe-fs/src/fs/devices/index.ts", "../../../safe-fs/src/fs/readonly/index.ts", "../../../safe-fs/src/fs/mount/index.ts", "../../../safe-fs/src/fs/overlay/index.ts", "../../../safe-fs/src/fs/quota/index.ts", "../../../safe-fs/src/fs/scoped.ts", "../../../safe-fs/src/contracts/abort.ts", "../../../safe-fs/src/xml.ts", "../../../safe-fs/src/fs/webdav/xml.ts", "../../../safe-fs/src/fs/webdav/webdav.ts", "../../../safe-fs/src/bridge/stats.ts", "../../../safe-fs/src/bridge/values.ts", "../../../safe-fs/src/bridge/confinement.ts", "../../../safe-fs/src/bridge/filesystem.ts", "../../../safe-fs/src/bridge/index.ts", "../../../safe-fs/src/python/request.ts", "../../../safe-fs/src/python/filesystem.ts", "../../../safe-fs/src/python/flags.ts", "../../../safe-fs/src/python/emscripten.ts", "../../../safe-fs/src/python/stat.ts", "../../src/integrations/safejs/shell.ts", "../../src/commands/safejs/io.ts", "../../src/commands/safejs/types.ts", "../../src/commands/safejs/render.ts", "../../src/commands/safejs/options.ts"],
|
|
4
|
-
"sourcesContent": ["export {\n createSafeJsNodeCommand as createNodeCommand,\n createSafeJsNodeCommands as createNodeCommands,\n safeJsNodeCommands as nodeCommands,\n type SafeJsNodeCommandsOptions as NodeCommandsOptions,\n} from \"./safejs.js\";\n", "import type { CommandDefinition } from \"../../contracts/command.js\";\nimport type { VirtualShellPlugin } from \"../../contracts/plugin.js\";\nimport { onlyKeys, record } from \"../../integrations/safejs/values.js\";\nimport { UsageError } from \"../internal.js\";\nimport { createSafeJsCommands } from \"../safejs/runtime.js\";\nimport type { Invocation } from \"../safejs/options.js\";\nimport type { NodeSafeJsCommandOptions } from \"./types.js\";\n\nexport type SafeJsNodeCommandsOptions<Budget = unknown> = NodeSafeJsCommandOptions<Budget> & { readonly replace?: boolean };\n\nexport function createSafeJsNodeCommands<Budget>(options: SafeJsNodeCommandsOptions<Budget>): readonly CommandDefinition[] {\n const settings = record(options, \"node options\");\n onlyKeys(settings, [\"runtime\", \"limits\", \"replace\"]);\n if (Object.hasOwn(settings, \"replace\") && typeof settings.replace !== \"boolean\") throw new TypeError(\"node replace must be boolean\");\n delete settings.replace;\n return Object.freeze([createSafeJsNodeCommand(settings as unknown as NodeSafeJsCommandOptions<Budget>)]);\n}\n\nexport function safeJsNodeCommands<Budget>(options: SafeJsNodeCommandsOptions<Budget>): VirtualShellPlugin {\n const definitions = createSafeJsNodeCommands(options);\n const replace = options.replace ?? false;\n return { name: \"node-commands\", setup(host) {\n if (!replace && host.commands.has(\"node\")) throw new Error(\"Command already registered: node\");\n for (const definition of definitions) host.commands.register(definition, { replace });\n } };\n}\n\nfunction invocation(args: readonly string[]): Invocation {\n let source: string | undefined;\n let print = false;\n let index = 0;\n for (; index < args.length; index++) {\n const argument = args[index]!;\n if (argument === \"--\") { index++; break; }\n if (argument === \"-h\" || argument === \"--help\") return { file: \"-\", args: [], print: false, help: true };\n if (argument === \"--input-type\" || argument.startsWith(\"--input-type=\")) {\n const value = argument === \"--input-type\" ? args[++index] : argument.slice(13);\n if (value !== \"module\") throw new UsageError(\"SafeJS node supports only --input-type=module\");\n continue;\n }\n const mode = argument === \"--eval\" || argument.startsWith(\"--eval=\") || argument.startsWith(\"-e\") ? \"eval\"\n : argument === \"--print\" || argument.startsWith(\"--print=\") || argument.startsWith(\"-p\") ? \"print\" : undefined;\n if (mode) {\n if (source !== undefined) throw new UsageError(\"conflicting source selectors\");\n print = mode === \"print\";\n const equal = argument.indexOf(\"=\");\n source = argument.startsWith(\"--\") ? equal >= 0 ? argument.slice(equal + 1) : args[++index]\n : argument.length > 2 ? argument.slice(2) : args[++index];\n if (source === undefined) throw new UsageError(`${argument} requires JavaScript source`);\n continue;\n }\n if (argument !== \"-\" && argument.startsWith(\"-\")) throw new UsageError(`unsupported node option '${argument}'`);\n break;\n }\n if (source !== undefined) return { source, file: print ? \"<node -p>\" : \"<node -e>\", args: args.slice(index), print, help: false };\n return { file: args[index] ?? \"-\", args: args.slice(index + 1), print: false, help: false };\n}\n\nexport function createSafeJsNodeCommand<Budget>(options: NodeSafeJsCommandOptions<Budget>): CommandDefinition {\n const settings = record(options, \"node options\");\n onlyKeys(settings, [\"runtime\", \"limits\"]);\n if (settings.runtime === undefined || settings.runtime === null) throw new TypeError(\"node requires an injected SafeJS runtime\");\n options = settings as unknown as NodeSafeJsCommandOptions<Budget>;\n const definitions = createSafeJsCommands(options, {\n name: \"node\",\n description: \"Execute JavaScript with an injected SafeJS runtime and virtual I/O\",\n help: \"Usage: node [-e SOURCE | -p EXPRESSION | FILE | -] [ARG...]\\nExecutes with the injected SafeJS interpreter; no native Node.js process.\\nSupports --eval, --print, --input-type=module and -- before operands.\\nNo source operand reads stdin. Files and inline source leave stdin for guest data.\\nUse async imports from fs or require(\\\"node:fs/promises\\\").\\nNative modules, synchronous fs and local module loading are not supported.\\n\",\n invocation,\n prepare(source, selected, modules) {\n const command = modules.command!;\n const stdio = modules.stdio!;\n const fs = modules.fs!;\n const processModule = {\n argv: [\"/virtual/bin/node\", ...(selected.source === undefined ? [selected.file] : []), ...selected.args],\n env: command.env,\n cwd: options.runtime.declareHostOperation(() => command.cwd, \"read-side-effect\"),\n exitCode: 0,\n stdin: { readText: stdio.readText, readBytes: stdio.readBytes },\n stdout: { write: stdio.write },\n stderr: { write: stdio.error },\n };\n modules.fs = { ...fs, default: fs };\n const requiredModules = new Map([[\"fs/promises\", fs], [\"node:fs/promises\", fs]]);\n return {\n source: (selected.print ? `console.log((\\n${source}\\n));` : source) + \"\\n;__safeBashSetExitCode(process.exitCode);\",\n bindings: {\n process: processModule, __safeBashSetExitCode: command.setExitCode,\n require: options.runtime.declareHostOperation((name: unknown) => {\n const module = typeof name === \"string\" ? requiredModules.get(name) : undefined;\n if (!module) throw new TypeError(\"Unsupported node module; use fs/promises or node:fs/promises\");\n return module;\n }, \"read-side-effect\"),\n },\n };\n },\n });\n return Object.freeze(definitions[0]!);\n}\n", "export function record(value: unknown, name: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${name} must be a plain object`);\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(`${name} must be a plain object`);\n }\n const result: Record<string, unknown> = {};\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (typeof key !== \"string\" || descriptor === undefined || !(\"value\" in descriptor)) {\n throw new TypeError(`${name} must contain only string-keyed data properties`);\n }\n Object.defineProperty(result, key, {\n value: descriptor.value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return result;\n}\n\nexport function onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n for (const key of Object.keys(value)) {\n if (!allowed.includes(key)) throw new TypeError(`Unsupported option: ${key}`);\n }\n}\n\nexport function stringValue(value: unknown, name: string): string {\n if (typeof value !== \"string\") throw new TypeError(`${name} must be a string`);\n return value;\n}\n\nexport function booleanValue(value: unknown, fallback = false): boolean {\n if (value === undefined) return fallback;\n if (typeof value !== \"boolean\") throw new TypeError(\"Expected a boolean option\");\n return value;\n}\n\nexport function abortError(): Error {\n return Object.assign(new Error(\"The operation was aborted\"), {\n name: \"AbortError\",\n code: \"ABORT_ERR\",\n });\n}\n\nexport function checkSignal(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortError();\n}\n\nexport async function withSignal<Value>(\n signal: AbortSignal | undefined,\n operation: () => Promise<Value>,\n): Promise<Value> {\n checkSignal(signal);\n if (signal === undefined) return operation();\n let onAbort: () => void = () => undefined;\n const cancelled = new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n try {\n return await Promise.race([Promise.resolve().then(() => {\n checkSignal(signal);\n return operation();\n }), cancelled]);\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n", "import { PublicDiagnostic, publicDiagnosticMessage } from \"../../diagnostics.js\";\nimport { toByteSource, writeBytes, type CommandDefinition } from \"../../contracts/index.js\";\nimport { writeDiagnostic } from \"../../escaping.js\";\nimport { makeSafeJsFsModule } from \"../../integrations/safejs/index.js\";\nimport { record, withSignal } from \"../../integrations/safejs/values.js\";\nimport { pathOf, UsageError } from \"../internal.js\";\nimport { GuestInput, GuestOutput } from \"./io.js\";\nimport { commandLimits, type Invocation } from \"./options.js\";\nimport { SafeJsCommandLimitError, type SafeJsCommandsOptions, type SafeJsModule, type SafeJsRuntime } from \"./types.js\";\n\nexport interface SafeJsCommandDialect {\n readonly name: string;\n readonly description: string;\n readonly help: string;\n readonly invocation: (args: readonly string[]) => Invocation;\n readonly prepare?: (source: string, selected: Invocation, modules: Record<string, SafeJsModule>) => {\n readonly source: string;\n readonly bindings: SafeJsModule;\n };\n}\n\nclass GuestDiagnostic extends PublicDiagnostic {\n constructor(readonly info: { name: string; code: string; message: string }) { super(info.message); }\n}\n\nfunction errorInfo(error: unknown): { name: string; code: string; message: string } {\n if (typeof error === \"string\") return { name: \"Error\", code: \"\", message: error };\n if (typeof error !== \"object\" || error === null) return { name: \"Error\", code: \"\", message: \"SafeJS execution failed\" };\n const field = (name: string): string => {\n const descriptor = Object.getOwnPropertyDescriptor(error, name);\n return descriptor && \"value\" in descriptor && typeof descriptor.value === \"string\" ? descriptor.value : \"\";\n };\n return { name: field(\"name\"), code: field(\"code\"), message: field(\"message\") || \"SafeJS execution failed\" };\n}\n\nfunction statusField(error: unknown, name: \"name\" | \"code\"): string {\n if (typeof error !== \"object\" || error === null) return \"\";\n const descriptor = Object.getOwnPropertyDescriptor(error, name);\n return descriptor && \"value\" in descriptor && typeof descriptor.value === \"string\" ? descriptor.value : \"\";\n}\n\nfunction validateRuntime<Budget>(runtime: SafeJsRuntime<Budget> | undefined): void {\n if (runtime === undefined) return;\n for (const key of [\"run\", \"createBudget\", \"makeFsModule\", \"declareHostOperation\"] as const) {\n if (typeof runtime[key] !== \"function\") throw new TypeError(`SafeJS runtime.${key} must be injected`);\n }\n}\n\nexport function createSafeJsCommands<Budget = unknown>(options: SafeJsCommandsOptions<Budget>, dialect: SafeJsCommandDialect): readonly CommandDefinition[] {\n const limits = commandLimits(options.limits);\n const runtime = options.runtime;\n validateRuntime(runtime);\n return [{ name: dialect.name, description: dialect.description, async execute(context) {\n const deadline = Date.now() + limits.timeoutMs;\n const diagnose = async (message: string): Promise<void> => {\n const diagnostic = new AbortController();\n const timer = setTimeout(() => diagnostic.abort(), Math.max(1, Math.min(limits.timeoutMs, deadline - Date.now())));\n try { await writeDiagnostic(context.stderr, `${dialect.name}: ${message.slice(0, 4096)}\\n`, AbortSignal.any([context.signal, diagnostic.signal])); }\n catch (error) { context.signal.throwIfAborted(); if (!diagnostic.signal.aborted) throw error; }\n finally { clearTimeout(timer); }\n };\n let parsed;\n try { parsed = dialect.invocation(context.args); }\n catch (error) { await diagnose(publicDiagnosticMessage(error, context.onInternalError)); return { exitCode: 2 }; }\n context.signal.throwIfAborted();\n if (parsed.help) { await writeBytes(context.stdout, Buffer.from(dialect.help), context.signal); return { exitCode: 0 }; }\n if (!runtime) { await diagnose(\"runtime not installed; inject run, createBudget, makeFsModule and declareHostOperation\"); return { exitCode: 127 }; }\n const controller = new AbortController();\n const signal = AbortSignal.any([context.signal, controller.signal]);\n let failure: unknown;\n let hasFailure = false;\n const fail = (error: unknown): void => {\n if (!hasFailure && !controller.signal.aborted) {\n hasFailure = true;\n failure = error;\n queueMicrotask(() => controller.abort(error));\n }\n };\n const timeout = setTimeout(() => fail(new SafeJsCommandLimitError(\"timeoutMs\")), limits.timeoutMs);\n let input: GuestInput | undefined;\n const output = new GuestOutput(context.stdout, context.stderr, limits.maxOutputBytes, signal, fail);\n let exitCode = 0;\n let thrown: unknown;\n let failed = false;\n try {\n const fromStdin = parsed.source === undefined && parsed.file === \"-\";\n let source = parsed.source;\n let filename = parsed.file;\n if (source === undefined) {\n if (!fromStdin) filename = pathOf(context, parsed.file);\n const capabilities = fromStdin ? undefined : await withSignal(signal, async () =>\n await context.fs.capabilitiesFor?.(filename, { signal }) ?? context.fs.capabilities);\n const bytes = fromStdin ? context.stdin : context.fs.readStream && capabilities?.streamingRead !== false\n ? context.fs.readStream(filename, { signal, chunkSize: 65536 })\n : toByteSource(await withSignal(signal, () => context.fs.readFile(filename, { signal, maxBytes: limits.maxSourceBytes })));\n const reader = new GuestInput(bytes, limits.maxSourceBytes, signal, fail, \"maxSourceBytes\");\n try { source = await reader.readText(); } finally { await reader.close(); }\n } else if (Buffer.byteLength(source) > limits.maxSourceBytes) throw new SafeJsCommandLimitError(\"maxSourceBytes\");\n if (source.startsWith(\"\\uFEFF\")) source = source.slice(1);\n input = new GuestInput(fromStdin ? toByteSource(\"\") : context.stdin, limits.maxInputBytes, signal, fail);\n const guestInput = input;\n const declare = runtime.declareHostOperation;\n const stdio: SafeJsModule = {\n readBytes: declare(async (size?: unknown) => guestInput.readBytes(size), \"read-side-effect\"),\n readText: declare(async () => guestInput.readText(), \"read-side-effect\"),\n write: declare(async (text: unknown) => output.text(text), \"read-side-effect\"),\n writeBytes: declare(async (bytes: unknown) => output.bytes(bytes), \"read-side-effect\"),\n error: declare(async (text: unknown) => output.text(text, true), \"read-side-effect\"),\n errorBytes: declare(async (bytes: unknown) => output.bytes(bytes, true), \"read-side-effect\"),\n };\n const env: Record<string, string> = Object.create(null);\n for (const [key, value] of Object.entries(context.env)) env[key] = value;\n const command: SafeJsModule = {\n args: [...parsed.args], cwd: context.cwd, env,\n setExitCode: declare((value: unknown) => {\n signal.throwIfAborted();\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > 255) throw new TypeError(\"exit code must be an integer from 0 through 255\");\n exitCode = value;\n }, \"read-side-effect\"),\n };\n const budget = runtime.createBudget({ maxSteps: limits.maxSteps, deadline,\n maxCallDepth: limits.maxCallDepth, stringLength: limits.stringLength, arrayLength: limits.arrayLength, dataSize: limits.dataSize });\n const modules = { fs: makeSafeJsFsModule(runtime.makeFsModule, context.fs, { cwd: context.cwd, signal }), stdio, command };\n const prepared = dialect.prepare?.(source, { ...parsed, file: filename }, modules);\n const result = record(await withSignal(signal, () => runtime.run(prepared?.source ?? source, {\n budget, filename, modules, signal, ...(prepared ? { bindings: prepared.bindings } : {}),\n sink: { log: (...args) => output.console(args, false), error: (...args) => output.console(args, true) },\n })), \"SafeJS run result\");\n signal.throwIfAborted();\n if (result.ok !== true && result.ok !== false) throw new TypeError(\"Invalid SafeJS run result.ok\");\n if (!result.ok) {\n const info = errorInfo(result.error);\n throw new GuestDiagnostic(info);\n }\n if (parsed.print && result.returnValue !== undefined) await output.result(result.returnValue);\n await output.drain();\n } catch (error) { thrown = hasFailure ? failure : error; failed = true; }\n finally {\n try { await output.drain(); } catch (error) { thrown = hasFailure ? failure : error; failed = true; }\n controller.abort();\n clearTimeout(timeout);\n await input?.close().catch(() => {});\n }\n context.signal.throwIfAborted();\n if (failed) {\n const info = thrown instanceof GuestDiagnostic ? thrown.info : { name: statusField(thrown, \"name\"), code: statusField(thrown, \"code\") };\n const detail = thrown instanceof SafeJsCommandLimitError ? thrown.message : publicDiagnosticMessage(thrown, context.onInternalError);\n if (!output.stderrFailed) await diagnose(detail);\n return { exitCode: thrown instanceof SafeJsCommandLimitError || info.code === \"budgetExceeded\" ? 124\n : thrown instanceof UsageError || info.name === \"ParseError\" ? 2 : 1 };\n }\n return { exitCode };\n } }];\n}\n", "export { createNodeFsBridge, makeSafeJsFsModule } from \"./filesystem.js\";\nexport type { NodeFsBridgeFileSystem, NodeFsBridgeOptions, SafeJsFsImplementation } from \"./filesystem.js\";\nexport { makeSafeJsShellModule } from \"./shell.js\";\nexport type {\n DeclareShellHostOperation,\n SafeJsShellOptions,\n ShellExecute,\n ShellExecutionOptions,\n ShellExecutionResult,\n ShellExecutor,\n ShellGuestOptions,\n ShellHostOperation,\n} from \"./shell.js\";\n", "import type { FileSystem, NodeFsBridgeOptions } from \"poe-code/safe-fs\";\n\nexport { createNodeFsBridge } from \"poe-code/safe-fs\";\nexport type { NodeFsBridgeFileSystem, NodeFsBridgeOptions, NodeFsImplementation as SafeJsFsImplementation } from \"poe-code/safe-fs\";\n\nexport function makeSafeJsFsModule<Module>(\n makeFsModule: (options: { adapter: FileSystem } & NodeFsBridgeOptions) => Module,\n fs: FileSystem,\n options: NodeFsBridgeOptions = {},\n): Module {\n return makeFsModule({ adapter: fs, ...options });\n}\n", "import {\n ACCESS_MODES,\n DeviceFileSystem,\n FileSystemQuotaError,\n FsError,\n MemoryFileSystem,\n MountFileSystem,\n OverlayFileSystem,\n PythonFileSystem,\n PythonStatTranslator,\n ReadOnlyFileSystem,\n WebDavFileSystem,\n XmlLimitError,\n assertPathWithin,\n basename,\n collectBytes,\n compareEntries,\n createDeviceFileSystem,\n createFsBridge,\n createMemoryFileSystem,\n createMountFileSystem,\n createOverlayFileSystem,\n createReadOnlyFileSystem,\n defaultMemoryFileSystemLimits,\n dirname,\n extname,\n isAbsolutePath,\n isErrnoCode,\n isFsError,\n isPathWithin,\n joinPath,\n mountPythonFileSystem,\n normalizePath,\n openFileDescriptor,\n parseXml,\n parseXmlSteps,\n posixPath,\n readBytes,\n relativePath,\n resolvePath,\n retainFileSystemCleanup,\n scopeFileSystem,\n toByteSource,\n toFsError,\n translatePythonOpenFlags,\n validatePath,\n withFileSystemQuota\n} from \"./chunks/chunk-VUCZTCHV.js\";\nexport {\n ACCESS_MODES,\n DeviceFileSystem,\n FileSystemQuotaError,\n FsError,\n MemoryFileSystem,\n MountFileSystem,\n OverlayFileSystem,\n PythonFileSystem,\n PythonStatTranslator,\n ReadOnlyFileSystem,\n WebDavFileSystem,\n XmlLimitError,\n assertPathWithin,\n basename,\n collectBytes,\n compareEntries,\n createDeviceFileSystem,\n createFsBridge,\n createMemoryFileSystem,\n createMountFileSystem,\n createOverlayFileSystem,\n createReadOnlyFileSystem,\n defaultMemoryFileSystemLimits,\n dirname,\n extname,\n isAbsolutePath,\n isErrnoCode,\n isFsError,\n isPathWithin,\n joinPath,\n mountPythonFileSystem,\n normalizePath,\n openFileDescriptor,\n parseXml,\n parseXmlSteps,\n posixPath,\n readBytes,\n relativePath,\n resolvePath,\n retainFileSystemCleanup,\n scopeFileSystem,\n toByteSource,\n toFsError,\n translatePythonOpenFlags,\n validatePath,\n withFileSystemQuota\n};\n//# sourceMappingURL=safe-fs.js.map\n", "import { FsError } from \"../contracts/errors.js\";\nimport type { FsOptions } from \"../contracts/filesystem.js\";\n\nexport type PlatformErrno = number | undefined;\nexport type PlatformComparisonCallback<Callback> = Callback & never;\n\nexport const platform = Object.freeze({\n errno(_code: string): PlatformErrno {\n return undefined;\n },\n callbackAuthorities: false,\n randomUUID(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto?.randomUUID === \"function\") return crypto.randomUUID();\n if (typeof crypto?.getRandomValues !== \"function\") {\n throw new FsError(\"ENOTSUP\", { message: \"secure crypto is required for overlay staging\" });\n }\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n }\n});\n\nconst operationKey = Symbol(\"filesystem-comparison\");\nconst contexts = new WeakSet<object>();\ntype OperationOptions = FsOptions & { readonly [operationKey]?: object };\n\nexport const comparisonContext = Object.freeze({\n active(options: FsOptions): boolean {\n const context = (options as OperationOptions)[operationKey];\n return context !== undefined && contexts.has(context);\n },\n async run<Result>(options: FsOptions, action: (nested: FsOptions) => Promise<Result>): Promise<Result> {\n const context = Object.freeze({});\n contexts.add(context);\n const nested: OperationOptions = { ...options, [operationKey]: context };\n try {\n return await action(nested);\n } finally {\n contexts.delete(context);\n }\n }\n});\n", "import { platform } from \"#safe-fs-platform\";\nimport type { PlatformErrno } from \"#safe-fs-platform\";\nexport type { PlatformErrno } from \"#safe-fs-platform\";\n\nconst descriptions = {\n EACCES: \"permission denied\",\n EAGAIN: \"resource temporarily unavailable\",\n EBADF: \"bad file descriptor\",\n EBUSY: \"resource busy or locked\",\n ECANCELED: \"operation canceled\",\n EEXIST: \"file already exists\",\n EFBIG: \"file too large\",\n EINTR: \"interrupted system call\",\n EINVAL: \"invalid argument\",\n EIO: \"input/output error\",\n EISDIR: \"illegal operation on a directory\",\n ELOOP: \"too many symbolic links encountered\",\n EMFILE: \"too many open files\",\n ENAMETOOLONG: \"name too long\",\n ENFILE: \"file table overflow\",\n ENOENT: \"no such file or directory\",\n ENOMEM: \"not enough memory\",\n ENOSPC: \"no space left on device\",\n ENOSYS: \"function not implemented\",\n ENOTDIR: \"not a directory\",\n ENOTEMPTY: \"directory not empty\",\n ENOTSUP: \"operation not supported\",\n EOPNOTSUPP: \"operation not supported\",\n EPERM: \"operation not permitted\",\n EPIPE: \"broken pipe\",\n EROFS: \"read-only file system\",\n ESPIPE: \"illegal seek\",\n ETIMEDOUT: \"operation timed out\",\n EXDEV: \"cross-device link not permitted\",\n} as const;\n\nexport type ErrnoCode = keyof typeof descriptions;\n\nexport interface FsErrorOptions extends ErrorOptions {\n readonly syscall?: string;\n readonly path?: string;\n readonly dest?: string;\n readonly message?: string;\n}\n\nexport class FsError extends Error {\n readonly code: ErrnoCode;\n readonly errno: PlatformErrno;\n readonly syscall?: string;\n readonly path?: string;\n readonly dest?: string;\n\n constructor(code: ErrnoCode, options: FsErrorOptions = {}) {\n if (!isErrnoCode(code)) throw new TypeError(`Unsupported errno code: ${String(code)}`);\n const errno = platform.errno(code);\n const operation = options.syscall ? `, ${options.syscall}` : \"\";\n const path = options.path === undefined ? \"\" : ` '${options.path}'`;\n const destination = options.dest === undefined ? \"\" : ` -> '${options.dest}'`;\n super(`${code}: ${options.message ?? descriptions[code]}${operation}${path}${destination}`, options);\n this.name = \"FsError\";\n this.code = code;\n this.errno = errno;\n if (options.syscall !== undefined) this.syscall = options.syscall;\n if (options.path !== undefined) this.path = options.path;\n if (options.dest !== undefined) this.dest = options.dest;\n }\n}\n\nexport function isErrnoCode(code: unknown): code is ErrnoCode {\n return typeof code === \"string\" && Object.hasOwn(descriptions, code);\n}\n\nexport function isFsError(error: unknown, code?: ErrnoCode): error is FsError {\n return error instanceof FsError && (code === undefined || error.code === code);\n}\n\nexport function toFsError(error: unknown, options: FsErrorOptions = {}): FsError {\n if (error instanceof FsError && Object.keys(options).length === 0) return error;\n const source = typeof error === \"object\" && error !== null\n ? error as Record<string, unknown>\n : {};\n const details: FsErrorOptions = {\n ...(typeof source.syscall === \"string\" ? { syscall: source.syscall } : {}),\n ...(typeof source.path === \"string\" ? { path: source.path } : {}),\n ...(typeof source.dest === \"string\" ? { dest: source.dest } : {}),\n cause: error,\n ...options,\n };\n return new FsError(isErrnoCode(source.code) ? source.code : \"EIO\", details);\n}\n", "import type { ByteSource } from \"./io.js\";\nimport type { FileDescriptor, OpenFileOptions } from \"./descriptor.js\";\n\nexport type { FileDescriptor, FileDescriptorCapabilities, OpenFileOptions } from \"./descriptor.js\";\n\nexport type FileType = \"file\" | \"directory\" | \"symlink\" | \"character\";\nexport type EntryComparison = \"same\" | \"distinct\" | \"unknown\";\n\nexport interface FileStat {\n readonly type: FileType;\n readonly size: number;\n readonly allocatedBytes?: number;\n readonly ioBlockSize?: number;\n readonly preferredIoBlockSize?: number;\n readonly mode: number;\n readonly mtimeMs: number;\n readonly atimeMs: number;\n readonly ctimeMs: number;\n readonly birthtimeMs?: number;\n readonly revision?: number;\n readonly identityScope?: object | symbol;\n readonly ino?: number;\n readonly dev?: number;\n readonly rdevMajor?: number;\n readonly rdevMinor?: number;\n readonly nlink?: number;\n readonly uid?: number;\n readonly gid?: number;\n}\n\nexport interface DirectoryEntry {\n readonly name: string;\n readonly type: FileType;\n}\n\nexport interface FileSystemCapabilities {\n readonly open?: boolean;\n readonly readOnly?: boolean;\n readonly read?: boolean;\n readonly stat?: boolean;\n readonly readdir?: boolean;\n readonly realpath?: boolean;\n readonly access?: boolean;\n readonly write?: boolean;\n readonly append?: boolean;\n readonly exclusiveCreate?: boolean;\n readonly explicitDirectories?: boolean;\n readonly implicitDirectories?: boolean;\n readonly mkdir?: boolean;\n readonly recursiveMkdir?: boolean;\n readonly remove?: boolean;\n readonly removeDirectory?: boolean;\n readonly recursiveRemove?: boolean;\n readonly rename?: boolean;\n readonly copy?: boolean;\n readonly exclusiveCopy?: boolean;\n readonly readlink?: boolean;\n readonly truncate?: boolean;\n readonly streamingAppend?: boolean;\n readonly randomAccessWrite?: boolean;\n readonly independentWriteStreams?: boolean;\n readonly symlinks?: boolean;\n readonly hardlinks?: boolean;\n readonly permissions?: boolean;\n readonly timestamps?: boolean;\n readonly atomicRename?: boolean;\n readonly atomicFileStaging?: boolean;\n readonly atomicFileMutation?: boolean;\n readonly atomicEntryRemoval?: boolean;\n readonly atomicTreeRemoval?: boolean;\n readonly atomicDirectoryMetadata?: boolean;\n readonly atomicRenameNoReplace?: boolean;\n readonly snapshotRmdir?: boolean;\n readonly streamingRead?: boolean;\n readonly retainedRead?: boolean;\n readonly retainedResize?: boolean;\n readonly atomicResize?: boolean;\n readonly streamingWrite?: boolean;\n readonly descriptorWriteStream?: boolean;\n readonly [capability: string]: boolean | undefined;\n}\n\nexport interface FsOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface OpenReadFileOptions extends FsOptions {\n readonly allowDirectory?: boolean;\n}\n\nexport interface CapabilityQueryOptions extends OpenReadFileOptions {\n readonly create?: boolean;\n}\n\nexport interface FileReadHandle {\n stat(options?: FsOptions): Promise<FileStat>;\n read(position: number, maxBytes: number, options?: FsOptions): Promise<Uint8Array>;\n seekEnd?: ((options?: FsOptions) => Promise<bigint>) | undefined;\n close(): Promise<void>;\n}\n\nexport interface OpenResizeFileOptions extends FsOptions {\n readonly create?: boolean;\n readonly mode?: number;\n}\n\n/** A single atomic read/compute/resize operation, never a caller-side stat/write pair.\n * size and referenceSize use signed 64-bit byte integers (referenceSize is nonnegative).\n * ioBlocks scales size by the target's preferred I/O block size before applying the\n * modifier. Relative/min/max/round operations use referenceSize or the current size.\n * Signed overflow rejects; negative final sizes clamp to zero. Providers enforce\n * their size/quota/permission limits before allocation or publication. */\nexport interface FileResizeOperation {\n readonly size: bigint;\n readonly modifier: \"absolute\" | \"relative\" | \"minimum\" | \"maximum\" | \"down\" | \"up\";\n readonly referenceSize?: bigint;\n readonly ioBlocks?: boolean;\n}\n\nexport interface FileResizeOptions extends FsOptions {\n readonly create?: boolean;\n readonly mode?: number;\n}\n\nexport interface FileResizeHandle {\n stat(options?: FsOptions): Promise<FileStat>;\n truncate(length: number, options?: FsOptions): Promise<void>;\n seekEnd?: ((options?: FsOptions) => Promise<bigint>) | undefined;\n close(): Promise<void>;\n}\n\nexport interface RenameOptions extends FsOptions {\n readonly noReplace?: boolean;\n}\n\nexport interface ReadFileOptions extends FsOptions {\n readonly maxBytes?: number;\n}\n\nexport interface ReadDirectoryOptions extends FsOptions {\n /**\n * Optional per-listing entry admission limit, a nonnegative safe integer.\n * Zero permits an empty listing; overflow rejects with EFBIG, never truncates.\n * Omission preserves the adapter's existing limits and ordering. Composed\n * adapters may conservatively count distinct candidates before visibility\n * filtering. This is not a global traversal, host-allocation or work quota.\n */\n readonly maxEntries?: number;\n}\n\nexport interface WriteFileOptions extends FsOptions {\n readonly flag?: \"w\" | \"wx\" | \"a\" | \"ax\";\n readonly mode?: number;\n}\n\nexport interface AppendFileOptions extends FsOptions {\n readonly mode?: number;\n}\n\nexport interface MkdirOptions extends FsOptions {\n readonly recursive?: boolean;\n readonly mode?: number;\n}\n\nexport interface RemoveOptions extends FsOptions {\n readonly recursive?: boolean;\n readonly force?: boolean;\n}\n\nexport interface CopyFileOptions extends FsOptions {\n readonly exclusive?: boolean;\n}\n\nexport interface ReadStreamOptions extends FsOptions {\n readonly start?: number;\n readonly endExclusive?: number;\n readonly chunkSize?: number;\n}\n\nexport interface ConditionalWriteFileOptions extends FsOptions {\n readonly parent: FileStat;\n readonly expected: FileStat | null;\n readonly append?: boolean;\n readonly mode?: number;\n}\n\nexport interface ConditionalRemoveEntryOptions extends FsOptions {\n readonly parent: FileStat;\n readonly expected: FileStat;\n}\n\nexport type ConditionalRemoveFileOptions = ConditionalRemoveEntryOptions;\n\nexport interface FileStagingEntry {\n readonly path: string;\n readonly stat: FileStat;\n}\n\nexport interface FileStaging {\n readonly parent: FileStagingEntry;\n readonly directory: FileStagingEntry;\n readonly file: FileStagingEntry;\n}\n\nexport type StagedFileContent =\n | { readonly type: \"file\"; readonly data: Uint8Array }\n | { readonly type: \"symlink\"; readonly target: string };\n\nexport interface CreateStagedFileOptions extends FsOptions {\n readonly parent: FileStat;\n readonly mode?: number;\n readonly atimeMs?: number;\n readonly mtimeMs?: number;\n}\n\nexport interface PublishStagedFileOptions extends FsOptions {\n readonly parent: FileStat;\n readonly destination: FileStat | null;\n}\n\nexport interface PrepareDirectoryOptions extends FsOptions {\n readonly expected: FileStat | null;\n readonly parent: FileStat;\n readonly mode?: number;\n readonly atimeMs?: number;\n readonly mtimeMs?: number;\n}\n\nexport interface FileSystem {\n writeFileConditional?(path: string, data: Uint8Array, options: ConditionalWriteFileOptions): Promise<FileStat>;\n removeEntryConditional?(path: string, options: ConditionalRemoveEntryOptions): Promise<void>;\n removeTreeConditional?(path: string, options: ConditionalRemoveEntryOptions): Promise<void>;\n removeFileConditional?(path: string, options: ConditionalRemoveFileOptions): Promise<void>;\n readonly capabilities: FileSystemCapabilities;\n open?(path: string, options: OpenFileOptions): Promise<FileDescriptor>;\n prepareDirectory?(path: string, options: PrepareDirectoryOptions): Promise<FileStat>;\n createStagedFile?(directoryPath: string, name: string, content: StagedFileContent, options: CreateStagedFileOptions): Promise<FileStaging>;\n publishStagedFile?(staging: FileStaging, destination: string, options: PublishStagedFileOptions): Promise<void>;\n removeStagedFile?(staging: FileStaging, options?: FsOptions): Promise<void>;\n openReadFile?(path: string, options?: OpenReadFileOptions): Promise<FileReadHandle>;\n openResizeFile?(path: string, options?: OpenResizeFileOptions): Promise<FileResizeHandle>;\n /** Missing targets reject ENOENT unless create is true; existing bytes survive refusals. */\n resizeFile?(path: string, operation: FileResizeOperation, options?: FileResizeOptions): Promise<void>;\n canonicalizeMissingTarget?(path: string, options?: FsOptions): string | undefined;\n capabilitiesFor?(path: string, options?: CapabilityQueryOptions): Promise<FileSystemCapabilities>;\n readFile(path: string, options?: ReadFileOptions): Promise<Uint8Array>;\n writeFile(path: string, data: Uint8Array, options?: WriteFileOptions): Promise<void>;\n appendFile(path: string, data: Uint8Array, options?: AppendFileOptions): Promise<void>;\n stat(path: string, options?: FsOptions): Promise<FileStat>;\n lstat(path: string, options?: FsOptions): Promise<FileStat>;\n compareEntry?(path: string, peer: FileSystem, peerPath: string, options?: FsOptions): Promise<EntryComparison>;\n readdir(path: string, options?: ReadDirectoryOptions): Promise<DirectoryEntry[]>;\n mkdir(path: string, options?: MkdirOptions): Promise<void>;\n rm(path: string, options?: RemoveOptions): Promise<void>;\n /** Atomic final-entry removal; every directory is refused, including raced replacements. */\n unlink?(path: string, options?: FsOptions): Promise<void>;\n rmdir?(path: string, options?: FsOptions): Promise<void>;\n rename(source: string, destination: string, options?: RenameOptions): Promise<void>;\n copyFile(source: string, destination: string, options?: CopyFileOptions): Promise<void>;\n realpath(path: string, options?: FsOptions): Promise<string>;\n access(path: string, mode?: number, options?: FsOptions): Promise<void>;\n readlink?(path: string, options?: FsOptions): Promise<string>;\n symlink?(target: string, path: string, options?: FsOptions): Promise<void>;\n link?(existingPath: string, newPath: string, options?: FsOptions): Promise<void>;\n chmod?(path: string, mode: number, options?: FsOptions): Promise<void>;\n utimes?(path: string, atimeMs: number, mtimeMs: number, options?: FsOptions): Promise<void>;\n truncate?(path: string, length?: number, options?: FsOptions): Promise<void>;\n readStream?(path: string, options?: ReadStreamOptions): ByteSource;\n writeStream?(path: string, source: ByteSource, options?: WriteFileOptions): Promise<void>;\n}\n\nexport type FileSystemFactory = (\n options: Readonly<Record<string, unknown>>,\n) => FileSystem | Promise<FileSystem>;\n\nexport const ACCESS_MODES = Object.freeze({ F_OK: 0, R_OK: 4, W_OK: 2, X_OK: 1 });\n", "export async function finishCleanup(cleanup: () => unknown, failed: boolean): Promise<void> {\n try {\n await cleanup();\n } catch (error) {\n if (!failed) throw error;\n }\n}\n", "import { FsError } from \"./errors.js\";\nimport { finishCleanup } from \"./cleanup.js\";\n\nexport type ByteSource = AsyncIterable<Uint8Array>;\n\nexport interface CollectOptions {\n readonly maxBytes: number;\n readonly signal?: AbortSignal;\n}\n\nexport function toByteSource(input: string | Uint8Array): ByteSource {\n if (typeof input !== \"string\" && !(input instanceof Uint8Array)) {\n throw new TypeError(\"Byte source input must be a string or Uint8Array\");\n }\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : new Uint8Array(input);\n return (async function* () {\n if (bytes.byteLength > 0) yield bytes;\n })();\n}\n\nexport async function collectBytes(source: ByteSource, options: CollectOptions): Promise<Uint8Array> {\n if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 0) {\n throw new RangeError(\"maxBytes must be a nonnegative safe integer\");\n }\n const chunks: Uint8Array[] = [];\n let size = 0;\n options.signal?.throwIfAborted();\n for await (const chunk of readBytes(source, options.signal)) {\n if (chunk.byteLength > options.maxBytes - size) {\n throw new FsError(\"EFBIG\", { syscall: \"collectBytes\", message: \"output exceeds maxBytes\" });\n }\n if (chunk.byteLength > 0) chunks.push(new Uint8Array(chunk));\n size += chunk.byteLength;\n }\n options.signal?.throwIfAborted();\n const result = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result;\n}\n\nasync function abortable<Result>(operation: () => PromiseLike<Result>, signal?: AbortSignal): Promise<Result> {\n signal?.throwIfAborted();\n if (!signal) return operation();\n return new Promise<Result>((resolve, reject) => {\n const onAbort = (): void => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(signal.reason);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n Promise.resolve(operation()).then(\n (result) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(result);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n },\n );\n } catch (error) {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n }\n });\n}\n\nexport async function* readBytes(source: ByteSource, signal?: AbortSignal): AsyncGenerator<Uint8Array> {\n signal?.throwIfAborted();\n const iterator = source[Symbol.asyncIterator]();\n let finished = false;\n let failed = false;\n try {\n while (true) {\n const result = await abortable(() => iterator.next(), signal);\n if (result.done) {\n finished = true;\n return;\n }\n if (!(result.value instanceof Uint8Array)) throw new TypeError(\"Byte sources must yield Uint8Array chunks\");\n yield result.value;\n }\n } catch (error) {\n failed = true;\n throw error;\n } finally {\n if (!finished && iterator.return) {\n const cleanup = Promise.resolve().then(() => iterator.return!());\n if (signal?.aborted) void cleanup.catch(() => {});\n else await finishCleanup(() => abortable(() => cleanup, signal), failed);\n }\n }\n}\n", "import { FsError } from \"../contracts/errors.js\";\nimport { finishCleanup } from \"../contracts/cleanup.js\";\nimport type { FileDescriptor, FileDescriptorCapabilities, FileStat, FsOptions, OpenFileOptions } from \"../contracts/filesystem.js\";\n\nexport interface DescriptorOpenOptions extends OpenFileOptions {\n readonly creation: \"never\" | \"ifMissing\" | \"exclusive\";\n readonly truncate: boolean;\n readonly append: boolean;\n readonly mode: number;\n}\n\nexport interface DescriptorBackend<Resource> {\n readonly resource: Resource;\n readonly capabilities?: FileDescriptorCapabilities;\n getPosition?(resource: Resource, options: FsOptions): Promise<number>;\n probeRead?(resource: Resource, options: FsOptions): Promise<\"ready\" | \"blocked\" | \"unknown\">;\n stat(resource: Resource, options: FsOptions): Promise<FileStat>;\n read(resource: Resource, buffer: Uint8Array, position: number | null, options: FsOptions): Promise<number>;\n write(resource: Resource, buffer: Uint8Array, position: number | null, options: FsOptions): Promise<number>;\n truncate(resource: Resource, length: number, options: FsOptions): Promise<void>;\n sync(resource: Resource, dataOnly: boolean, options: FsOptions): Promise<void>;\n close(resource: Resource): Promise<void>;\n}\n\nfunction admitCapabilities(path: string, options: OpenFileOptions, capabilities: FileDescriptorCapabilities): void {\n if (![capabilities.positionedRead, capabilities.positionedWrite, capabilities.truncate].every(value => typeof value === \"boolean\")\n || capabilities.position !== undefined && typeof capabilities.position !== \"boolean\"\n || capabilities.readObservation !== undefined && typeof capabilities.readObservation !== \"boolean\"\n || capabilities.openTruncate !== undefined && typeof capabilities.openTruncate !== \"boolean\"\n || capabilities.positionedAppendWrite !== undefined && typeof capabilities.positionedAppendWrite !== \"boolean\"\n || capabilities.delegateZeroLengthWrite !== undefined && typeof capabilities.delegateZeroLengthWrite !== \"boolean\"\n || ![\"none\", \"volatile\", \"storage\"].includes(capabilities.synchronization)) throw new FsError(\"EINVAL\", { syscall: \"open\", path });\n if (options.truncate && !(capabilities.openTruncate ?? capabilities.truncate) || options.synchronization !== undefined && capabilities.synchronization === \"none\") {\n throw new FsError(\"ENOTSUP\", { syscall: \"open\", path });\n }\n}\n\nexport function forwardFileDescriptor(descriptor: FileDescriptor,\n operation: <Result>(syscall: string, options: FsOptions, action: () => Promise<Result>) => Promise<Result>,\n capabilities?: FileDescriptorCapabilities,\n snapshot: (stat: FileStat) => FileStat = stat => ({ ...stat })): DescriptorBackend<FileDescriptor> {\n const retainedCapabilities = Object.freeze({ ...descriptor.capabilities });\n const selected = Object.freeze({ ...(capabilities ?? retainedCapabilities) });\n const getPosition = selected.position === true && retainedCapabilities.position === true ? descriptor.getPosition : undefined;\n if (selected.position === true && typeof getPosition !== \"function\") throw new FsError(\"ENOTSUP\", { syscall: \"getPosition\" });\n const probeRead = selected.readObservation === true && retainedCapabilities.readObservation === true ? descriptor.probeRead : undefined;\n if (selected.readObservation === true && typeof probeRead !== \"function\") throw new FsError(\"ENOTSUP\", { syscall: \"probeRead\" });\n return {\n resource: descriptor, capabilities: selected,\n ...(getPosition === undefined ? {} : {\n getPosition: (retained: FileDescriptor, options: FsOptions) => operation(\"getPosition\", options, () => getPosition.call(retained, options)),\n }),\n ...(probeRead === undefined ? {} : {\n probeRead: (retained: FileDescriptor, options: FsOptions) => operation(\"probeRead\", options, () => probeRead.call(retained, options)),\n }),\n stat: (retained, options) => operation(\"fstat\", options, async () => snapshot(await retained.stat(options))),\n read: (retained, buffer, position, options) => operation(\"read\", options, () => retained.read(buffer, position, options)),\n write: (retained, buffer, position, options) => operation(\"write\", options, () => retained.write(buffer, position, options)),\n truncate: (retained, length, options) => operation(\"ftruncate\", options, () => retained.truncate(length, options)),\n sync: (retained, dataOnly, options) => operation(dataOnly ? \"fdatasync\" : \"fsync\", options, () => retained.sync(dataOnly, options)),\n close: retained => operation(\"close\", {}, () => retained.close()),\n };\n}\n\nfunction integer(value: number, syscall: string, path: string): void {\n if (!Number.isSafeInteger(value) || value < 0) throw new FsError(\"EINVAL\", { syscall, path });\n}\n\nclass ManagedFileDescriptor<Resource> implements FileDescriptor {\n readonly capabilities: FileDescriptorCapabilities;\n readonly #path: string;\n readonly #access: OpenFileOptions[\"access\"];\n readonly #append: boolean;\n #getPosition: DescriptorBackend<Resource>[\"getPosition\"];\n #probeRead: DescriptorBackend<Resource>[\"probeRead\"];\n #backend: DescriptorBackend<Resource> | undefined;\n #pending: Promise<void> = Promise.resolve();\n #closing: Promise<void> | undefined;\n\n constructor(path: string, options: DescriptorOpenOptions, capabilities: FileDescriptorCapabilities, backend: DescriptorBackend<Resource>) {\n this.#path = path;\n this.#access = options.access;\n this.#append = options.append;\n const getPosition = capabilities.position === true ? backend.getPosition : undefined;\n if (capabilities.position === true && typeof getPosition !== \"function\") throw new FsError(\"ENOTSUP\", { syscall: \"getPosition\", path });\n this.#getPosition = getPosition?.bind(backend);\n const probeRead = capabilities.readObservation === true ? backend.probeRead : undefined;\n if (capabilities.readObservation === true && typeof probeRead !== \"function\") throw new FsError(\"ENOTSUP\", { syscall: \"probeRead\", path });\n this.#probeRead = probeRead?.bind(backend);\n this.#backend = backend;\n const positionedAppendWrite = capabilities.positionedAppendWrite === true && capabilities.positionedWrite && options.access !== \"read\";\n this.capabilities = Object.freeze({\n ...(capabilities.position === undefined ? {} : { position: capabilities.position }),\n ...(capabilities.readObservation === undefined ? {} : { readObservation: capabilities.readObservation }),\n ...(capabilities.openTruncate === undefined ? {} : { openTruncate: capabilities.openTruncate }),\n positionedRead: capabilities.positionedRead && options.access !== \"write\",\n positionedWrite: capabilities.positionedWrite && options.access !== \"read\" && (!options.append || positionedAppendWrite),\n ...(capabilities.positionedAppendWrite === undefined ? {} : { positionedAppendWrite }),\n ...(capabilities.delegateZeroLengthWrite === undefined ? {} : { delegateZeroLengthWrite: capabilities.delegateZeroLengthWrite && options.access !== \"read\" }),\n truncate: capabilities.truncate && options.access !== \"read\",\n synchronization: capabilities.synchronization,\n });\n }\n\n #run<Result>(syscall: string, options: FsOptions,\n action: (backend: DescriptorBackend<Resource>, options: FsOptions) => Promise<Result>): Promise<Result> {\n const signal = options.signal;\n try {\n signal?.throwIfAborted();\n if (this.#closing || !this.#backend) throw new FsError(\"EBADF\", { syscall, path: this.#path });\n } catch (error) { return Promise.reject(error); }\n const forwarded = signal === undefined ? {} : { signal };\n const operation = this.#pending.then(async () => {\n signal?.throwIfAborted();\n try {\n const result = await action(this.#backend!, forwarded);\n signal?.throwIfAborted();\n return result;\n } catch (error) {\n signal?.throwIfAborted();\n throw error;\n }\n });\n this.#pending = operation.then(() => {}, () => {});\n return operation;\n }\n\n #position(buffer: Uint8Array, position: number | null, syscall: \"read\" | \"write\"): void {\n if (!(buffer instanceof Uint8Array)) throw new FsError(\"EINVAL\", { syscall, path: this.#path });\n if (position !== null) {\n integer(position, syscall, this.#path);\n if (syscall === \"write\" && this.#append && this.capabilities.positionedAppendWrite !== true) throw new FsError(\"EINVAL\", { syscall, path: this.#path });\n if (!(syscall === \"read\" ? this.capabilities.positionedRead : this.capabilities.positionedWrite)) {\n throw new FsError(\"ESPIPE\", { syscall, path: this.#path });\n }\n }\n }\n\n stat(options: FsOptions = {}): Promise<FileStat> {\n return this.#run(\"fstat\", options, (backend, forwarded) => backend.stat(backend.resource, forwarded));\n }\n\n getPosition(options: FsOptions = {}): Promise<number> {\n return this.#run(\"getPosition\", options, async (backend, forwarded) => {\n if (!this.capabilities.position || !this.#getPosition) throw new FsError(\"ENOTSUP\", { syscall: \"getPosition\", path: this.#path });\n const position = await this.#getPosition(backend.resource, forwarded);\n if (!Number.isSafeInteger(position) || position < 0) throw new FsError(\"EIO\", { syscall: \"getPosition\", path: this.#path });\n return position;\n });\n }\n\n probeRead(options: FsOptions = {}): Promise<\"ready\" | \"blocked\" | \"unknown\"> {\n return this.#run(\"probeRead\", options, async (backend, forwarded) => {\n if (!this.capabilities.readObservation || !this.#probeRead) throw new FsError(\"ENOTSUP\", { syscall: \"probeRead\", path: this.#path });\n const readiness = await this.#probeRead(backend.resource, forwarded);\n if (readiness !== \"ready\" && readiness !== \"blocked\" && readiness !== \"unknown\") throw new FsError(\"EIO\", { syscall: \"probeRead\", path: this.#path });\n return readiness;\n });\n }\n\n read(buffer: Uint8Array, position: number | null, options: FsOptions = {}): Promise<number> {\n return this.#run(\"read\", options, async (backend, forwarded) => {\n if (this.#access === \"write\") throw new FsError(\"EBADF\", { syscall: \"read\", path: this.#path });\n this.#position(buffer, position, \"read\");\n if (buffer.byteLength === 0) return 0;\n const count = await backend.read(backend.resource, buffer, position, forwarded);\n if (!Number.isSafeInteger(count) || count < 0 || count > buffer.byteLength) throw new FsError(\"EIO\", { syscall: \"read\", path: this.#path });\n return count;\n });\n }\n\n write(buffer: Uint8Array, position: number | null, options: FsOptions = {}): Promise<number> {\n return this.#run(\"write\", options, async (backend, forwarded) => {\n if (this.#access === \"read\") throw new FsError(\"EBADF\", { syscall: \"write\", path: this.#path });\n this.#position(buffer, position, \"write\");\n if (buffer.byteLength === 0 && this.capabilities.delegateZeroLengthWrite !== true) return 0;\n const count = await backend.write(backend.resource, buffer, position, forwarded);\n if (!Number.isSafeInteger(count) || count < 0 || count > buffer.byteLength) throw new FsError(\"EIO\", { syscall: \"write\", path: this.#path });\n return count;\n });\n }\n\n truncate(length: number, options: FsOptions = {}): Promise<void> {\n return this.#run(\"ftruncate\", options, async (backend, forwarded) => {\n if (this.#access === \"read\") throw new FsError(\"EBADF\", { syscall: \"ftruncate\", path: this.#path });\n integer(length, \"ftruncate\", this.#path);\n if (!this.capabilities.truncate) throw new FsError(\"ENOTSUP\", { syscall: \"ftruncate\", path: this.#path });\n await backend.truncate(backend.resource, length, forwarded);\n });\n }\n\n sync(dataOnly: boolean, options: FsOptions = {}): Promise<void> {\n return this.#run(dataOnly ? \"fdatasync\" : \"fsync\", options, async (backend, forwarded) => {\n if (typeof dataOnly !== \"boolean\") throw new FsError(\"EINVAL\", { syscall: \"fsync\", path: this.#path });\n if (this.capabilities.synchronization === \"none\") throw new FsError(\"ENOTSUP\", { syscall: dataOnly ? \"fdatasync\" : \"fsync\", path: this.#path });\n await backend.sync(backend.resource, dataOnly, forwarded);\n });\n }\n\n close(): Promise<void> {\n this.#closing ??= this.#pending.then(async () => {\n try { await this.#backend!.close(this.#backend!.resource); }\n finally {\n this.#backend = undefined;\n this.#getPosition = undefined;\n this.#probeRead = undefined;\n this.#pending = Promise.resolve();\n }\n });\n return this.#closing;\n }\n}\n\nexport async function openFileDescriptor<Resource>(path: string, options: OpenFileOptions,\n capabilities: FileDescriptorCapabilities,\n acquire: (options: DescriptorOpenOptions) => Promise<DescriptorBackend<Resource>>): Promise<FileDescriptor> {\n if (!options || typeof options !== \"object\") throw new FsError(\"EINVAL\", { syscall: \"open\", path });\n const signal = options.signal;\n signal?.throwIfAborted();\n const keys = [\"access\", \"creation\", \"truncate\", \"append\", \"mode\", \"synchronization\", \"signal\"];\n const { access, creation = \"never\", truncate = false, append = false, mode = 0o666, synchronization } = options;\n if (Object.keys(options).some(key => !keys.includes(key))\n || ![\"read\", \"write\", \"readwrite\"].includes(access)\n || ![\"never\", \"ifMissing\", \"exclusive\"].includes(creation)\n || typeof truncate !== \"boolean\" || typeof append !== \"boolean\"\n || access === \"read\" && (truncate || append)\n || synchronization !== undefined && ![\"data\", \"all\"].includes(synchronization)\n || !Number.isSafeInteger(mode) || mode < 0 || mode > 0o7777) {\n throw new FsError(\"EINVAL\", { syscall: \"open\", path });\n }\n const admitted: DescriptorOpenOptions = Object.freeze({ access, creation, truncate, append, mode,\n ...(signal === undefined ? {} : { signal }), ...(synchronization === undefined ? {} : { synchronization }) });\n const admittedCapabilities = Object.freeze({ ...capabilities });\n admitCapabilities(path, admitted, admittedCapabilities);\n let backend: DescriptorBackend<Resource>;\n try { backend = await acquire(admitted); }\n catch (error) { signal?.throwIfAborted(); throw error; }\n try {\n signal?.throwIfAborted();\n const selected = Object.freeze({ ...(backend.capabilities ?? admittedCapabilities) });\n signal?.throwIfAborted();\n admitCapabilities(path, admitted, selected);\n const descriptor = new ManagedFileDescriptor(path, admitted, selected, backend);\n signal?.throwIfAborted();\n return descriptor;\n } catch (error) {\n await finishCleanup(() => backend.close(backend.resource), true);\n signal?.throwIfAborted();\n throw error;\n }\n}\n", "import { FsError } from \"./errors.js\";\n\nexport function validatePath(path: string): void {\n if (typeof path !== \"string\" || path.includes(\"\\0\")) {\n throw new FsError(\"EINVAL\", { syscall: \"resolve\", message: \"paths must be strings without NUL bytes\" });\n }\n}\n\nexport function resolvePath(cwd: string, ...paths: string[]): string {\n validatePath(cwd);\n if (!cwd.startsWith(\"/\")) throw new FsError(\"EINVAL\", { syscall: \"resolve\", path: cwd, message: \"cwd must be absolute\" });\n for (const path of paths) validatePath(path);\n const components: string[] = [];\n for (const path of [cwd, ...paths]) {\n if (path.startsWith(\"/\")) components.length = 0;\n for (const component of path.split(\"/\")) {\n if (component === \"\" || component === \".\") continue;\n if (component === \"..\") components.pop();\n else components.push(component);\n }\n }\n return `/${components.join(\"/\")}`;\n}\n\nexport function normalizePath(path: string, cwd = \"/\"): string {\n return resolvePath(cwd, path);\n}\n\nexport function dirname(path: string): string {\n if (typeof path !== \"string\") throw new TypeError(\"path must be a string\");\n let end = path.length;\n while (end > 0 && path[end - 1] === \"/\") end--;\n if (end === 0) return path.startsWith(\"/\") ? \"/\" : \".\";\n const boundary = path.lastIndexOf(\"/\", end - 1);\n if (boundary < 0) return \".\";\n if (boundary === 0) return \"/\";\n if (boundary === 1 && path.startsWith(\"/\")) return \"//\";\n return path.slice(0, boundary);\n}\n\nexport function relativePath(from: string, to: string): string {\n const source = normalizePath(from).split(\"/\").filter(Boolean);\n const target = normalizePath(to).split(\"/\").filter(Boolean);\n let common = 0;\n while (common < source.length && common < target.length && source[common] === target[common]) common++;\n return [...Array<string>(source.length - common).fill(\"..\"), ...target.slice(common)].join(\"/\");\n}\n\nexport function isPathWithin(root: string, path: string): boolean {\n const normalizedRoot = normalizePath(root);\n const normalizedPath = normalizePath(path);\n return normalizedRoot === \"/\" || normalizedPath === normalizedRoot || normalizedPath.startsWith(`${normalizedRoot}/`);\n}\n\nexport function assertPathWithin(root: string, path: string): string {\n const normalizedPath = normalizePath(path);\n if (!isPathWithin(root, normalizedPath)) throw new FsError(\"EACCES\", { syscall: \"resolve\", path, message: \"path escapes the allowed root\" });\n return normalizedPath;\n}\n", "import { dirname as virtualDirname } from \"./virtual-path.js\";\n\nfunction assertString(value: unknown): asserts value is string {\n if (typeof value !== \"string\") throw new TypeError(\"path must be a string\");\n}\n\nexport function basename(path: string, suffix = \"\"): string {\n assertString(path);\n assertString(suffix);\n if (suffix && path === suffix) return \"\";\n let end = path.length;\n while (end > 0 && path[end - 1] === \"/\") end--;\n if (end === 0 && suffix && suffix.length <= path.length) return path;\n const start = path.lastIndexOf(\"/\", end - 1) + 1;\n const base = path.slice(start, end);\n if (suffix.length > base.length && suffix.length <= path.length && suffix.endsWith(base)) return path.slice(start);\n return suffix && suffix.length < base.length && base.endsWith(suffix)\n ? base.slice(0, -suffix.length)\n : base;\n}\n\nexport const dirname = virtualDirname;\n\nexport function extname(path: string): string {\n const base = basename(path);\n const position = base.lastIndexOf(\".\");\n return position <= 0 || base === \"..\" ? \"\" : base.slice(position);\n}\n\nexport function isAbsolutePath(path: string): boolean {\n assertString(path);\n return path.startsWith(\"/\");\n}\n\nexport function joinPath(...paths: string[]): string {\n for (const path of paths) assertString(path);\n const joined = paths.filter(Boolean).join(\"/\");\n if (!joined) return \".\";\n const absolute = joined.startsWith(\"/\");\n const components: string[] = [];\n for (const component of joined.split(\"/\")) {\n if (!component || component === \".\") continue;\n if (component === \"..\") {\n if (components.length && components.at(-1) !== \"..\") components.pop();\n else if (!absolute) components.push(component);\n } else components.push(component);\n }\n const result = `${absolute ? \"/\" : \"\"}${components.join(\"/\")}` || \".\";\n return joined.endsWith(\"/\") && result !== \"/\" ? `${result}/` : result;\n}\n\nexport const posixPath = Object.freeze({ basename, dirname, extname, join: joinPath, isAbsolute: isAbsolutePath });\n", "import type { FileStat } from \"../../contracts/filesystem.js\";\n\nfunction complete(stat: FileStat): boolean {\n const { identityScope, dev, ino } = stat;\n return ((typeof identityScope === \"object\" && identityScope !== null) || typeof identityScope === \"symbol\")\n && typeof dev === \"number\" && Number.isSafeInteger(dev) && dev >= 0\n && typeof ino === \"number\" && Number.isSafeInteger(ino) && ino >= 0;\n}\n\nexport function compareIdentity(left: FileStat | undefined, right: FileStat | undefined): \"same\" | \"distinct\" | \"unknown\" {\n if (!left || !right || !complete(left) || !complete(right)) return \"unknown\";\n return left.identityScope === right.identityScope && left.dev === right.dev && left.ino === right.ino\n ? \"same\" : \"distinct\";\n}\n", "import { comparisonContext, platform } from \"#safe-fs-platform\";\nimport { FsError } from \"../../contracts/errors.js\";\nimport type { EntryComparison, FileStat, FileSystem, FsOptions } from \"../../contracts/filesystem.js\";\nimport { compareIdentity } from \"./identity.js\";\n\nexport interface EntryLocation {\n readonly filesystem: FileSystem;\n readonly path: string;\n readonly readOnly?: boolean;\n readonly stat?: FileStat;\n}\n\nexport interface EntryView extends EntryLocation {\n readonly stat: FileStat;\n readonly readOnly: boolean;\n}\n\nexport type EntryViewResolver = (path: string, options: FsOptions) => Promise<EntryLocation>;\nexport type EntryAuthority = (own: EntryView, peer: EntryView, options: FsOptions) => Promise<EntryComparison>;\n\nconst resolvers = new WeakMap<FileSystem, EntryViewResolver>();\nconst authorities = new WeakMap<FileSystem, EntryAuthority>();\nexport function assertCallbackAuthorityAllowed(): void {\n if (!platform.callbackAuthorities) throw new FsError(\"ENOTSUP\", { message: \"custom comparison authorities require Node context\" });\n}\n\nexport function registerEntryView(filesystem: FileSystem, resolver: EntryViewResolver): void {\n if (resolvers.has(filesystem)) throw new TypeError(\"entry view already registered\");\n resolvers.set(filesystem, resolver);\n}\n\nexport function registerEntryAuthority(filesystem: FileSystem, authority: EntryAuthority): void {\n if (authorities.has(filesystem)) throw new TypeError(\"entry authority already registered\");\n authorities.set(filesystem, authority);\n}\n\nexport async function resolveEntryView(filesystem: FileSystem, path: string, options: FsOptions = {}): Promise<EntryView> {\n let location: EntryLocation = { filesystem, path };\n let readOnly = false;\n const visited = new Set<FileSystem>();\n for (;;) {\n options.signal?.throwIfAborted();\n if (visited.has(location.filesystem)) throw new FsError(\"EIO\", { path, message: \"cyclic entry view\" });\n visited.add(location.filesystem);\n readOnly ||= location.readOnly === true || location.filesystem.capabilities.readOnly === true;\n if (location.stat) return { filesystem: location.filesystem, path: location.path, stat: location.stat, readOnly };\n const resolve = resolvers.get(location.filesystem);\n if (!resolve) {\n let stat: FileStat;\n let followedPath: string;\n try {\n followedPath = await location.filesystem.realpath(location.path, options);\n options.signal?.throwIfAborted();\n stat = await location.filesystem.lstat(followedPath, options);\n }\n catch (error) { options.signal?.throwIfAborted(); throw error; }\n options.signal?.throwIfAborted();\n if (stat.type === \"symlink\") throw new FsError(\"EIO\", { path, message: \"followed entry changed during observation\" });\n return { filesystem: location.filesystem, path: followedPath, stat, readOnly };\n }\n let next: EntryLocation;\n try { next = await resolve(location.path, options); }\n catch (error) { options.signal?.throwIfAborted(); throw error; }\n options.signal?.throwIfAborted();\n if (next.filesystem === location.filesystem && next.stat) {\n return { filesystem: next.filesystem, path: next.path, stat: next.stat, readOnly: readOnly || next.readOnly === true };\n }\n location = next;\n }\n}\n\nexport async function compareResolvedEntries(own: EntryView, peer: EntryView, options: FsOptions = {}): Promise<EntryComparison> {\n options.signal?.throwIfAborted();\n if (comparisonContext.active(options)) return \"unknown\";\n const identity = compareIdentity(own.stat, peer.stat);\n if (identity !== \"unknown\") return identity;\n return comparisonContext.run(options, async (options) => {\n const queried = new Set<EntryAuthority | FileSystem>();\n let result: EntryComparison = \"unknown\";\n for (const [left, right] of [[own, peer], [peer, own]] as const) {\n options.signal?.throwIfAborted();\n const authority = authorities.get(left.filesystem);\n const key = authority ?? left.filesystem;\n if (queried.has(key)) continue;\n queried.add(key);\n let answer: EntryComparison;\n try {\n if (authority) answer = await authority(left, right, options);\n else if (left.filesystem.compareEntry) {\n assertCallbackAuthorityAllowed();\n answer = await left.filesystem.compareEntry(left.path, right.filesystem, right.path, options);\n }\n else continue;\n } catch (error) {\n options.signal?.throwIfAborted();\n throw error;\n }\n options.signal?.throwIfAborted();\n if (answer !== \"same\" && answer !== \"distinct\" && answer !== \"unknown\") {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"invalid entry comparison answer\" });\n }\n if (answer === \"unknown\") continue;\n if (result !== \"unknown\" && result !== answer) {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"conflicting entry comparison answers\" });\n }\n result = answer;\n }\n return result;\n });\n}\n\nexport async function compareEntries(\n filesystem: FileSystem, path: string, peer: FileSystem, peerPath: string, options: FsOptions = {},\n): Promise<EntryComparison> {\n options.signal?.throwIfAborted();\n if (comparisonContext.active(options)) return \"unknown\";\n const own = await resolveEntryView(filesystem, path, options);\n const other = await resolveEntryView(peer, peerPath, options);\n return compareResolvedEntries(own, other, options);\n}\n", "import { FsError } from \"../../contracts/errors.js\";\nimport type { FileStat, FileSystem, FsOptions, EntryComparison } from \"../../contracts/filesystem.js\";\nimport type { EntryView } from \"../mount/comparison.js\";\nimport { assertCallbackAuthorityAllowed } from \"../mount/comparison.js\";\n\nexport interface OwnedS3Entry {\n readonly storage: object;\n readonly key: string;\n}\n\nconst observedStats = new WeakMap<FileStat, { filesystem: FileSystem; path: string; entry: OwnedS3Entry }>();\nconst entries = new WeakMap<FileSystem, (view: EntryView) => OwnedS3Entry | undefined>();\nconst comparisons = new WeakMap<FileSystem, NonNullable<FileSystem[\"compareEntry\"]>>();\nconst configuredComparisons = new WeakMap<FileSystem, NonNullable<FileSystem[\"compareEntry\"]>>();\n\nexport function recordS3Observation(filesystem: FileSystem, path: string, stat: FileStat, entry: OwnedS3Entry): void {\n observedStats.set(stat, { filesystem, path, entry });\n}\n\nexport function registerS3EntryOwner(filesystem: FileSystem, normalize: (path: string) => string,\n intact: () => boolean, baseComparison: NonNullable<FileSystem[\"compareEntry\"]>, comparison?: NonNullable<FileSystem[\"compareEntry\"]>): void {\n comparisons.set(filesystem, baseComparison);\n if (comparison) configuredComparisons.set(filesystem, comparison);\n entries.set(filesystem, view => {\n if (!intact()) return undefined;\n const observation = observedStats.get(view.stat);\n return observation?.filesystem === filesystem && observation.path === normalize(view.path) ? observation.entry : undefined;\n });\n}\n\nexport function getOwnedS3Entry(view: EntryView): OwnedS3Entry | undefined {\n return entries.get(view.filesystem)?.(view);\n}\n\nexport async function compareOwnedS3Entries(own: EntryView, peer: EntryView, options: FsOptions): Promise<EntryComparison> {\n options.signal?.throwIfAborted();\n let explicit = false;\n let answer: EntryComparison = \"unknown\";\n const visited = new Set<FileSystem>();\n for (const [left, right] of [[own, peer], [peer, own]] as const) {\n const baseComparison = comparisons.get(left.filesystem);\n if (!baseComparison || visited.has(left.filesystem)) continue;\n visited.add(left.filesystem);\n const current = left.filesystem.compareEntry;\n const comparison = current === baseComparison ? configuredComparisons.get(left.filesystem) : current;\n if (current === baseComparison && comparison === undefined) continue;\n explicit = true;\n if (comparison === undefined) continue;\n options.signal?.throwIfAborted();\n if (typeof comparison !== \"function\") {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"invalid explicit S3 comparison method\" });\n }\n assertCallbackAuthorityAllowed();\n const result = await comparison.call(left.filesystem, left.path, right.filesystem, right.path, options);\n options.signal?.throwIfAborted();\n if (result !== \"same\" && result !== \"distinct\" && result !== \"unknown\") {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"invalid explicit S3 comparison\" });\n }\n if (result === \"unknown\") continue;\n if (answer !== \"unknown\" && answer !== result) {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"conflicting explicit S3 comparisons\" });\n }\n answer = result;\n }\n const left = getOwnedS3Entry(own);\n options.signal?.throwIfAborted();\n const right = getOwnedS3Entry(peer);\n options.signal?.throwIfAborted();\n const same = left && right && left.storage === right.storage && left.key === right.key;\n if (same && answer === \"distinct\") {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"explicit S3 comparison contradicts a known alias\" });\n }\n if (same) return \"same\";\n if (explicit) return answer;\n return left && right ? \"distinct\" : \"unknown\";\n}\n", "import type { EntryComparison, FileStat, FileSystem, FsOptions } from \"../../contracts/filesystem.js\";\nimport type { EntryAuthority, EntryView } from \"../mount/comparison.js\";\nimport { FsError } from \"../../contracts/errors.js\";\nimport { assertCallbackAuthorityAllowed } from \"../mount/comparison.js\";\n\nexport interface OwnedWebDavEntry {\n readonly storage: object;\n readonly resource: object;\n}\n\nexport interface OwnedWebDavResource extends OwnedWebDavEntry {\n readonly identifier: string;\n}\n\nconst responses = new WeakMap<Response, ReadonlyMap<string, OwnedWebDavResource>>();\nconst observations = new WeakMap<FileStat, { filesystem: FileSystem; path: string; entry: OwnedWebDavResource }>();\nexport function registerOwnedResourceResponse(response: Response, entries: ReadonlyMap<string, OwnedWebDavResource>): void {\n if (responses.has(response)) throw new TypeError(\"resource response already registered\");\n responses.set(response, new Map(entries));\n}\n\nexport function recordOwnedResourceStat(response: Response, filesystem: FileSystem, path: string, stat: FileStat): void {\n const entry = responses.get(response)?.get(path);\n if (entry) observations.set(stat, { filesystem, path, entry });\n}\n\nexport function getOwnedWebDavEntry(view: EntryView): OwnedWebDavEntry | undefined {\n const observation = observations.get(view.stat);\n return observation?.filesystem === view.filesystem && observation.path === view.path\n ? observation.entry : undefined;\n}\n\nexport function ownedResponseIdentifier(response: Response, path: string): string | undefined {\n return responses.get(response)?.get(path)?.identifier;\n}\n\ntype ResourceQuery = (path: string, options: FsOptions) => Promise<string | undefined>;\nconst queries = new WeakMap<FileSystem, ResourceQuery>();\nconst comparisons = new WeakMap<FileSystem, NonNullable<FileSystem[\"compareEntry\"]>>();\nconst callbacks = new WeakMap<FileSystem, NonNullable<FileSystem[\"compareEntry\"]>>();\n\nexport function registerResourceQuery(filesystem: FileSystem, query: ResourceQuery,\n baseComparison: NonNullable<FileSystem[\"compareEntry\"]>, callback?: NonNullable<FileSystem[\"compareEntry\"]>): void {\n comparisons.set(filesystem, baseComparison);\n if (callback) callbacks.set(filesystem, callback);\n queries.set(filesystem, async (path, options) => {\n options.signal?.throwIfAborted();\n const identifier = await query(path, options);\n options.signal?.throwIfAborted();\n return identifier;\n });\n}\n\nexport function resourceIdentifier(value: string): string {\n if (!/^[A-Za-z][A-Za-z0-9+.-]*:[^\\s<>\"{}|\\\\^`]+$/.test(value) || /%(?![0-9A-Fa-f]{2})/.test(value)\n || /[^\\x21-\\x7e]/.test(value)) throw new Error(\"invalid DAV:resource-id URI\");\n new URL(value);\n if (/^urn:uuid:/i.test(value)) {\n if (!/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) {\n throw new Error(\"invalid DAV:resource-id UUID\");\n }\n return value.toLowerCase();\n }\n return value;\n}\n\nexport const compareWebDavResources: EntryAuthority = async (own, peer, options): Promise<EntryComparison> => {\n options.signal?.throwIfAborted();\n let explicit = false;\n let answer: EntryComparison = \"unknown\";\n const visited = new Set<FileSystem>();\n for (const [left, right] of [[own, peer], [peer, own]] as const) {\n const baseComparison = comparisons.get(left.filesystem);\n if (!baseComparison) continue;\n const method = left.filesystem.compareEntry;\n const comparison = method === baseComparison ? callbacks.get(left.filesystem) : method;\n if (method === baseComparison && !comparison) continue;\n explicit = true;\n if (!comparison || visited.has(left.filesystem)) continue;\n visited.add(left.filesystem);\n options.signal?.throwIfAborted();\n assertCallbackAuthorityAllowed();\n const result = await comparison.call(left.filesystem, left.path, right.filesystem, right.path, options);\n options.signal?.throwIfAborted();\n if (result !== \"same\" && result !== \"distinct\" && result !== \"unknown\") {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"invalid explicit WebDAV comparison\" });\n }\n if (result === \"unknown\") continue;\n if (answer !== \"unknown\" && answer !== result) {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"conflicting explicit WebDAV comparisons\" });\n }\n answer = result;\n }\n const builtin = await compareProtocolEntries(own, peer, options);\n if (builtin === \"same\" && answer === \"distinct\") {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"explicit WebDAV comparison contradicts built-in identity\" });\n }\n if (builtin === \"same\") return \"same\";\n return explicit ? answer : builtin;\n};\n\nasync function compareProtocolEntries(own: EntryView, peer: EntryView, options: FsOptions): Promise<EntryComparison> {\n const left = getOwnedWebDavEntry(own);\n const right = getOwnedWebDavEntry(peer);\n const ownQuery = queries.get(own.filesystem);\n const peerQuery = queries.get(peer.filesystem);\n if (!ownQuery || !peerQuery) return \"unknown\";\n options.signal?.throwIfAborted();\n const ownId = await ownQuery(own.path, options);\n options.signal?.throwIfAborted();\n const peerId = await peerQuery(peer.path, options);\n options.signal?.throwIfAborted();\n if (ownId === undefined || peerId === undefined) return \"unknown\";\n if (left && right) {\n const same = left.storage === right.storage && left.resource === right.resource;\n if (same !== (ownId === peerId)) throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"conflicting owned and protocol WebDAV identities\" });\n }\n return ownId === peerId ? \"same\" : \"distinct\";\n}\n", "import { FsError } from \"../contracts/errors.js\";\nimport type { ReadDirectoryOptions } from \"../contracts/filesystem.js\";\n\nexport function directoryEntryLimit(options: ReadDirectoryOptions, path: string): number | undefined {\n options.signal?.throwIfAborted();\n const limit = options.maxEntries;\n if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 0)) {\n throw new FsError(\"EINVAL\", { syscall: \"readdir\", path, message: \"directory entry limit must be a nonnegative safe integer\" });\n }\n return limit;\n}\n\nexport function admitDirectoryEntries(count: number, limit: number | undefined, path: string): void {\n if (limit !== undefined && count > limit) {\n throw new FsError(\"EFBIG\", { syscall: \"readdir\", path, message: \"directory entry limit exceeded\" });\n }\n}\n", "import { FsError } from \"../../contracts/errors.js\";\nimport type { ErrnoCode } from \"../../contracts/errors.js\";\n\ntype Node = { type: \"file\"; mode: number }\n | { type: \"symlink\"; mode: number; target: string }\n | { type: \"directory\"; mode: number; entries: ReadonlyMap<string, Node> };\n\ninterface Position {\n readonly node: Node;\n readonly name: string;\n readonly parent?: Position;\n}\n\ninterface Component {\n readonly name: string;\n readonly start: number;\n}\n\nfunction components(path: string, signal?: AbortSignal): Component[] {\n const result: Component[] = [];\n let start = 0;\n for (let offset = 0; offset <= path.length; offset++) {\n signal?.throwIfAborted();\n if (offset !== path.length && path.charCodeAt(offset) !== 47) continue;\n if (offset > start) result.push({ name: path.slice(start, offset), start });\n start = offset + 1;\n }\n return result;\n}\n\nexport function resolveMissingTarget(root: Node, path: string, signal?: AbortSignal): string {\n const fail = (code: ErrnoCode, failedPath = path): never => {\n throw new FsError(code, { syscall: \"realpath\", path: failedPath });\n };\n const origin = components(path, signal);\n const initial: Position = { node: root, name: \"\" };\n let position = initial;\n let links = 0;\n let missing = origin.length;\n let missingLink = false;\n for (let index = 0; index <= origin.length; index++) {\n const token = origin[index];\n if (!token && path.length > 0 && !path.endsWith(\"/\")) break;\n const before = position;\n const frames = [{ names: [token ?? { name: \".\", start: path.length }], next: 0 }];\n let first = true;\n let originLink = false;\n let found = true;\n while (frames.length > 0) {\n signal?.throwIfAborted();\n const frame = frames.at(-1);\n if (!frame) break;\n const component = frame.names[frame.next++];\n if (!component) { frames.pop(); continue; }\n const current = position.node;\n if (current.type !== \"directory\") return fail(\"ENOTDIR\");\n if (((current.mode >> 6) & 1) !== 1) return fail(\"EACCES\");\n const name = component.name;\n if (name === \".\") { first = false; continue; }\n if (name === \"..\") { position = position.parent ?? initial; first = false; continue; }\n if (new TextEncoder().encode(name).byteLength > 255) return fail(\"ENAMETOOLONG\");\n const node = current.entries.get(name);\n if (!node) { found = false; break; }\n if (first) originLink = node.type === \"symlink\";\n first = false;\n if (node.type === \"symlink\") {\n if (++links > 40) return fail(\"ELOOP\");\n const names = components(node.target, signal);\n if (node.target.endsWith(\"/\")) names.push({ name: \".\", start: node.target.length });\n if (node.target.startsWith(\"/\")) position = initial;\n frames.push({ names, next: 0 });\n } else position = { node, name, parent: position };\n }\n if (!found) {\n position = before;\n missing = index;\n missingLink = originLink;\n break;\n }\n }\n if (missingLink) {\n let end = path.length;\n for (let count = origin.length; count > missing; count--) {\n signal?.throwIfAborted();\n if (count === missing + 1 && path[end - 1] !== \"/\") return fail(\"ENOENT\", path.slice(0, end));\n const last = origin[count - 1];\n if (!last) break;\n const boundary = last.start - 1;\n end = boundary <= 0 ? 1 : boundary === 1 && path.startsWith(\"/\") ? 2 : boundary;\n }\n }\n const names: string[] = [];\n for (let current: Position | undefined = position; current?.parent; current = current.parent) {\n signal?.throwIfAborted();\n names.push(current.name);\n }\n names.reverse();\n for (let index = missing; index < origin.length; index++) {\n signal?.throwIfAborted();\n const name = origin[index]?.name;\n if (name === \"..\") names.pop();\n else if (name && name !== \".\") names.push(name);\n }\n return `/${names.join(\"/\")}`;\n}\n", "import { FsError } from \"../../contracts/errors.js\";\nimport type { MemoryFileSystemLimits } from \"./limits.js\";\n\nexport class MemoryLedger {\n private retainedBytes = 0;\n private metadataUnits = 0;\n\n constructor(readonly limits: Readonly<MemoryFileSystemLimits>) {}\n\n get availableBytes(): number {\n return this.limits.maxRetainedBytes - this.retainedBytes;\n }\n\n fileSize(length: number, syscall: string, path: string): void {\n if (!Number.isSafeInteger(length) || length < 0 || length > this.limits.maxFileBytes) {\n throw new FsError(\"EFBIG\", { syscall, path });\n }\n }\n\n check(bytes: number, units: number, syscall: string, path: string): void {\n if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > this.availableBytes ||\n !Number.isSafeInteger(units) || units < 0 || units > this.limits.maxMetadataUnits - this.metadataUnits) {\n throw new FsError(\"ENOSPC\", { syscall, path });\n }\n }\n\n reserve(bytes: number, units: number, syscall: string, path: string): void {\n this.check(bytes, units, syscall, path);\n this.retainedBytes += bytes;\n this.metadataUnits += units;\n }\n\n release(bytes: number, units: number): void {\n if (bytes < 0 || units < 0 || bytes > this.retainedBytes || units > this.metadataUnits) {\n throw new Error(\"Invalid Memory filesystem reservation release\");\n }\n this.retainedBytes -= bytes;\n this.metadataUnits -= units;\n }\n}\n\nexport class MemoryAllocation {\n private references = 1;\n\n constructor(readonly data: Uint8Array, private readonly ledger: MemoryLedger) {}\n\n retain(): void {\n this.references++;\n }\n\n release(): void {\n if (this.references <= 0) throw new Error(\"Memory allocation already released\");\n if (--this.references === 0) this.ledger.release(this.data.byteLength, 0);\n }\n}\n", "import type { FileSystem, FileSystemFactory } from \"./contracts/filesystem.js\";\n\nexport type FileSystemConfig = {\n readonly type: string;\n readonly options?: Readonly<Record<string, unknown>>;\n};\nexport type FileSystemAdapterDescriptor = {\n readonly validateOptions: (options: Readonly<Record<string, unknown>>) => void;\n readonly create: FileSystemFactory;\n};\nexport type FileSystemAdapterRegistry = ReadonlyMap<string, FileSystemAdapterDescriptor>;\n\nexport function readConfigRecord(\n value: unknown,\n label: string,\n keys?: readonly string[]\n): Readonly<Record<string, unknown>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be a record.`);\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(`${label} must be a plain record.`);\n }\n const record: Record<string, unknown> = Object.create(null);\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== \"string\" || (keys !== undefined && !keys.includes(key))) {\n throw new TypeError(`Unknown ${label}: ${String(key)}`);\n }\n const property = Object.getOwnPropertyDescriptor(value, key)!;\n if (!(\"value\" in property)) throw new TypeError(`${label}.${key} must be a data property.`);\n record[key] = property.value;\n }\n return Object.freeze(record);\n}\n\nexport function validateFileSystemConfig(value: unknown): FileSystemConfig {\n const config = readConfigRecord(value, \"filesystem config\", [\"type\", \"options\"]);\n if (typeof config.type !== \"string\" || config.type.trim().length === 0) {\n throw new TypeError(\"Filesystem adapter type must be a nonempty string.\");\n }\n return {\n type: config.type,\n ...(config.options === undefined\n ? {}\n : { options: readConfigRecord(config.options, \"filesystem options\") })\n };\n}\n\nexport async function createFileSystem(\n config: FileSystemConfig,\n options: { registry: FileSystemAdapterRegistry }\n): Promise<FileSystem> {\n const validated = validateFileSystemConfig(config);\n const creation = readConfigRecord(options, \"filesystem creation option\", [\"registry\"]);\n const registry = creation.registry as FileSystemAdapterRegistry | undefined;\n if (registry === undefined || registry === null || typeof registry.get !== \"function\") {\n throw new TypeError(\"registry must be a filesystem adapter map.\");\n }\n const descriptor = registry.get(validated.type);\n if (descriptor === undefined)\n throw new TypeError(`Unknown filesystem adapter: ${validated.type}`);\n const adapterOptions = validated.options ?? Object.freeze(Object.create(null));\n descriptor.validateOptions(adapterOptions);\n return await descriptor.create(adapterOptions);\n}\n", "import { readConfigRecord } from \"../../config.js\";\n\nexport interface MemoryFileSystemLimits {\n readonly maxBytes?: number;\n readonly maxFileBytes: number;\n readonly maxRetainedBytes: number;\n readonly maxMetadataUnits: number;\n}\n\nexport type MemoryFileSystemOptions = Partial<MemoryFileSystemLimits>;\n\nexport const defaultMemoryFileSystemLimits: Readonly<MemoryFileSystemLimits> = Object.freeze({\n maxFileBytes: 16 * 1024 * 1024,\n maxRetainedBytes: 64 * 1024 * 1024,\n maxMetadataUnits: 10_000,\n});\n\nexport function normalizeMemoryFileSystemLimits(options: unknown): Readonly<MemoryFileSystemLimits> {\n const keys = [\"maxFileBytes\", \"maxRetainedBytes\", \"maxMetadataUnits\"] as const;\n const record = readConfigRecord(options, \"memory option\", [...keys, \"maxBytes\"]);\n const limits: { -readonly [Key in keyof MemoryFileSystemLimits]: MemoryFileSystemLimits[Key] } = { ...defaultMemoryFileSystemLimits };\n if (Object.hasOwn(record, \"maxBytes\") && record.maxBytes !== undefined) {\n if (typeof record.maxBytes !== \"number\" || !Number.isSafeInteger(record.maxBytes) || record.maxBytes < 0) {\n throw new RangeError(\"maxBytes must be a nonnegative safe integer\");\n }\n limits.maxBytes = record.maxBytes;\n }\n for (const key of keys) {\n const value = Object.hasOwn(record, key) ? record[key] : limits[key];\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < (key === \"maxMetadataUnits\" ? 1 : 0)) {\n throw new RangeError(`${key} must be a ${key === \"maxMetadataUnits\" ? \"positive\" : \"nonnegative\"} safe integer`);\n }\n limits[key] = value;\n }\n return Object.freeze(limits);\n}\n", "import { FsError } from \"../../contracts/errors.js\";\nimport type { ErrnoCode } from \"../../contracts/errors.js\";\nimport type {\n AppendFileOptions, CopyFileOptions, DirectoryEntry, EntryComparison, FileReadHandle, FileResizeHandle, FileStat, FileSystem,\n FsOptions, RenameOptions, MkdirOptions, ReadDirectoryOptions, ReadFileOptions, ReadStreamOptions, RemoveOptions,\n FileDescriptor, OpenFileOptions, OpenReadFileOptions, OpenResizeFileOptions, WriteFileOptions,\n ConditionalWriteFileOptions, ConditionalRemoveFileOptions, ConditionalRemoveEntryOptions, CreateStagedFileOptions, FileStaging, PublishStagedFileOptions, PrepareDirectoryOptions, StagedFileContent,\n} from \"../../contracts/filesystem.js\";\nimport type { ByteSource } from \"../../contracts/io.js\";\nimport { assertCallbackAuthorityAllowed, compareEntries, registerEntryAuthority } from \"../mount/comparison.js\";\nimport type { EntryAuthority } from \"../mount/comparison.js\";\nimport { getOwnedS3Entry } from \"../s3/registry.js\";\nimport { getOwnedWebDavEntry } from \"../webdav/resource-id.js\";\nimport { admitDirectoryEntries, directoryEntryLimit } from \"../directory-admission.js\";\nimport { openFileDescriptor } from \"../descriptor.js\";\nimport { resolveMissingTarget } from \"./missing-target.js\";\nimport { MemoryAllocation, MemoryLedger } from \"./ledger.js\";\nimport { normalizeMemoryFileSystemLimits, type MemoryFileSystemOptions } from \"./limits.js\";\n\nexport { defaultMemoryFileSystemLimits, type MemoryFileSystemLimits, type MemoryFileSystemOptions } from \"./limits.js\";\n\ninterface Metadata {\n revision: number;\n mode: number;\n ino: number;\n nlink: number;\n atimeMs: number;\n mtimeMs: number;\n ctimeMs: number;\n birthtimeMs: number;\n references: number;\n}\n\ninterface FileNode extends Metadata {\n type: \"file\";\n data: Uint8Array;\n allocation: MemoryAllocation;\n}\n\ninterface DirectoryNode extends Metadata {\n type: \"directory\";\n entries: Map<string, MemoryNode>;\n}\n\ninterface SymlinkNode extends Metadata {\n type: \"symlink\";\n target: string;\n}\n\ntype MemoryNode = FileNode | DirectoryNode | SymlinkNode;\n\ninterface Location {\n node: MemoryNode | undefined;\n parent: DirectoryNode;\n name: string;\n path: string;\n}\n\ninterface ResolveOptions {\n resizeCreate?: boolean;\n followFinal?: boolean;\n allowMissing?: boolean;\n createDirectories?: number;\n}\n\ninterface WriteTarget {\n location: Location;\n mode: number;\n append: boolean;\n}\n\nconst typeModes = { file: 0o100000, directory: 0o040000, symlink: 0o120000 } as const;\nconst preferredIoBlockSize = 64 * 1024;\nconst ext4HtreeEof64 = (1n << 63n) - 1n;\nconst ownedStats = new WeakMap<FileStat, { filesystem: FileSystem; path: string; root: DirectoryNode }>();\nconst ownedStores = new WeakMap<FileSystem, { root: DirectoryNode; ledger: MemoryLedger; capabilities: FileSystem[\"capabilities\"]; intact: () => boolean }>();\nconst registeredAuthorities = new WeakSet<FileSystem>();\nconst compareOwnedMemory: EntryAuthority = async (own, peer, options) => {\n options.signal?.throwIfAborted();\n let explicit = false;\n let answer: EntryComparison = \"unknown\";\n const visited = new Set<FileSystem>();\n for (const [left, right] of [[own, peer], [peer, own]] as const) {\n if (!registeredAuthorities.has(left.filesystem) || visited.has(left.filesystem)) continue;\n visited.add(left.filesystem);\n const comparison = left.filesystem.compareEntry;\n if (comparison === memoryImplementation.compareEntry?.value) continue;\n explicit = true;\n if (!comparison) continue;\n options.signal?.throwIfAborted();\n assertCallbackAuthorityAllowed();\n const result = await comparison.call(left.filesystem, left.path, right.filesystem, right.path, options);\n options.signal?.throwIfAborted();\n if (result !== \"same\" && result !== \"distinct\" && result !== \"unknown\") {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"invalid explicit Memory comparison\" });\n }\n if (result === \"unknown\") continue;\n if (answer !== \"unknown\" && answer !== result) {\n throw new FsError(\"EIO\", { path: own.path, dest: peer.path, message: \"conflicting explicit Memory comparisons\" });\n }\n answer = result;\n }\n if (explicit) return answer;\n const owner = ownedStores.get(own.filesystem);\n const observation = ownedStats.get(own.stat);\n if (!owner?.intact() || observation?.filesystem !== own.filesystem || observation.path !== own.path\n || observation.root !== owner.root) return \"unknown\";\n const qualified = getOwnedS3Entry(peer) ?? getOwnedWebDavEntry(peer);\n options.signal?.throwIfAborted();\n return qualified ? \"distinct\" : \"unknown\";\n};\n\nexport class MemoryFileSystem implements FileSystem {\n readonly capabilities = ((filesystem: MemoryFileSystem) => {\n return Object.freeze({\n read: true, stat: true, readdir: true, realpath: true, access: true, open: true,\n write: true, append: true, exclusiveCreate: true, explicitDirectories: true, implicitDirectories: false,\n mkdir: true, recursiveMkdir: true, remove: true, removeDirectory: true, recursiveRemove: true,\n rename: true, atomicRenameNoReplace: true, copy: true, exclusiveCopy: true, readlink: true, truncate: true,\n streamingAppend: true, randomAccessWrite: true,\n readOnly: false,\n symlinks: true,\n hardlinks: true,\n permissions: true,\n timestamps: true,\n atomicRename: true,\n atomicFileStaging: true, atomicFileMutation: true, atomicEntryRemoval: true, atomicTreeRemoval: true,\n atomicDirectoryMetadata: true,\n streamingRead: true,\n retainedRead: true,\n get retainedResize() { return stockRetainedResize(filesystem); },\n streamingWrite: true,\n get descriptorWriteStream() { return stockDescriptorWrite(filesystem); },\n });\n })(this);\n\n private readonly identityScope = Symbol();\n private nextInode = 1;\n private readonly ledger: MemoryLedger;\n private readonly root: DirectoryNode;\n private totalBytes = 0;\n\n constructor(options: MemoryFileSystemOptions = {}) {\n this.ledger = new MemoryLedger(normalizeMemoryFileSystemLimits(options));\n this.ledger.reserve(0, 1, \"mkdir\", \"/\");\n this.root = this.directory(0o755);\n const root = this.root;\n ownedStores.set(this, {\n root,\n ledger: this.ledger,\n capabilities: this.capabilities,\n intact: () => this.root === root,\n });\n if (this.compareEntry === memoryImplementation.compareEntry?.value) {\n registeredAuthorities.add(this);\n registerEntryAuthority(this, compareOwnedMemory);\n }\n }\n\n compareEntry(path: string, peer: FileSystem, peerPath: string, options: FsOptions = {}): Promise<EntryComparison> {\n return compareEntries(this, path, peer, peerPath, options);\n }\n\n canonicalizeMissingTarget(path: string, options: FsOptions = {}): string | undefined {\n options.signal?.throwIfAborted();\n const owner = ownedStores.get(this);\n if (!owner || Object.getPrototypeOf(this) !== MemoryFileSystem.prototype\n || Object.getOwnPropertyDescriptor(this, \"root\")?.value !== owner.root) return undefined;\n for (const name of [\"realpath\", \"lstat\", \"resolve\", \"permission\", \"validatePath\", \"fail\", \"snapshot\"]) {\n const descriptor = Object.getOwnPropertyDescriptor(this, name)\n ?? Object.getOwnPropertyDescriptor(MemoryFileSystem.prototype, name);\n if (!descriptor || !(\"value\" in descriptor) || descriptor.value !== memoryImplementation[name]?.value) return undefined;\n }\n if (path !== \"\") this.validatePath(path, \"realpath\");\n return resolveMissingTarget(owner.root, path || \".\", options.signal);\n }\n\n private metadata(mode: number): Metadata {\n const now = Date.now();\n return {\n mode, ino: this.nextInode++, nlink: 1, references: 0, revision: 0,\n atimeMs: now, mtimeMs: now, ctimeMs: now, birthtimeMs: now,\n };\n }\n\n private directory(mode: number): DirectoryNode {\n return { ...this.metadata(typeModes.directory | mode), type: \"directory\", entries: new Map() };\n }\n\n private addNode<Node extends MemoryNode>(parent: DirectoryNode, name: string, create: () => Node,\n syscall: string, path: string, retainedBytes = 0): Node {\n const bytes = name.length * 2 + retainedBytes;\n this.ledger.reserve(bytes, 2, syscall, path);\n try {\n const node = create();\n if (node.type === \"file\") this.admitSize(undefined, node.data.byteLength, syscall, path);\n parent.entries.set(name, node);\n if (node.type === \"file\") this.totalBytes += node.data.byteLength;\n this.changed(parent);\n return node;\n } catch (error) {\n this.ledger.release(bytes, 2);\n throw error;\n }\n }\n\n private releaseNode(node: MemoryNode): void {\n if (node.nlink !== 0 || node.references !== 0) return;\n this.ledger.release(node.type === \"symlink\" ? node.target.length * 2 : 0, 1);\n if (node.type === \"file\") {\n this.totalBytes -= node.data.byteLength;\n node.allocation.release();\n }\n }\n\n private releaseReference(node: FileNode | DirectoryNode, path: string): void {\n node.references--;\n this.ledger.release(path.length * 2, 1);\n this.releaseNode(node);\n }\n\n private replaceData(node: FileNode, allocation: MemoryAllocation, length = allocation.data.byteLength): void {\n const previous = node.allocation;\n this.totalBytes += length - node.data.byteLength;\n node.data = allocation.data.subarray(0, length);\n node.allocation = allocation;\n previous.release();\n }\n\n private admitSize(node: FileNode | undefined, length: number, syscall: string, path: string): void {\n this.ledger.fileSize(length, syscall, path);\n if (length - (node?.data.byteLength ?? 0) > (this.ledger.limits.maxBytes ?? Number.MAX_SAFE_INTEGER) - this.totalBytes) {\n this.fail(\"ENOSPC\", syscall, path);\n }\n }\n\n private fail(code: ErrnoCode, syscall: string, path: string, dest?: string): never {\n throw new FsError(code, { syscall, path, ...(dest === undefined ? {} : { dest }) });\n }\n\n private validatePath(path: string, syscall: string): void {\n if (typeof path !== \"string\" || path.includes(\"\\0\")) this.fail(\"EINVAL\", syscall, path);\n if (path.length === 0) this.fail(\"ENOENT\", syscall, path);\n }\n\n private permission(node: MemoryNode, mask: number, syscall: string, path: string): void {\n if (((node.mode >> 6) & mask) !== mask) this.fail(\"EACCES\", syscall, path);\n }\n\n private mode(mode: number | undefined, fallback: number, syscall: string, path: string): number {\n const value = mode ?? fallback;\n if (!Number.isInteger(value) || value < 0 || value > 0o7777) this.fail(\"EINVAL\", syscall, path);\n return value;\n }\n\n private integer(value: number, syscall: string, path: string): void {\n if (!Number.isSafeInteger(value) || value < 0) this.fail(\"EINVAL\", syscall, path);\n }\n\n private changed(node: MemoryNode): void {\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n node.mtimeMs = node.ctimeMs = Date.now();\n }\n\n private resolve(path: string, syscall: string, options: ResolveOptions = {}): Location {\n this.validatePath(path, syscall);\n const pending = path.split(\"/\").filter(Boolean);\n if (path.endsWith(\"/\")) pending.push(\"\");\n const stack: { node: MemoryNode; name: string }[] = [{ node: this.root, name: \"\" }];\n let links = 0;\n while (pending.length > 0) {\n const component = pending.shift()!;\n const current = stack[stack.length - 1]!.node;\n if (current.type !== \"directory\") this.fail(\"ENOTDIR\", syscall, path);\n if (!(component === \"\" && pending.length === 0 && options.resizeCreate !== undefined)) this.permission(current, 1, syscall, path);\n if (component === \".\" || component === \"\") continue;\n if (component === \"..\") {\n if (stack.length > 1) stack.pop();\n continue;\n }\n if (new TextEncoder().encode(component).byteLength > 255) this.fail(\"ENAMETOOLONG\", syscall, path);\n if (options.resizeCreate === true && pending.length === 1 && pending[0] === \"\") this.fail(\"EISDIR\", syscall, path);\n let node = current.entries.get(component);\n if (!node && options.createDirectories !== undefined) {\n this.permission(current, 3, syscall, path);\n const mode = options.createDirectories;\n node = this.addNode(current, component, () => this.directory(mode), syscall, path);\n }\n if (!node) {\n if (options.allowMissing && pending.length === 0) {\n return { node, parent: current, name: component, path: [...stack.map((entry) => entry.name), component].join(\"/\") };\n }\n this.fail(\"ENOENT\", syscall, path);\n }\n if (node.type === \"symlink\" && (options.followFinal !== false || pending.length > 0)) {\n if (++links > 40) this.fail(\"ELOOP\", syscall, path);\n const target = node.target.split(\"/\").filter(Boolean);\n if (node.target.endsWith(\"/\")) target.push(\"\");\n if (options.resizeCreate !== undefined && target.at(-1) === \"\" && pending[0] === \"\") target.pop();\n pending.unshift(...target);\n if (node.target.startsWith(\"/\")) stack.splice(1);\n continue;\n }\n stack.push({ node, name: component });\n }\n const entry = stack[stack.length - 1]!;\n return {\n node: entry.node,\n parent: (stack[stack.length - 2]?.node ?? this.root) as DirectoryNode,\n name: entry.name,\n path: stack.map((part) => part.name).join(\"/\") || \"/\",\n };\n }\n\n private file(path: string, syscall: string): FileNode {\n const node = this.resolve(path, syscall).node!;\n if (node.type !== \"file\") this.fail(\"EISDIR\", syscall, path);\n return node;\n }\n\n private entry(path: string, syscall: string, allowMissing = false): Location {\n this.validatePath(path, syscall);\n const location = this.resolve(path.replace(/\\/+$/, \"\") || \"/\", syscall, { followFinal: false, allowMissing });\n if (path.endsWith(\"/\") && location.node && location.node.type !== \"directory\") this.fail(\"ENOTDIR\", syscall, path);\n return location;\n }\n\n private terminalDot(path: string): boolean {\n return /(?:^|\\/)\\.{1,2}\\/*$/.test(path);\n }\n\n private snapshot(node: MemoryNode): FileStat {\n return {\n type: node.type,\n ioBlockSize: preferredIoBlockSize,\n ...(Number.isSafeInteger(node.revision) ? { revision: node.revision } : {}),\n preferredIoBlockSize: 4096,\n size: node.type === \"file\" ? node.data.byteLength\n : node.type === \"symlink\" ? new TextEncoder().encode(node.target).byteLength : 0,\n mode: node.mode, ...(ownedStores.get(this)?.intact() ? { identityScope: this.identityScope } : {}),\n ino: node.ino, dev: 0, uid: 0, gid: 0,\n nlink: node.type === \"directory\" && node.nlink !== 0\n ? 2 + [...node.entries.values()].filter((entry) => entry.type === \"directory\").length : node.nlink,\n atimeMs: node.atimeMs, mtimeMs: node.mtimeMs, ctimeMs: node.ctimeMs, birthtimeMs: node.birthtimeMs,\n };\n }\n\n private bytes(data: Uint8Array, syscall: string, path: string): MemoryAllocation {\n const allocation = this.allocate(data.byteLength, syscall, path);\n try {\n allocation.data.set(data);\n return allocation;\n } catch (error) {\n allocation.release();\n throw error;\n }\n }\n\n private allocate(length: number, syscall: string, path: string): MemoryAllocation {\n this.ledger.fileSize(length, syscall, path);\n this.ledger.reserve(length, 0, syscall, path);\n try {\n return new MemoryAllocation(new Uint8Array(length), this.ledger);\n } catch (cause) {\n this.ledger.release(length, 0);\n throw new FsError(\"EFBIG\", { syscall, path, cause });\n }\n }\n\n open(path: string, options: OpenFileOptions): Promise<FileDescriptor> {\n return openFileDescriptor<{ node: FileNode | undefined; position: number }>(path, options, {\n positionedRead: true, positionedWrite: true, truncate: true, synchronization: \"volatile\", position: true,\n }, async admitted => {\n const location = this.resolve(path, \"open\", {\n followFinal: admitted.creation !== \"exclusive\", allowMissing: admitted.creation !== \"never\",\n });\n let node = location.node;\n if (node) {\n if (admitted.creation === \"exclusive\") this.fail(\"EEXIST\", \"open\", path);\n if (node.type !== \"file\") this.fail(\"EISDIR\", \"open\", path);\n this.permission(node, admitted.access === \"read\" ? 4 : admitted.access === \"write\" ? 2 : 6, \"open\", path);\n } else {\n this.permission(location.parent, 3, \"open\", path);\n }\n this.ledger.reserve(path.length * 2, 1, \"open\", path);\n try {\n node ??= this.openWrite(path, {}, \"open\", { location, mode: admitted.mode, append: false });\n if (admitted.truncate) this.resizeNode(node, 0, \"open\", path);\n } catch (error) {\n this.ledger.release(path.length * 2, 1);\n throw error;\n }\n node.references++;\n const resource: { node: FileNode | undefined; position: number } = { node, position: 0 };\n return {\n resource,\n getPosition: async retained => retained.position,\n stat: async retained => this.snapshot(retained.node!),\n read: async (retained, buffer, position) => {\n const inode = retained.node!;\n const start = position ?? retained.position;\n const count = Math.min(buffer.byteLength, Math.max(0, inode.data.byteLength - start));\n buffer.set(inode.data.subarray(start, start + count));\n if (position === null) retained.position += count;\n inode.atimeMs = Date.now();\n return count;\n },\n write: async (retained, buffer, position) => {\n const inode = retained.node!;\n const start = admitted.append ? inode.data.byteLength : position ?? retained.position;\n const end = start + buffer.byteLength;\n this.writeAt(inode, buffer, start, \"write\", path);\n if (position === null) retained.position = end;\n return buffer.byteLength;\n },\n truncate: async (retained, length) => {\n const inode = retained.node!;\n this.resizeNode(inode, length, \"ftruncate\", path);\n },\n sync: async () => {},\n close: async retained => {\n const inode = retained.node!;\n retained.node = undefined;\n this.releaseReference(inode, path);\n },\n };\n });\n }\n\n private prepareWrite(path: string, options: WriteFileOptions, syscall: string): WriteTarget {\n const flag = options.flag ?? \"w\";\n if (![\"w\", \"wx\", \"a\", \"ax\"].includes(flag)) this.fail(\"EINVAL\", syscall, path);\n const mode = this.mode(options.mode, 0o666, syscall, path);\n const exclusive = flag === \"wx\" || flag === \"ax\";\n const location = this.resolve(path, syscall, { followFinal: !exclusive, allowMissing: true });\n if (location.node) {\n if (exclusive) this.fail(\"EEXIST\", syscall, path);\n if (location.node.type !== \"file\") this.fail(\"EISDIR\", syscall, path);\n this.permission(location.node, 2, syscall, path);\n } else {\n this.permission(location.parent, 3, syscall, path);\n }\n return { location, mode, append: flag === \"a\" || flag === \"ax\" };\n }\n\n private openWrite(path: string, options: WriteFileOptions, syscall: string,\n target = this.prepareWrite(path, options, syscall)): FileNode {\n const { location, mode } = target;\n if (location.node) return location.node as FileNode;\n return this.addNode(location.parent, location.name, (): FileNode => {\n const allocation = new MemoryAllocation(new Uint8Array(), this.ledger);\n return { ...this.metadata(typeModes.file | mode), type: \"file\", data: allocation.data, allocation };\n }, syscall, path);\n }\n\n private writeData(path: string, data: Uint8Array, options: WriteFileOptions, syscall: string): FileNode {\n if (!(data instanceof Uint8Array)) throw new TypeError(\"Memory files require Uint8Array data\");\n const target = this.prepareWrite(path, options, syscall);\n const current = target.location.node as FileNode | undefined;\n const length = (target.append ? current?.data.byteLength ?? 0 : 0) + data.byteLength;\n this.admitSize(current, length, syscall, path);\n const growth = target.append && length > (current?.allocation.data.byteLength ?? 0) ? length : 0;\n this.ledger.check(data.byteLength + growth + (current ? 0 : target.location.name.length * 2), current ? 0 : 2, syscall, path);\n const copied = this.bytes(data, syscall, path);\n let allocation = copied;\n let transferred = false;\n try {\n if (!current) {\n if (target.append && length > 0) {\n const capacity = Math.min(Math.max(length, 64), this.ledger.limits.maxFileBytes,\n this.ledger.availableBytes - target.location.name.length * 2);\n allocation = this.allocate(capacity, syscall, path);\n allocation.data.set(copied.data);\n }\n const node = this.addNode(target.location.parent, target.location.name, (): FileNode => ({\n ...this.metadata(typeModes.file | target.mode), type: \"file\",\n data: allocation.data.subarray(0, length), allocation,\n }), syscall, path);\n transferred = true;\n return node;\n }\n if (target.append) this.writeAt(current, copied.data, current.data.byteLength, syscall, path);\n else {\n this.replaceData(current, copied);\n transferred = true;\n this.changed(current);\n }\n return current;\n } finally {\n if (allocation !== copied && !transferred) allocation.release();\n if (!transferred || allocation !== copied) copied.release();\n }\n }\n\n private writeAt(node: FileNode, data: Uint8Array, position: number, syscall: string, path: string): void {\n if (data.byteLength === 0) {\n this.changed(node);\n return;\n }\n const end = position + data.byteLength;\n this.ledger.fileSize(end, syscall, path);\n const length = Math.max(node.data.byteLength, end);\n this.admitSize(node, length, syscall, path);\n let allocation = node.allocation;\n if (length > allocation.data.byteLength) {\n this.ledger.check(length, 0, syscall, path);\n const capacity = Math.min(Math.max(length, node.data.byteLength * 2, 64),\n this.ledger.limits.maxFileBytes, this.ledger.availableBytes);\n allocation = this.allocate(capacity, syscall, path);\n }\n try {\n const storage = allocation.data;\n if (allocation !== node.allocation) storage.set(node.data);\n if (position > node.data.byteLength) storage.fill(0, node.data.byteLength, position);\n storage.set(data, position);\n } catch (error) {\n if (allocation !== node.allocation) allocation.release();\n throw error;\n }\n if (allocation !== node.allocation) this.replaceData(node, allocation, length);\n else {\n this.totalBytes += length - node.data.byteLength;\n node.data = allocation.data.subarray(0, length);\n }\n this.changed(node);\n }\n\n async readFile(path: string, options: ReadFileOptions = {}): Promise<Uint8Array> {\n options.signal?.throwIfAborted();\n if (options.maxBytes !== undefined) this.integer(options.maxBytes, \"readFile\", path);\n const node = this.file(path, \"readFile\");\n this.permission(node, 4, \"readFile\", path);\n if (options.maxBytes !== undefined && node.data.byteLength > options.maxBytes) this.fail(\"EFBIG\", \"readFile\", path);\n node.atimeMs = Date.now();\n return new Uint8Array(node.data);\n }\n\n private expectEntry(node: MemoryNode | undefined, expected: FileStat | null, path: string, unchanged = true): void {\n if (expected === null) {\n if (node) this.fail(\"EAGAIN\", \"fileStaging\", path);\n return;\n }\n if (!node) this.fail(\"EAGAIN\", \"fileStaging\", path);\n const current = this.snapshot(node);\n if (!expected.identityScope || expected.identityScope !== current.identityScope\n || !Number.isSafeInteger(expected.ino) || !Number.isSafeInteger(expected.dev)) this.fail(\"ENOTSUP\", \"fileStaging\", path);\n if (current.ino !== expected.ino || current.dev !== expected.dev || current.type !== expected.type) this.fail(\"EAGAIN\", \"fileStaging\", path);\n if (unchanged) {\n if (!Number.isSafeInteger(expected.revision) || !Number.isSafeInteger(current.revision)) this.fail(\"ENOTSUP\", \"fileStaging\", path);\n if (current.revision !== expected.revision || current.size !== expected.size || current.mode !== expected.mode\n || current.nlink !== expected.nlink || current.mtimeMs !== expected.mtimeMs || current.ctimeMs !== expected.ctimeMs) this.fail(\"EAGAIN\", \"fileStaging\", path);\n }\n }\n\n private stagingLocations(staging: FileStaging): { directory: Location; file: Location } {\n const parent = this.entry(staging.parent.path, \"fileStaging\");\n this.expectEntry(parent.node, staging.parent.stat, staging.parent.path, false);\n if (parent.node!.type !== \"directory\") this.fail(\"ENOTDIR\", \"fileStaging\", staging.parent.path);\n const directory = this.entry(staging.directory.path, \"fileStaging\");\n this.expectEntry(directory.node, staging.directory.stat, staging.directory.path, false);\n if (directory.parent !== parent.node || directory.node!.type !== \"directory\" || (directory.node!.mode & 0o777) !== 0o700) this.fail(\"EAGAIN\", \"fileStaging\", staging.directory.path);\n const file = this.entry(staging.file.path, \"fileStaging\", true);\n if (file.parent !== directory.node || ![\"file\", \"symlink\"].includes(staging.file.stat.type)) this.fail(\"EAGAIN\", \"fileStaging\", staging.file.path);\n return { directory, file };\n }\n\n async createStagedFile(directoryPath: string, name: string, content: StagedFileContent, options: CreateStagedFileOptions): Promise<FileStaging> {\n options.signal?.throwIfAborted();\n if (!name || name === \".\" || name === \"..\" || name.includes(\"/\") || name.includes(\"\\0\")) this.fail(\"EINVAL\", \"createStagedFile\", directoryPath);\n const location = this.entry(directoryPath, \"createStagedFile\", true);\n if (location.node) this.fail(\"EEXIST\", \"createStagedFile\", directoryPath);\n this.expectEntry(location.parent, options.parent, directoryPath, false);\n this.permission(location.parent, 3, \"createStagedFile\", directoryPath);\n const mode = this.mode(options.mode, content.type === \"file\" ? 0o666 : 0o777, \"createStagedFile\", directoryPath);\n for (const time of [options.atimeMs, options.mtimeMs]) if (time !== undefined && !Number.isFinite(time)) this.fail(\"EINVAL\", \"createStagedFile\", directoryPath);\n if (content.type === \"file\" && !(content.data instanceof Uint8Array)) throw new TypeError(\"Staged files require Uint8Array data\");\n if (content.type === \"file\") this.admitSize(undefined, content.data.byteLength, \"createStagedFile\", directoryPath);\n if (content.type === \"symlink\") this.validatePath(content.target, \"createStagedFile\");\n const retained = (location.name.length + name.length) * 2 + (content.type === \"symlink\" ? content.target.length * 2 : 0);\n this.ledger.reserve(retained, 4, \"createStagedFile\", directoryPath);\n let allocation: MemoryAllocation | undefined;\n let directory: DirectoryNode;\n let file: FileNode | SymlinkNode;\n try {\n if (content.type === \"file\") allocation = this.bytes(content.data, \"createStagedFile\", directoryPath);\n directory = this.directory(0o700);\n file = content.type === \"file\"\n ? { ...this.metadata(typeModes.file | mode), type: \"file\", data: allocation!.data, allocation: allocation! }\n : { ...this.metadata(typeModes.symlink | mode), type: \"symlink\", target: content.target };\n if (options.atimeMs !== undefined) file.atimeMs = options.atimeMs;\n if (options.mtimeMs !== undefined) file.mtimeMs = options.mtimeMs;\n directory.entries.set(name, file);\n location.parent.entries.set(location.name, directory);\n if (file.type === \"file\") this.totalBytes += file.data.byteLength;\n } catch (error) { allocation?.release(); this.ledger.release(retained, 4); throw error; }\n this.changed(location.parent);\n const parentPath = location.path.slice(0, location.path.lastIndexOf(\"/\")) || \"/\";\n const receipt = (path: string, node: MemoryNode) => Object.freeze({ path, stat: Object.freeze(this.snapshot(node)) });\n return Object.freeze({ parent: receipt(parentPath, location.parent), directory: receipt(location.path, directory), file: receipt(`${location.path}/${name}`, file) });\n }\n\n async publishStagedFile(staging: FileStaging, destination: string, options: PublishStagedFileOptions): Promise<void> {\n options.signal?.throwIfAborted();\n const { directory, file } = this.stagingLocations(staging);\n this.expectEntry(file.node, staging.file.stat, staging.file.path);\n const target = this.entry(destination, \"publishStagedFile\", true);\n this.expectEntry(target.parent, options.parent, destination, false);\n this.expectEntry(target.node, options.destination, destination);\n if (target.parent === directory.node || target.node === directory.node || target.node === file.node) this.fail(\"EINVAL\", \"publishStagedFile\", destination);\n if (target.node && (target.node.type !== \"file\" || target.node.nlink !== 1)) this.fail(\"EAGAIN\", \"publishStagedFile\", destination);\n return MemoryFileSystem.prototype.rename.call(this, staging.file.path, destination, { ...options, noReplace: options.destination === null });\n }\n\n async removeStagedFile(staging: FileStaging, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n const { directory, file } = this.stagingLocations(staging);\n if (file.node) this.expectEntry(file.node, staging.file.stat, staging.file.path);\n const node = directory.node as DirectoryNode;\n if (node.entries.size !== (file.node ? 1 : 0)) this.fail(\"ENOTEMPTY\", \"removeStagedFile\", staging.directory.path);\n this.permission(directory.parent, 3, \"removeStagedFile\", staging.directory.path);\n this.permission(node, 3, \"removeStagedFile\", staging.file.path);\n directory.parent.entries.delete(directory.name);\n if (file.node) {\n node.entries.delete(file.name);\n this.ledger.release(file.name.length * 2, 1);\n file.node.nlink--;\n file.node.ctimeMs = Date.now();\n file.node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, file.node.revision + 1);\n this.releaseNode(file.node);\n }\n this.ledger.release(directory.name.length * 2, 1);\n node.nlink = 0;\n node.ctimeMs = Date.now();\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n this.releaseNode(node);\n this.changed(directory.parent);\n }\n\n async prepareDirectory(path: string, options: PrepareDirectoryOptions): Promise<FileStat> {\n options.signal?.throwIfAborted();\n const location = this.entry(path, \"prepareDirectory\", true);\n this.expectEntry(location.parent, options.parent, path, false);\n this.expectEntry(location.node, options.expected, path, false);\n const mode = options.mode === undefined ? undefined : this.mode(options.mode, 0, \"prepareDirectory\", path);\n for (const time of [options.atimeMs, options.mtimeMs]) if (time !== undefined && !Number.isFinite(time)) this.fail(\"EINVAL\", \"prepareDirectory\", path);\n let node = location.node;\n if (!node) {\n this.permission(location.parent, 3, \"prepareDirectory\", path);\n node = this.addNode(location.parent, location.name, () => this.directory(mode ?? 0o777), \"prepareDirectory\", path);\n }\n if (node.type !== \"directory\") this.fail(\"ENOTDIR\", \"prepareDirectory\", path);\n if (mode !== undefined) node.mode = typeModes.directory | mode;\n if (options.atimeMs !== undefined) node.atimeMs = options.atimeMs;\n if (options.mtimeMs !== undefined) node.mtimeMs = options.mtimeMs;\n node.ctimeMs = Date.now();\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n return Object.freeze(this.snapshot(node));\n }\n\n async writeFileConditional(path: string, data: Uint8Array, options: ConditionalWriteFileOptions): Promise<FileStat> {\n options.signal?.throwIfAborted();\n const location = this.entry(path, \"writeFileConditional\", true);\n this.expectEntry(location.parent, options.parent, path, false);\n this.expectEntry(location.node, options.expected, path);\n if (location.node && location.node.type !== \"file\") this.fail(\"EINVAL\", \"writeFileConditional\", path);\n this.writeData(path, data, { ...(options.mode === undefined ? {} : { mode: options.mode }), flag: options.append ? \"a\" : \"w\" }, \"writeFileConditional\");\n return Object.freeze(this.snapshot(location.parent.entries.get(location.name)!));\n }\n\n async removeEntryConditional(path: string, options: ConditionalRemoveEntryOptions): Promise<void> {\n options.signal?.throwIfAborted();\n const location = this.entry(path, \"removeEntryConditional\", true);\n this.expectEntry(location.parent, options.parent, path, false);\n this.expectEntry(location.node, options.expected, path);\n const node = location.node!;\n if (this.terminalDot(path)) this.fail(\"EINVAL\", \"removeEntryConditional\", path);\n if (node === this.root) this.fail(\"EBUSY\", \"removeEntryConditional\", path);\n if (node.type !== \"file\" && node.type !== \"symlink\" && node.type !== \"directory\") this.fail(\"EINVAL\", \"removeEntryConditional\", path);\n this.permission(location.parent, 3, \"removeEntryConditional\", path);\n if (node.type === \"directory\" && node.entries.size > 0) this.fail(\"ENOTEMPTY\", \"removeEntryConditional\", path);\n location.parent.entries.delete(location.name);\n this.ledger.release(location.name.length * 2, 1);\n node.nlink--;\n node.ctimeMs = Date.now();\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n this.releaseNode(node);\n this.changed(location.parent);\n }\n\n async removeFileConditional(path: string, options: ConditionalRemoveFileOptions): Promise<void> {\n options.signal?.throwIfAborted();\n const location = this.entry(path, \"removeFileConditional\", true);\n this.expectEntry(location.parent, options.parent, path, false);\n this.expectEntry(location.node, options.expected, path);\n const node = location.node!;\n if (node.type !== \"file\") this.fail(\"EINVAL\", \"removeFileConditional\", path);\n this.permission(location.parent, 3, \"removeFileConditional\", path);\n location.parent.entries.delete(location.name);\n this.ledger.release(location.name.length * 2, 1);\n node.nlink--;\n node.ctimeMs = Date.now();\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n this.releaseNode(node);\n this.changed(location.parent);\n }\n\n async removeTreeConditional(path: string, options: ConditionalRemoveEntryOptions): Promise<void> {\n options.signal?.throwIfAborted();\n const location = this.entry(path, \"removeTreeConditional\", true);\n this.expectEntry(location.parent, options.parent, path, false);\n this.expectEntry(location.node, options.expected, path, false);\n if (location.node?.type !== \"directory\") this.fail(\"ENOTDIR\", \"removeTreeConditional\", path);\n this.removeLocation(location, path, \"removeTreeConditional\", true);\n }\n\n async writeFile(path: string, data: Uint8Array, options: WriteFileOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n this.writeData(path, data, options, \"writeFile\");\n }\n\n async appendFile(path: string, data: Uint8Array, options: AppendFileOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n this.writeData(path, data, { ...options, flag: \"a\" }, \"appendFile\");\n }\n\n async stat(path: string, options: FsOptions = {}): Promise<FileStat> {\n options.signal?.throwIfAborted();\n return this.snapshot(this.resolve(path, \"stat\").node!);\n }\n\n async lstat(path: string, options: FsOptions = {}): Promise<FileStat> {\n options.signal?.throwIfAborted();\n const stat = this.snapshot(this.resolve(path, \"lstat\", { followFinal: false }).node!);\n ownedStats.set(stat, { filesystem: this, path, root: this.root });\n return stat;\n }\n\n async readdir(path: string, options: ReadDirectoryOptions = {}): Promise<DirectoryEntry[]> {\n const limit = directoryEntryLimit(options, path);\n const node = this.resolve(path, \"readdir\").node!;\n if (node.type !== \"directory\") this.fail(\"ENOTDIR\", \"readdir\", path);\n this.permission(node, 4, \"readdir\", path);\n admitDirectoryEntries(node.entries.size, limit, path);\n node.atimeMs = Date.now();\n return [...node.entries].map(([name, entry]) => ({ name, type: entry.type }))\n .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);\n }\n\n async mkdir(path: string, options: MkdirOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n this.validatePath(path, \"mkdir\");\n const mode = this.mode(options.mode, 0o777, \"mkdir\", path);\n if (options.recursive) {\n const node = this.resolve(path, \"mkdir\", { createDirectories: mode }).node!;\n if (node.type !== \"directory\") this.fail(\"EEXIST\", \"mkdir\", path);\n return;\n }\n const location = this.resolve(path.replace(/\\/+$/, \"\") || \"/\", \"mkdir\", { allowMissing: true, followFinal: false });\n if (location.node) this.fail(\"EEXIST\", \"mkdir\", path);\n this.permission(location.parent, 3, \"mkdir\", path);\n this.addNode(location.parent, location.name, () => this.directory(mode), \"mkdir\", path);\n }\n\n async rmdir(path: string, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n const location = this.entry(path, \"rmdir\");\n const node = location.node!;\n if (this.terminalDot(path)) this.fail(\"EINVAL\", \"rmdir\", path);\n if (node === this.root) this.fail(\"EBUSY\", \"rmdir\", path);\n if (node.type !== \"directory\") this.fail(\"ENOTDIR\", \"rmdir\", path);\n this.permission(location.parent, 3, \"rmdir\", path);\n if (node.entries.size > 0) this.fail(\"ENOTEMPTY\", \"rmdir\", path);\n location.parent.entries.delete(location.name);\n this.ledger.release(location.name.length * 2, 1);\n node.nlink = 0;\n node.ctimeMs = Date.now();\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n this.releaseNode(node);\n this.changed(location.parent);\n }\n\n async rm(path: string, options: RemoveOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n let location: Location;\n try {\n location = this.entry(path, \"rm\");\n } catch (error) {\n if (options.force && error instanceof FsError && error.code === \"ENOENT\") return;\n throw error;\n }\n this.removeLocation(location, path, \"rm\", options.recursive === true);\n }\n\n private removeLocation(location: Location, path: string, syscall: string, recursive: boolean): void {\n const node = location.node!;\n if (this.terminalDot(path)) this.fail(\"EINVAL\", syscall, path);\n if (node === this.root) this.fail(\"EBUSY\", syscall, path);\n this.permission(location.parent, 3, syscall, path);\n if (node.type === \"directory\" && !recursive) this.fail(\"EISDIR\", syscall, path);\n const removed: MemoryNode[] = [node];\n for (let index = 0; index < removed.length; index++) {\n const entry = removed[index]!;\n if (entry.type === \"directory\" && entry.entries.size > 0) {\n this.permission(entry, 7, syscall, path);\n for (const child of entry.entries.values()) removed.push(child);\n }\n }\n location.parent.entries.delete(location.name);\n this.ledger.release(location.name.length * 2, 1);\n for (const entry of removed) {\n if (entry.type === \"directory\") {\n for (const name of entry.entries.keys()) this.ledger.release(name.length * 2, 1);\n entry.entries.clear();\n }\n entry.nlink--;\n entry.ctimeMs = Date.now();\n entry.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, entry.revision + 1);\n this.releaseNode(entry);\n }\n this.changed(location.parent);\n }\n\n unlink(path: string, options: FsOptions = {}): Promise<void> {\n // Do not allow an untyped recursive option to widen final-entry removal.\n return this.rm(path, { ...(options.signal === undefined ? {} : { signal: options.signal }) });\n }\n\n async rename(source: string, destination: string, options: RenameOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n try {\n const origin = this.entry(source, \"rename\");\n const target = this.entry(destination, \"rename\", true);\n const node = origin.node!;\n if (this.terminalDot(source) || this.terminalDot(destination)) this.fail(\"EINVAL\", \"rename\", source, destination);\n if (node === this.root || target.node === this.root) this.fail(\"EBUSY\", \"rename\", source, destination);\n if (destination.endsWith(\"/\") && node.type !== \"directory\") this.fail(\"ENOTDIR\", \"rename\", source, destination);\n if (options.noReplace && target.node) this.fail(\"EEXIST\", \"rename\", source, destination);\n if (target.node === node) return;\n if (node.type === \"directory\" && target.path.startsWith(`${origin.path}/`)) this.fail(\"EINVAL\", \"rename\", source, destination);\n this.permission(origin.parent, 3, \"rename\", source);\n this.permission(target.parent, 3, \"rename\", destination);\n if (target.node) {\n if (node.type === \"directory\" && target.node.type !== \"directory\") this.fail(\"ENOTDIR\", \"rename\", source, destination);\n if (node.type !== \"directory\" && target.node.type === \"directory\") this.fail(\"EISDIR\", \"rename\", source, destination);\n if (target.node.type === \"directory\" && target.node.entries.size > 0) this.fail(\"ENOTEMPTY\", \"rename\", source, destination);\n }\n const nameGrowth = target.node ? 0 : (target.name.length - origin.name.length) * 2;\n this.ledger.reserve(Math.max(0, nameGrowth), 0, \"rename\", source);\n try { target.parent.entries.set(target.name, node); }\n catch (error) { this.ledger.release(Math.max(0, nameGrowth), 0); throw error; }\n origin.parent.entries.delete(origin.name);\n if (target.node) {\n this.ledger.release(origin.name.length * 2, 1);\n target.node.nlink--;\n target.node.ctimeMs = Date.now();\n target.node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, target.node.revision + 1);\n this.releaseNode(target.node);\n } else if (nameGrowth < 0) this.ledger.release(-nameGrowth, 0);\n this.changed(origin.parent);\n this.changed(target.parent);\n node.ctimeMs = Date.now();\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n } catch (error) {\n if (error instanceof FsError) throw new FsError(error.code, { syscall: \"rename\", path: source, dest: destination, cause: error });\n throw error;\n }\n }\n\n async copyFile(source: string, destination: string, options: CopyFileOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n try {\n const origin = this.file(source, \"copyFile\");\n this.permission(origin, 4, \"copyFile\", source);\n const target = this.resolve(destination, \"copyFile\", { followFinal: !options.exclusive, allowMissing: true });\n if (target.node && options.exclusive) this.fail(\"EEXIST\", \"copyFile\", source, destination);\n if (target.node === origin) this.fail(\"EINVAL\", \"copyFile\", source, destination);\n const node = this.writeData(destination, origin.data, { mode: origin.mode & 0o7777, flag: options.exclusive ? \"wx\" : \"w\" }, \"copyFile\");\n node.mode = origin.mode;\n origin.atimeMs = Date.now();\n } catch (error) {\n if (error instanceof FsError) throw new FsError(error.code, { syscall: \"copyFile\", path: source, dest: destination, cause: error });\n throw error;\n }\n }\n\n async realpath(path: string, options: FsOptions = {}): Promise<string> {\n options.signal?.throwIfAborted();\n return this.resolve(path, \"realpath\").path;\n }\n\n async access(path: string, mode = 0, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n if (!Number.isInteger(mode) || mode < 0 || mode > 7) this.fail(\"EINVAL\", \"access\", path);\n this.permission(this.resolve(path, \"access\").node!, mode, \"access\", path);\n }\n\n async readlink(path: string, options: FsOptions = {}): Promise<string> {\n options.signal?.throwIfAborted();\n const node = this.resolve(path, \"readlink\", { followFinal: false }).node!;\n if (node.type !== \"symlink\") this.fail(\"EINVAL\", \"readlink\", path);\n return node.target;\n }\n\n async symlink(target: string, path: string, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n this.validatePath(target, \"symlink\");\n const location = this.resolve(path, \"symlink\", { followFinal: false, allowMissing: true });\n if (location.node) this.fail(\"EEXIST\", \"symlink\", path);\n this.permission(location.parent, 3, \"symlink\", path);\n this.addNode(location.parent, location.name, (): SymlinkNode => ({\n ...this.metadata(typeModes.symlink | 0o777), type: \"symlink\", target,\n }), \"symlink\", path, target.length * 2);\n }\n\n async link(existingPath: string, newPath: string, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n const node = this.resolve(existingPath, \"link\", { followFinal: false }).node!;\n if (node.type === \"directory\") this.fail(\"EPERM\", \"link\", existingPath, newPath);\n const target = this.resolve(newPath, \"link\", { followFinal: false, allowMissing: true });\n if (target.node) this.fail(\"EEXIST\", \"link\", existingPath, newPath);\n this.permission(target.parent, 3, \"link\", newPath);\n this.ledger.reserve(target.name.length * 2, 1, \"link\", newPath);\n try { target.parent.entries.set(target.name, node); }\n catch (error) { this.ledger.release(target.name.length * 2, 1); throw error; }\n node.nlink++;\n node.ctimeMs = Date.now();\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n this.changed(target.parent);\n }\n\n async chmod(path: string, mode: number, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n const permissions = this.mode(mode, 0, \"chmod\", path);\n const node = this.resolve(path, \"chmod\").node!;\n node.mode = typeModes[node.type] | permissions;\n node.ctimeMs = Date.now();\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n }\n\n async utimes(path: string, atimeMs: number, mtimeMs: number, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n if (!Number.isFinite(atimeMs) || !Number.isFinite(mtimeMs)) this.fail(\"EINVAL\", \"utimes\", path);\n const node = this.resolve(path, \"utimes\").node!;\n node.atimeMs = atimeMs;\n node.mtimeMs = mtimeMs;\n node.ctimeMs = Date.now();\n node.revision = Math.min(Number.MAX_SAFE_INTEGER + 1, node.revision + 1);\n }\n\n async truncate(path: string, length = 0, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n this.integer(length, \"truncate\", path);\n const node = this.file(path, \"truncate\");\n this.permission(node, 2, \"truncate\", path);\n this.resizeNode(node, length, \"truncate\", path);\n }\n\n private resizeNode(node: FileNode, length: number, syscall: string, path: string): void {\n this.admitSize(node, length, syscall, path);\n const data = this.allocate(length, syscall, path);\n try { data.data.set(node.data.subarray(0, length)); }\n catch (error) { data.release(); throw error; }\n this.replaceData(node, data);\n this.changed(node);\n }\n\n async openResizeFile(path: string, options: OpenResizeFileOptions = {}): Promise<FileResizeHandle> {\n options.signal?.throwIfAborted();\n if (!stockRetainedResize(this)) throw new FsError(\"ENOTSUP\", { syscall: \"openResizeFile\", path });\n const location = this.resolve(path, \"openResizeFile\", { allowMissing: options.create === true, resizeCreate: options.create ?? false });\n let mode = 0o666;\n if (location.node) {\n if (location.node.type !== \"file\") this.fail(\"EISDIR\", \"openResizeFile\", path);\n this.permission(location.node, 2, \"openResizeFile\", path);\n } else {\n this.permission(location.parent, 3, \"openResizeFile\", path);\n mode = this.mode(options.mode, mode, \"openResizeFile\", path);\n }\n this.ledger.reserve(path.length * 2, 1, \"openResizeFile\", path);\n let node: FileNode | undefined;\n try {\n node = this.openWrite(path, {}, \"openResizeFile\", { location, mode, append: false });\n node.references++;\n } catch (error) {\n this.ledger.release(path.length * 2, 1);\n throw error;\n }\n const snapshot = this.snapshot.bind(this);\n const integer = this.integer.bind(this);\n const resizeNode = this.resizeNode.bind(this);\n const releaseReference = this.releaseReference.bind(this);\n let closing: Promise<void> | undefined;\n const current = (signal: AbortSignal | undefined, syscall: string): FileNode => {\n signal?.throwIfAborted();\n if (!node) throw new FsError(\"EBADF\", { syscall, path });\n return node;\n };\n return {\n async stat(options = {}) { return snapshot(current(options.signal, \"fstat\")); },\n async seekEnd(options = {}) { return BigInt(current(options.signal, \"lseek\").data.byteLength); },\n async truncate(length, options = {}) {\n const file = current(options.signal, \"ftruncate\");\n integer(length, \"ftruncate\", path);\n resizeNode(file, length, \"ftruncate\", path);\n },\n close() {\n if (!closing) {\n const retained = node;\n node = undefined;\n closing = Promise.resolve().then(() => { if (retained) releaseReference(retained, path); });\n }\n return closing;\n },\n };\n }\n\n async openReadFile(path: string, options: OpenReadFileOptions = {}): Promise<FileReadHandle> {\n const signal = options.signal;\n signal?.throwIfAborted();\n const allowDirectory = options.allowDirectory === true;\n signal?.throwIfAborted();\n const unsupported = (): never => { throw new FsError(\"ENOTSUP\", { syscall: \"openReadFile\", path }); };\n const owner = ownedStores.get(this);\n if (!owner || Object.getPrototypeOf(this) !== MemoryFileSystem.prototype\n || Object.getOwnPropertyDescriptor(this, \"root\")?.value !== owner.root\n || Object.getOwnPropertyDescriptor(this, \"ledger\")?.value !== owner.ledger) unsupported();\n for (const name of [\"openReadFile\", \"readFile\", \"readStream\", \"stat\", \"lstat\", \"realpath\", \"access\",\n \"file\", \"resolve\", \"permission\", \"validatePath\", \"fail\", \"snapshot\", \"integer\", \"releaseReference\", \"releaseNode\"]) {\n const descriptor = Object.getOwnPropertyDescriptor(this, name)\n ?? Object.getOwnPropertyDescriptor(MemoryFileSystem.prototype, name);\n if (!descriptor || !(\"value\" in descriptor) || descriptor.value !== memoryImplementation[name]?.value) unsupported();\n }\n const retainedRead = Object.getOwnPropertyDescriptor(this, \"capabilities\")?.value?.retainedRead;\n signal?.throwIfAborted();\n if (retainedRead !== true) unsupported();\n const selected = allowDirectory ? this.resolve(path, \"openReadFile\").node! : this.file(path, \"openReadFile\");\n if (selected.type !== \"file\" && selected.type !== \"directory\") this.fail(\"EISDIR\", \"openReadFile\", path);\n let node: FileNode | DirectoryNode | undefined = selected;\n this.permission(node, 4, \"openReadFile\", path);\n signal?.throwIfAborted();\n this.ledger.reserve(path.length * 2, 1, \"openReadFile\", path);\n node.references++;\n const snapshot = this.snapshot.bind(this);\n const integer = this.integer.bind(this);\n const releaseReference = this.releaseReference.bind(this);\n let closing: Promise<void> | undefined;\n const current = (signal: AbortSignal | undefined, syscall: string): FileNode | DirectoryNode => {\n signal?.throwIfAborted();\n if (!node) throw new FsError(\"EBADF\", { syscall, path });\n return node;\n };\n return {\n async stat(options = {}) {\n return snapshot(current(options.signal, \"fstat\"));\n },\n async seekEnd(options = {}) {\n const file = current(options.signal, \"lseek\");\n return file.type === \"directory\" ? ext4HtreeEof64 : BigInt(file.data.byteLength);\n },\n async read(position, maxBytes, options = {}) {\n const file = current(options.signal, \"read\");\n integer(position, \"read\", path);\n integer(maxBytes, \"read\", path);\n if (maxBytes === 0 || maxBytes > Number.MAX_SAFE_INTEGER - position) {\n throw new FsError(\"EINVAL\", { syscall: \"read\", path });\n }\n if (file.type === \"directory\") throw new FsError(\"EISDIR\", { syscall: \"read\", path });\n const bytes = file.data.slice(position, position + maxBytes);\n file.atimeMs = Date.now();\n return bytes;\n },\n close() {\n if (node) {\n releaseReference(node, path);\n node = undefined;\n }\n closing ??= Promise.resolve();\n return closing;\n },\n };\n }\n\n async *readStream(path: string, options: ReadStreamOptions = {}): ByteSource {\n options.signal?.throwIfAborted();\n const start = options.start ?? 0;\n const chunkSize = options.chunkSize ?? preferredIoBlockSize;\n this.integer(start, \"readStream\", path);\n this.integer(chunkSize, \"readStream\", path);\n if (chunkSize === 0) this.fail(\"EINVAL\", \"readStream\", path);\n if (options.endExclusive !== undefined) {\n this.integer(options.endExclusive, \"readStream\", path);\n if (options.endExclusive < start) this.fail(\"EINVAL\", \"readStream\", path);\n }\n const node = this.file(path, \"readStream\");\n this.permission(node, 4, \"readStream\", path);\n this.ledger.reserve(path.length * 2, 1, \"readStream\", path);\n node.references++;\n const allocation = node.allocation;\n allocation.retain();\n const data = node.data;\n try {\n const end = Math.min(options.endExclusive ?? data.byteLength, data.byteLength);\n node.atimeMs = Date.now();\n for (let offset = start; offset < end; offset += chunkSize) {\n options.signal?.throwIfAborted();\n yield data.slice(offset, Math.min(offset + chunkSize, end));\n }\n options.signal?.throwIfAborted();\n } finally {\n allocation.release();\n this.releaseReference(node, path);\n }\n }\n\n async writeStream(path: string, source: ByteSource, options: WriteFileOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n this.validatePath(path, \"writeStream\");\n this.ledger.reserve(path.length * 2, 1, \"writeStream\", path);\n let node: FileNode | undefined;\n try {\n node = this.openWrite(path, options, \"writeStream\");\n node.references++;\n const append = options.flag === \"a\" || options.flag === \"ax\";\n let position = 0;\n if (!append) {\n this.replaceData(node, new MemoryAllocation(new Uint8Array(), this.ledger));\n this.changed(node);\n }\n for await (const chunk of source) {\n options.signal?.throwIfAborted();\n if (!(chunk instanceof Uint8Array)) throw new TypeError(\"Memory files require Uint8Array data\");\n this.writeAt(node, chunk, append ? node.data.byteLength : position, \"writeStream\", path);\n if (!append) position += chunk.byteLength;\n }\n options.signal?.throwIfAborted();\n } finally {\n if (node) this.releaseReference(node, path);\n else this.ledger.release(path.length * 2, 1);\n }\n }\n}\n\nconst memoryImplementation = Object.getOwnPropertyDescriptors(MemoryFileSystem.prototype);\n\nfunction stockDescriptorWrite(filesystem: MemoryFileSystem): boolean {\n if (Object.getPrototypeOf(filesystem) !== MemoryFileSystem.prototype) return false;\n const owner = ownedStores.get(filesystem);\n if (!owner || Object.getOwnPropertyDescriptor(filesystem, \"root\")?.value !== owner.root\n || Object.getOwnPropertyDescriptor(filesystem, \"capabilities\")?.value !== owner.capabilities) return false;\n for (const name of [\"writeStream\", \"writeFile\", \"appendFile\", \"access\", \"stat\", \"lstat\", \"realpath\",\n \"openWrite\", \"prepareWrite\", \"writeData\", \"addNode\", \"replaceData\", \"releaseReference\", \"releaseNode\",\n \"resolve\", \"permission\", \"validatePath\", \"mode\", \"bytes\", \"allocate\", \"admitSize\", \"changed\", \"metadata\", \"integer\", \"writeAt\", \"fail\"]) {\n const descriptor = Object.getOwnPropertyDescriptor(filesystem, name)\n ?? Object.getOwnPropertyDescriptor(MemoryFileSystem.prototype, name);\n if (!descriptor || !(\"value\" in descriptor) || descriptor.value !== memoryImplementation[name]?.value) return false;\n }\n return true;\n}\n\nfunction stockRetainedResize(filesystem: MemoryFileSystem): boolean {\n if (!stockDescriptorWrite(filesystem)) return false;\n const owner = ownedStores.get(filesystem);\n if (!owner || Object.getOwnPropertyDescriptor(filesystem, \"ledger\")?.value !== owner.ledger) return false;\n for (const name of [\"openResizeFile\", \"truncate\", \"resizeNode\", \"snapshot\"]) {\n const descriptor = Object.getOwnPropertyDescriptor(filesystem, name)\n ?? Object.getOwnPropertyDescriptor(MemoryFileSystem.prototype, name);\n if (!descriptor || !(\"value\" in descriptor) || descriptor.value !== memoryImplementation[name]?.value) return false;\n }\n return true;\n}\n\nexport function createMemoryFileSystem(options: MemoryFileSystemOptions | Readonly<Record<string, unknown>> = {}): MemoryFileSystem {\n return new MemoryFileSystem(normalizeMemoryFileSystemLimits(options));\n}\n", "import { FsError } from \"../contracts/errors.js\";\nimport type { FileSystem, FsOptions } from \"../contracts/filesystem.js\";\nimport { normalizePath, validatePath } from \"../contracts/virtual-path.js\";\n\nexport const pathNamespace = Symbol.for(\"@poe-code/safe-fs/path-namespace/v1\");\nconst captureNamespace = Symbol.for(\"@poe-code/safe-fs/capture-path-namespace/v1\");\n\nexport function capturePathNamespace(filesystem: FileSystem, options: FsOptions): ((path: string) => string) | undefined {\n options.signal?.throwIfAborted();\n const projection: unknown = Reflect.get(filesystem, pathNamespace);\n options.signal?.throwIfAborted();\n if (projection === undefined) return undefined;\n return captureProjection(projection, options);\n}\n\nexport function readOnlyPathNamespace(projection: unknown): object | undefined {\n if (projection === undefined) return undefined;\n const select = (path: string): string => captureProjection(projection, {})(path);\n Object.defineProperty(select, captureNamespace, {\n value: Object.freeze((options: FsOptions) => captureProjection(projection, options)),\n });\n return Object.freeze({ select: Object.freeze(select) });\n}\n\nfunction captureProjection(projection: unknown, options: FsOptions): (path: string) => string {\n options.signal?.throwIfAborted();\n if (projection === null || typeof projection !== \"object\") throw new FsError(\"EIO\");\n const frozen = Object.isFrozen(projection);\n options.signal?.throwIfAborted();\n if (!frozen) throw new FsError(\"EIO\");\n let select: unknown = Reflect.get(projection, \"select\");\n options.signal?.throwIfAborted();\n if (typeof select !== \"function\") throw new FsError(\"EIO\");\n const capture: unknown = Reflect.get(select, captureNamespace);\n options.signal?.throwIfAborted();\n let receiver: unknown = projection;\n if (capture !== undefined) {\n if (typeof capture !== \"function\") throw new FsError(\"EIO\");\n select = Reflect.apply(capture, select, [options]);\n options.signal?.throwIfAborted();\n if (typeof select !== \"function\") throw new FsError(\"EIO\");\n receiver = undefined;\n }\n const selected = select;\n return path => {\n options.signal?.throwIfAborted();\n const root: unknown = Reflect.apply(selected, receiver, [path]);\n options.signal?.throwIfAborted();\n if (typeof root !== \"string\" || !root.startsWith(\"/\")) throw new FsError(\"EIO\", { path });\n try { validatePath(root); }\n catch (cause) { throw new FsError(\"EIO\", { path, cause }); }\n if (normalizePath(root) !== root || root !== \"/\" && path !== root && !path.startsWith(`${root}/`)) throw new FsError(\"EIO\", { path });\n return root;\n };\n}\n", "import { FsError, isFsError } from \"../../contracts/errors.js\";\nimport type { FileStat, FileSystem, FsOptions } from \"../../contracts/filesystem.js\";\nimport { validatePath } from \"../../contracts/virtual-path.js\";\nimport { capturePathNamespace } from \"../path-namespace.js\";\n\nexport const nullPath = \"/dev/null\";\nexport const deviceDirectory = \"/dev\";\n\nexport function lexicalDevicePath(path: string): string {\n validatePath(path);\n const parts: string[] = [];\n for (const component of path.split(\"/\")) {\n if (`/${parts.join(\"/\")}` === nullPath) throw new FsError(\"ENOTDIR\", { path });\n if (component === \"..\") parts.pop();\n else if (component && component !== \".\") parts.push(component);\n }\n return `/${parts.join(\"/\")}`;\n}\n\nasync function resolveResizeDevicePath(filesystem: FileSystem, path: string, options: FsOptions, create: boolean, namespace: ((path: string) => string) | undefined): Promise<string> {\n validatePath(path);\n const components = (value: string) => {\n const result = value.split(\"/\").filter(Boolean);\n if (value.endsWith(\"/\")) result.push(\"\");\n return result;\n };\n const pending = components(path);\n const parts: string[] = [];\n let links = 0;\n let expanded = path.length;\n let boundary: string | undefined;\n while (pending.length) {\n options.signal?.throwIfAborted();\n const component = pending.shift()!;\n const current = `/${parts.join(\"/\")}`;\n if (current === nullPath) throw new FsError(\"ENOTDIR\", { path });\n if (current !== deviceDirectory) {\n const observe = filesystem.stat;\n options.signal?.throwIfAborted();\n const stat = await Reflect.apply(observe, filesystem, [current, options]);\n options.signal?.throwIfAborted();\n if (stat.type !== \"directory\") throw new FsError(\"ENOTDIR\", { path });\n if (!(component === \"\" && pending.length === 0)) {\n const access = filesystem.access;\n options.signal?.throwIfAborted();\n await Reflect.apply(access, filesystem, [current, 1, options]);\n options.signal?.throwIfAborted();\n }\n }\n if (component === \".\" || component === \"\") continue;\n if (component === \"..\") {\n if (boundary !== undefined && current === boundary) throw new FsError(\"EACCES\", { path });\n parts.pop();\n continue;\n }\n if (new TextEncoder().encode(component).byteLength > 255) throw new FsError(\"ENAMETOOLONG\", { path });\n const candidate = `/${[...parts, component].join(\"/\")}`;\n const selected = namespace === undefined ? undefined : candidate === deviceDirectory || candidate === nullPath ? \"/\" : namespace(candidate);\n if (boundary !== undefined && selected !== boundary) throw new FsError(\"EACCES\", { path });\n if (create && pending.length === 1 && pending[0] === \"\") throw new FsError(\"EISDIR\", { path });\n if (candidate !== deviceDirectory && candidate !== nullPath) {\n let stat: FileStat | undefined;\n const lstat = filesystem.lstat;\n options.signal?.throwIfAborted();\n try { stat = await Reflect.apply(lstat, filesystem, [candidate, options]); }\n catch (error) {\n options.signal?.throwIfAborted();\n if (!(isFsError(error, \"ENOENT\") && create && pending.length === 0)) throw error;\n }\n options.signal?.throwIfAborted();\n if (stat?.type === \"symlink\") {\n boundary ??= selected;\n const readlink = filesystem.readlink;\n options.signal?.throwIfAborted();\n if (typeof readlink !== \"function\") throw new FsError(\"ENOTSUP\", { path });\n if (++links > 40) throw new FsError(\"ELOOP\", { path });\n const target = await Reflect.apply(readlink, filesystem, [candidate, options]);\n options.signal?.throwIfAborted();\n validatePath(target);\n expanded += target.length;\n if (expanded > 65536) throw new FsError(\"ENAMETOOLONG\", { path });\n if (target.startsWith(\"/\")) parts.splice(0, parts.length, ...(boundary ?? \"/\").split(\"/\").filter(Boolean));\n const targetParts = components(target);\n if (targetParts.at(-1) === \"\" && pending[0] === \"\") targetParts.pop();\n pending.unshift(...targetParts);\n continue;\n }\n }\n parts.push(component);\n }\n return `/${parts.join(\"/\")}`;\n}\n\nexport async function resolveDevicePath(filesystem: FileSystem, path: string, options: FsOptions, followFinal = true, resizeCreate?: boolean): Promise<string> {\n options.signal?.throwIfAborted();\n const namespace = capturePathNamespace(filesystem, options);\n if (resizeCreate !== undefined) return resolveResizeDevicePath(filesystem, path, options, resizeCreate, namespace);\n const lexical = lexicalDevicePath(path);\n const lstat = filesystem.lstat;\n options.signal?.throwIfAborted();\n const aliases = typeof lstat === \"function\";\n if (!aliases && lexical !== nullPath && lexical !== deviceDirectory && lexical !== \"/\") return lexical;\n const pending = path.split(\"/\");\n const parts: string[] = [];\n let links = 0;\n let expanded = path.length;\n let absolute = path.startsWith(\"/\");\n let traversalFailure: FsError | undefined;\n let boundary: string | undefined;\n while (pending.length) {\n options.signal?.throwIfAborted();\n if (`/${parts.join(\"/\")}` === nullPath) throw new FsError(\"ENOTDIR\", { path });\n const component = pending.shift()!;\n if (!component || component === \".\") continue;\n if (component === \"..\") {\n if (boundary !== undefined && `/${parts.join(\"/\")}` === boundary) throw new FsError(\"EACCES\", { path });\n parts.pop();\n continue;\n }\n const candidate = `/${[...parts, component].join(\"/\")}`;\n const selected = namespace === undefined ? undefined : candidate === deviceDirectory || candidate === nullPath ? \"/\" : namespace(candidate);\n if (boundary !== undefined && selected !== boundary) throw new FsError(\"EACCES\", { path });\n if (candidate !== deviceDirectory && candidate !== nullPath && ((followFinal && aliases) || pending.length)) {\n const lookup = absolute ? candidate : candidate.slice(1);\n let stat: FileStat | undefined;\n try {\n if (typeof lstat !== \"function\") throw new FsError(\"ENOTSUP\", { path });\n stat = await Reflect.apply(lstat, filesystem, [lookup, options]);\n } catch (error) {\n options.signal?.throwIfAborted();\n if (isFsError(error, \"ENOTSUP\") && links === 0 && lexical !== nullPath && lexical !== deviceDirectory && lexical !== \"/\") return lexical;\n if (!isFsError(error, \"ENOENT\")) throw error;\n if (pending.length) traversalFailure ??= error;\n }\n options.signal?.throwIfAborted();\n if (stat?.type === \"symlink\") {\n boundary ??= selected;\n const readlink = filesystem.readlink;\n options.signal?.throwIfAborted();\n if (typeof readlink !== \"function\") throw new FsError(\"ENOTSUP\", { path });\n if (++links > 40) throw new FsError(\"ELOOP\", { path });\n const target = await Reflect.apply(readlink, filesystem, [lookup, options]);\n options.signal?.throwIfAborted();\n validatePath(target);\n expanded += target.length;\n if (expanded > 65536) throw new FsError(\"ENAMETOOLONG\", { path });\n if (target.startsWith(\"/\")) {\n parts.splice(0, parts.length, ...(boundary ?? \"/\").split(\"/\").filter(Boolean));\n absolute = true;\n }\n pending.unshift(...target.split(\"/\"));\n continue;\n }\n if (stat && pending.length && stat.type !== \"directory\") traversalFailure ??= new FsError(\"ENOTDIR\", { path });\n }\n parts.push(component);\n }\n const resolved = `/${parts.join(\"/\")}`;\n if (traversalFailure && (resolved === nullPath || resolved === deviceDirectory || resolved === \"/\")) throw traversalFailure;\n return resolved;\n}\n", "import type { ByteSource } from \"../../contracts/io.js\";\nimport { finishCleanup } from \"../../contracts/cleanup.js\";\nimport type { FileReadHandle } from \"../../contracts/filesystem.js\";\n\nexport function deviceReadStream(open: () => Promise<ByteSource>, signal?: AbortSignal): ByteSource {\n return { [Symbol.asyncIterator]() {\n let opened: Promise<AsyncIterator<Uint8Array>> | undefined;\n let closing: Promise<IteratorResult<Uint8Array>> | undefined;\n const iterator = () => opened ??= open().then(source => source[Symbol.asyncIterator]());\n const close = () => closing ??= iterator().then(async source => source.return ? source.return() : { done: true, value: undefined });\n return {\n async next() {\n if (closing) { await closing; return { done: true, value: undefined }; }\n try {\n const source = await iterator();\n signal?.throwIfAborted();\n if (closing) { await closing; return { done: true, value: undefined }; }\n const next = source.next;\n signal?.throwIfAborted();\n if (closing) { await closing; return { done: true, value: undefined }; }\n return await Reflect.apply(next, source, []);\n }\n catch (error) { await finishCleanup(close, true); throw error; }\n },\n return: close,\n };\n } };\n}\n\nexport async function drainDeviceFile(handle: FileReadHandle, signal?: AbortSignal): Promise<void> {\n let failed = false;\n let position = 0;\n try {\n await drainDeviceInput({ [Symbol.asyncIterator]: () => ({ async next() {\n const value = await handle.read(position, 65536, signal ? { signal } : {});\n if (!(value instanceof Uint8Array) || value.byteLength > 65536) throw new TypeError(\"Retained reads must return bounded Uint8Array chunks\");\n position += value.byteLength;\n if (!Number.isSafeInteger(position)) throw new RangeError(\"Retained read position exceeds safe integer range\");\n return { done: value.byteLength === 0, value };\n } }) }, signal);\n } catch (error) { failed = true; throw error; }\n finally {\n await finishCleanup(async () => {\n try { await handle.close(); }\n catch (error) { signal?.throwIfAborted(); throw error; }\n }, failed);\n }\n signal?.throwIfAborted();\n}\n\nfunction nextChunk(iterator: AsyncIterator<Uint8Array>, signal?: AbortSignal): Promise<IteratorResult<Uint8Array>> {\n signal?.throwIfAborted();\n return new Promise((resolve, reject) => {\n const aborted = () => { signal?.removeEventListener(\"abort\", aborted); reject(signal?.reason); };\n signal?.addEventListener(\"abort\", aborted, { once: true });\n try {\n Promise.resolve(iterator.next()).then(result => {\n signal?.removeEventListener(\"abort\", aborted);\n if (signal?.aborted) reject(signal.reason);\n else resolve(result);\n }, error => { signal?.removeEventListener(\"abort\", aborted); reject(signal?.aborted ? signal.reason : error); });\n } catch (error) { signal?.removeEventListener(\"abort\", aborted); reject(signal?.aborted ? signal.reason : error); }\n });\n}\n\nexport async function drainDeviceInput(source: ByteSource, signal?: AbortSignal): Promise<void> {\n signal?.throwIfAborted();\n const iterator = source[Symbol.asyncIterator]();\n let failed = false;\n let bytes = 0;\n let pulls = 0;\n try {\n for (;;) {\n const result = await nextChunk(iterator, signal);\n signal?.throwIfAborted();\n if (result.done) break;\n if (!(result.value instanceof Uint8Array)) throw new TypeError(\"Byte sources must yield Uint8Array chunks\");\n bytes += result.value.byteLength;\n if (++pulls >= 64 || bytes >= 65536) {\n await new Promise<void>(resolve => setTimeout(resolve, 0));\n signal?.throwIfAborted();\n bytes = 0;\n pulls = 0;\n }\n }\n } catch (error) {\n failed = true;\n throw error;\n } finally {\n await finishCleanup(async () => {\n try { await iterator.return?.(); }\n catch (error) { signal?.throwIfAborted(); throw error; }\n }, failed);\n }\n signal?.throwIfAborted();\n}\n", "import type { FsOptions, FileReadHandle, FileResizeHandle, FileSystem, FileSystemCapabilities, OpenReadFileOptions, OpenResizeFileOptions } from \"../contracts/filesystem.js\";\nimport { FsError } from \"../contracts/errors.js\";\nimport { finishCleanup } from \"../contracts/cleanup.js\";\n\nexport function retainedReadCapabilities(filesystem: FileSystem, capabilities = filesystem.capabilities): FileSystemCapabilities {\n return typeof filesystem.openReadFile === \"function\" ? capabilities : { ...capabilities, retainedRead: false };\n}\n\nexport async function openRetainedReadFile(filesystem: FileSystem, path: string, options: OpenReadFileOptions): Promise<FileReadHandle> {\n const signal = options.signal;\n let handle: FileReadHandle | undefined;\n try {\n signal?.throwIfAborted();\n const available = typeof filesystem.openReadFile === \"function\";\n signal?.throwIfAborted();\n if (!available) throw new FsError(\"ENOTSUP\", { syscall: \"openReadFile\", path });\n const query = filesystem.capabilitiesFor;\n signal?.throwIfAborted();\n const metadata = Promise.resolve(query == null ? undefined : Reflect.apply(query, filesystem, [path, options]));\n const queried = await (signal ? new Promise<FileSystemCapabilities | undefined>((resolve, reject) => {\n const abort = (): void => { signal.removeEventListener(\"abort\", abort); reject(signal.reason); };\n signal.addEventListener(\"abort\", abort, { once: true });\n metadata.then(\n value => { signal.removeEventListener(\"abort\", abort); resolve(value); },\n error => { signal.removeEventListener(\"abort\", abort); reject(error); },\n );\n if (signal.aborted) abort();\n }) : metadata);\n signal?.throwIfAborted();\n const capabilities = queried ?? filesystem.capabilities;\n signal?.throwIfAborted();\n const supported = capabilities.retainedRead;\n signal?.throwIfAborted();\n if (supported !== true) throw new FsError(\"ENOTSUP\", { syscall: \"openReadFile\", path });\n const acquire = filesystem.openReadFile;\n signal?.throwIfAborted();\n if (typeof acquire !== \"function\") throw new FsError(\"ENOTSUP\", { syscall: \"openReadFile\", path });\n handle = await Reflect.apply(acquire, filesystem, [path, options]);\n signal?.throwIfAborted();\n return handle;\n } catch (error) {\n if (handle) await finishCleanup(() => handle!.close(), true);\n signal?.throwIfAborted();\n throw error;\n }\n}\n\nexport function requireCapabilities(...values: readonly (boolean | undefined)[]): boolean | undefined {\n return values.some(value => value === false) ? false : values.every(value => value === true) ? true : undefined;\n}\n\nexport function retainedResizeCapabilities(filesystem: FileSystem, capabilities = filesystem.capabilities): FileSystemCapabilities {\n if (capabilities.retainedResize !== true) return capabilities;\n return typeof filesystem.openResizeFile === \"function\" && capabilities.readOnly !== true\n ? capabilities : { ...capabilities, retainedResize: false };\n}\n\nexport async function openRetainedResizeFile(filesystem: FileSystem, path: string, options: OpenResizeFileOptions): Promise<FileResizeHandle> {\n const signal = options.signal;\n let handle: FileResizeHandle | undefined;\n try {\n signal?.throwIfAborted();\n const available = typeof filesystem.openResizeFile === \"function\";\n signal?.throwIfAborted();\n if (!available) throw new FsError(\"ENOTSUP\", { syscall: \"openResizeFile\", path });\n const query = filesystem.capabilitiesFor;\n signal?.throwIfAborted();\n const intent = { ...(signal === undefined ? {} : { signal }), create: options.create === true };\n signal?.throwIfAborted();\n const metadata = Promise.resolve(query === undefined ? filesystem.capabilities : Reflect.apply(query, filesystem, [path, intent]));\n const capabilities = await (signal ? new Promise<FileSystemCapabilities>((resolve, reject) => {\n const abort = (): void => { signal.removeEventListener(\"abort\", abort); reject(signal.reason); };\n signal.addEventListener(\"abort\", abort, { once: true });\n metadata.then(\n value => { signal.removeEventListener(\"abort\", abort); resolve(value); },\n error => { signal.removeEventListener(\"abort\", abort); reject(error); },\n );\n if (signal.aborted) abort();\n }) : metadata);\n signal?.throwIfAborted();\n const readOnly = capabilities.readOnly;\n signal?.throwIfAborted();\n if (readOnly === true) throw new FsError(\"EROFS\", { syscall: \"openResizeFile\", path });\n const supported = capabilities.retainedResize;\n signal?.throwIfAborted();\n if (supported !== true) throw new FsError(\"ENOTSUP\", { syscall: \"openResizeFile\", path });\n const acquire = filesystem.openResizeFile;\n signal?.throwIfAborted();\n if (typeof acquire !== \"function\") throw new FsError(\"ENOTSUP\", { syscall: \"openResizeFile\", path });\n handle = await Reflect.apply(acquire, filesystem, [path, options]);\n signal?.throwIfAborted();\n return handle;\n } catch (error) {\n if (handle) await finishCleanup(() => handle!.close(), true);\n signal?.throwIfAborted();\n throw error;\n }\n}\n\nexport function readOnlyCapabilities(capabilities: FileSystemCapabilities): FileSystemCapabilities {\n const inspection = Object.fromEntries([\n \"read\", \"stat\", \"readdir\", \"realpath\", \"access\", \"readlink\", \"explicitDirectories\", \"implicitDirectories\",\n \"symlinks\", \"streamingRead\", \"open\", \"retainedRead\",\n ].filter(name => capabilities[name] !== undefined).map(name => [name, capabilities[name]]));\n return Object.freeze({\n ...inspection, readOnly: true, write: false, append: false, exclusiveCreate: false,\n mkdir: false, recursiveMkdir: false, remove: false, removeDirectory: false, recursiveRemove: false,\n rename: false, copy: false, exclusiveCopy: false, truncate: false, streamingAppend: false,\n randomAccessWrite: false, hardlinks: false, permissions: false, timestamps: false,\n descriptorWriteStream: false, atomicResize: false, retainedResize: false, atomicFileMutation: false, atomicEntryRemoval: false, atomicTreeRemoval: false, atomicFileStaging: false, atomicDirectoryMetadata: false,\n atomicRename: false, atomicRenameNoReplace: false, streamingWrite: false,\n });\n}\n\nexport function quotaCapabilities(capabilities: FileSystemCapabilities): FileSystemCapabilities {\n const streamingWrite = requireCapabilities(capabilities.write, capabilities.append, !capabilities.readOnly);\n const streamingAppend = requireCapabilities(capabilities.append, !capabilities.readOnly);\n const { streamingWrite: ignoredWrite, streamingAppend: ignoredAppend, ...rest } = capabilities;\n return Object.freeze({ ...rest, descriptorWriteStream: false, atomicResize: false, atomicFileMutation: false, atomicEntryRemoval: false, atomicFileStaging: false, atomicDirectoryMetadata: false,\n ...(streamingWrite === undefined ? {} : { streamingWrite }),\n ...(streamingAppend === undefined ? {} : { streamingAppend }),\n });\n}\n\nexport function ownedMutationCapabilities(filesystem: FileSystem, capabilities = filesystem.capabilities): FileSystemCapabilities {\n const unavailable: Record<string, false> = {};\n if (capabilities.atomicEntryRemoval === true && (capabilities.readOnly === true || typeof filesystem.removeEntryConditional !== \"function\")) unavailable.atomicEntryRemoval = false;\n if (capabilities.atomicTreeRemoval === true && (capabilities.readOnly === true || typeof filesystem.removeTreeConditional !== \"function\")) unavailable.atomicTreeRemoval = false;\n if (capabilities.atomicFileMutation === true && (capabilities.readOnly === true || typeof filesystem.writeFileConditional !== \"function\" || typeof filesystem.removeFileConditional !== \"function\")) unavailable.atomicFileMutation = false;\n if (capabilities.atomicFileStaging === true && (capabilities.readOnly === true\n || typeof filesystem.createStagedFile !== \"function\" || typeof filesystem.publishStagedFile !== \"function\" || typeof filesystem.removeStagedFile !== \"function\")) unavailable.atomicFileStaging = false;\n if (capabilities.atomicDirectoryMetadata === true && (capabilities.readOnly === true || typeof filesystem.prepareDirectory !== \"function\")) unavailable.atomicDirectoryMetadata = false;\n return Object.keys(unavailable).length ? { ...capabilities, ...unavailable } : capabilities;\n}\n\nexport async function requireOwnedMutation(filesystem: FileSystem, path: string,\n capability: \"atomicEntryRemoval\" | \"atomicTreeRemoval\" | \"atomicFileMutation\" | \"atomicFileStaging\" | \"atomicDirectoryMetadata\", options: FsOptions, create = false): Promise<void> {\n options.signal?.throwIfAborted();\n const capabilities = ownedMutationCapabilities(filesystem, await filesystem.capabilitiesFor?.(path, create ? { ...options, create: true } : options) ?? filesystem.capabilities);\n options.signal?.throwIfAborted();\n if (capabilities[capability] !== true) throw new FsError(\"ENOTSUP\", { path, syscall: capability });\n}\n", "import { FsError, isFsError } from \"../../contracts/errors.js\";\nimport { finishCleanup } from \"../../contracts/cleanup.js\";\nimport type { FileDescriptor, OpenFileOptions } from \"../../contracts/descriptor.js\";\nimport type {\n AppendFileOptions, CapabilityQueryOptions, CopyFileOptions, DirectoryEntry, FileReadHandle, FileResizeHandle, FileResizeOperation, FileResizeOptions, FileStat, FileSystem, OpenReadFileOptions, OpenResizeFileOptions,\n FileSystemCapabilities, FsOptions, RenameOptions, MkdirOptions, ReadDirectoryOptions, ReadFileOptions,\n ReadStreamOptions, RemoveOptions, WriteFileOptions,\n ConditionalWriteFileOptions, ConditionalRemoveFileOptions, ConditionalRemoveEntryOptions, CreateStagedFileOptions, FileStaging, PublishStagedFileOptions, PrepareDirectoryOptions, StagedFileContent,\n} from \"../../contracts/filesystem.js\";\nimport type { ByteSource } from \"../../contracts/io.js\";\nimport { admitDirectoryEntries, directoryEntryLimit } from \"../directory-admission.js\";\nimport { compareEntries, registerEntryAuthority, registerEntryView } from \"../mount/comparison.js\";\nimport { deviceDirectory, lexicalDevicePath, nullPath, resolveDevicePath } from \"./path.js\";\nimport { deviceReadStream, drainDeviceFile, drainDeviceInput } from \"./stream.js\";\nimport { openRetainedReadFile, openRetainedResizeFile, retainedResizeCapabilities, ownedMutationCapabilities, requireOwnedMutation } from \"../capabilities.js\";\nimport { pathNamespace } from \"../path-namespace.js\";\n\nconst views = new WeakMap<FileSystem, DeviceFileSystem>();\nconst deviceCapabilities: FileSystemCapabilities = Object.freeze({\n readOnly: false, read: true, stat: true, realpath: true, access: true, readdir: false,\n write: true, append: true, exclusiveCreate: true, streamingRead: true, retainedRead: true,\n streamingWrite: true, streamingAppend: true, independentWriteStreams: true, copy: true, exclusiveCopy: true,\n remove: false, removeDirectory: false, recursiveRemove: false, rename: false,\n mkdir: false, recursiveMkdir: false, symlinks: false, hardlinks: false, readlink: false,\n permissions: false, timestamps: false, truncate: false, randomAccessWrite: false,\n open: false, atomicFileMutation: false, atomicEntryRemoval: false, atomicTreeRemoval: false, atomicFileStaging: false, atomicDirectoryMetadata: false,\n atomicRename: false, atomicRenameNoReplace: false, descriptorWriteStream: true, retainedResize: true, atomicResize: false,\n});\n\nfunction globalCapabilities(filesystem: FileSystem): FileSystemCapabilities {\n const capabilities: Record<string, boolean | undefined> = { readOnly: false };\n const optional: Record<string, readonly (keyof FileSystem)[]> = {\n open: [\"open\"],\n atomicEntryRemoval: [\"removeEntryConditional\"], atomicTreeRemoval: [\"removeTreeConditional\"], atomicFileMutation: [\"writeFileConditional\", \"removeFileConditional\"], atomicFileStaging: [\"createStagedFile\", \"publishStagedFile\", \"removeStagedFile\"], atomicDirectoryMetadata: [\"prepareDirectory\"],\n streamingRead: [\"readStream\"], streamingWrite: [\"writeStream\"], retainedRead: [\"openReadFile\"],\n streamingAppend: [\"writeStream\"], descriptorWriteStream: [\"writeStream\"], retainedResize: [\"openResizeFile\"], atomicResize: [\"resizeFile\"],\n symlinks: [\"symlink\", \"readlink\"], hardlinks: [\"link\"], permissions: [\"chmod\"],\n timestamps: [\"utimes\"], readlink: [\"readlink\"], truncate: [\"truncate\"], removeDirectory: [\"rmdir\"],\n };\n for (const key of new Set([...Object.keys(filesystem.capabilities), ...Object.keys(deviceCapabilities)])) {\n if (key === \"readOnly\") continue;\n Object.defineProperty(capabilities, key, { enumerable: true, get() {\n if (key === \"copy\" || key === \"exclusiveCopy\") return undefined;\n let declared = filesystem.capabilities[key];\n if (declared === true && optional[key]?.some(method => typeof filesystem[method] !== \"function\")) declared = false;\n if (key === \"retainedResize\" && filesystem.capabilities.readOnly === true) declared = false;\n if (key === \"descriptorWriteStream\" && filesystem.capabilities.streamingWrite === false) declared = false;\n return declared === deviceCapabilities[key] ? declared : undefined;\n } });\n }\n return Object.freeze(capabilities);\n}\n\nfunction reserved(path: string): boolean { return path === \"/\" || path === deviceDirectory || path === nullPath; }\nfunction nonnegative(value: number | undefined, path: string): void {\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) throw new FsError(\"EINVAL\", { path });\n}\n\nexport class DeviceFileSystem implements FileSystem {\n readonly #filesystem: FileSystem;\n readonly capabilities: FileSystemCapabilities;\n readonly #nullStat: FileStat;\n readonly #directoryStat: FileStat;\n\n constructor(filesystem: FileSystem) {\n this.#filesystem = filesystem;\n Object.defineProperty(this, pathNamespace, { get: () => Reflect.get(filesystem, pathNamespace) });\n this.capabilities = globalCapabilities(filesystem);\n const identityScope = Object.freeze({});\n const stat = { mode: 0o020666, size: 0, allocatedBytes: 0,\n mtimeMs: 0, atimeMs: 0, ctimeMs: 0, birthtimeMs: 0, identityScope, ino: 1, dev: 0, nlink: 1 };\n this.#nullStat = Object.freeze({ ...stat, type: \"character\", preferredIoBlockSize: 4096 });\n this.#directoryStat = Object.freeze({ ...stat, type: \"directory\", mode: 0o040755, ino: 2 });\n const methods = new Map<PropertyKey, { backing: unknown; bound: unknown }>();\n const view = new Proxy(this, {\n set: (_target, property, value) => Reflect.set(filesystem, property, value, filesystem),\n get(target, property) {\n const value = Reflect.get(target, property, target);\n if (typeof value !== \"function\" || property === \"constructor\") return value;\n const backing = Reflect.get(filesystem, property, filesystem);\n const cached = methods.get(property);\n if (cached && cached.backing === backing) return cached.bound;\n const bound = value.bind(target);\n methods.set(property, { backing, bound });\n return bound;\n },\n });\n for (const identity of [this, view]) registerEntryView(identity, async (path, options) => {\n const resolved = await this.#resolve(path, options);\n if (resolved === nullPath || resolved === deviceDirectory) return { filesystem: this, path: resolved,\n stat: resolved === nullPath ? this.#nullStat : this.#directoryStat, readOnly: false };\n return { filesystem, path };\n });\n // This internal view has no identity proof beyond its synthetic stats.\n registerEntryAuthority(this, async () => \"unknown\");\n return view;\n }\n\n #resolve(path: string, options: FsOptions, followFinal = true, resizeCreate?: boolean) {\n return resolveDevicePath(this.#filesystem, path, options, followFinal, resizeCreate);\n }\n\n async #mutable(path: string, options: FsOptions, followFinal = true): Promise<void> {\n if (reserved(await this.#resolve(path, options, followFinal))) throw new FsError(\"EBUSY\", { path });\n }\n\n async #writeTarget(path: string, options: WriteFileOptions): Promise<boolean> {\n const resolved = await this.#resolve(path, options);\n if (resolved === nullPath) {\n if (options.flag === \"wx\" || options.flag === \"ax\") throw new FsError(\"EEXIST\", { path });\n if (options.flag !== undefined && options.flag !== \"w\" && options.flag !== \"a\") throw new FsError(\"EINVAL\", { path });\n return true;\n }\n if (resolved === \"/\" || resolved === deviceDirectory) throw new FsError(\"EISDIR\", { path });\n return false;\n }\n\n canonicalizeMissingTarget(path: string, options: FsOptions = {}): string | undefined {\n options.signal?.throwIfAborted();\n const resolved = lexicalDevicePath(path);\n return reserved(resolved) ? resolved : this.#filesystem.canonicalizeMissingTarget?.(path, options);\n }\n\n async capabilitiesFor(path: string, options: CapabilityQueryOptions = {}): Promise<FileSystemCapabilities> {\n const resolved = await this.#resolve(path, options, true, options.create);\n options.signal?.throwIfAborted();\n if (options.create !== undefined && (resolved === deviceDirectory || resolved === \"/\")) throw new FsError(\"EISDIR\", { syscall: \"capabilitiesFor\", path });\n if (resolved === nullPath) return deviceCapabilities;\n if (resolved === deviceDirectory) return { ...deviceCapabilities, readdir: true, write: false, append: false,\n exclusiveCreate: false, streamingWrite: false, streamingAppend: false, independentWriteStreams: false, descriptorWriteStream: false,\n retainedRead: false, retainedResize: false, streamingRead: false, copy: false, exclusiveCopy: false };\n const query = this.#filesystem.capabilitiesFor;\n options.signal?.throwIfAborted();\n const selected = query === undefined || query === null ? undefined : await Reflect.apply(query, this.#filesystem, [path, options]);\n options.signal?.throwIfAborted();\n const observed = ownedMutationCapabilities(this.#filesystem, selected ?? this.#filesystem.capabilities);\n options.signal?.throwIfAborted();\n const capabilities = observed.retainedResize === true ? retainedResizeCapabilities(this.#filesystem, observed) : observed;\n const unavailable: Record<string, false> = {};\n if (typeof this.#filesystem.open !== \"function\") unavailable.open = false;\n if (typeof this.#filesystem.readStream !== \"function\") unavailable.streamingRead = false;\n if (typeof this.#filesystem.writeStream !== \"function\") {\n unavailable.streamingWrite = false;\n unavailable.streamingAppend = false;\n unavailable.descriptorWriteStream = false;\n }\n if (typeof this.#filesystem.openReadFile !== \"function\") unavailable.retainedRead = false;\n if (observed.atomicResize === true && (typeof this.#filesystem.resizeFile !== \"function\" || observed.readOnly === true)) unavailable.atomicResize = false;\n const result = Object.keys(unavailable).some(key => capabilities[key] !== false)\n ? { ...capabilities, ...unavailable } : capabilities;\n options.signal?.throwIfAborted();\n return result;\n }\n\n async stat(path: string, options: FsOptions = {}): Promise<FileStat> {\n const resolved = await this.#resolve(path, options);\n options.signal?.throwIfAborted();\n if (resolved === nullPath) return { ...this.#nullStat };\n if (resolved === deviceDirectory) return { ...this.#directoryStat };\n const stat = this.#filesystem.stat;\n options.signal?.throwIfAborted();\n const result = await Reflect.apply(stat, this.#filesystem, [path, options]);\n options.signal?.throwIfAborted();\n return result;\n }\n\n async lstat(path: string, options: FsOptions = {}): Promise<FileStat> {\n const resolved = await this.#resolve(path, options, false);\n options.signal?.throwIfAborted();\n if (resolved === nullPath) return { ...this.#nullStat };\n if (resolved === deviceDirectory) return { ...this.#directoryStat };\n const lstat = this.#filesystem.lstat;\n options.signal?.throwIfAborted();\n const result = await Reflect.apply(lstat, this.#filesystem, [path, options]);\n options.signal?.throwIfAborted();\n return result;\n }\n\n compareEntry(path: string, peer: FileSystem, peerPath: string, options: FsOptions = {}) {\n return compareEntries(this, path, peer, peerPath, options);\n }\n\n async realpath(path: string, options: FsOptions = {}): Promise<string> {\n const resolved = await this.#resolve(path, options);\n return reserved(resolved) ? resolved : this.#filesystem.realpath(path, options);\n }\n\n async readFile(path: string, options: ReadFileOptions = {}): Promise<Uint8Array> {\n const resolved = await this.#resolve(path, options);\n if (resolved === nullPath) { nonnegative(options.maxBytes, path); return new Uint8Array(); }\n if (resolved === deviceDirectory) throw new FsError(\"EISDIR\", { path });\n return this.#filesystem.readFile(path, options);\n }\n\n readStream(path: string, options: ReadStreamOptions = {}): ByteSource {\n return deviceReadStream(async () => {\n const resolved = await this.#resolve(path, options);\n if (resolved === nullPath) {\n nonnegative(options.start, path); nonnegative(options.endExclusive, path); nonnegative(options.chunkSize, path);\n if (options.chunkSize === 0 || (options.endExclusive !== undefined && options.endExclusive < (options.start ?? 0))) throw new FsError(\"EINVAL\", { path });\n return { [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true, value: undefined }) }) };\n }\n if (resolved === deviceDirectory) throw new FsError(\"EISDIR\", { path });\n if (!this.#filesystem.readStream) throw new FsError(\"ENOTSUP\", { path });\n return this.#filesystem.readStream(path, options);\n }, options.signal);\n }\n\n async openReadFile(path: string, options: OpenReadFileOptions = {}): Promise<FileReadHandle> {\n const resolved = await this.#resolve(path, options);\n if (resolved !== nullPath) {\n if (resolved === deviceDirectory) throw new FsError(\"EISDIR\", { path });\n return openRetainedReadFile(this.#filesystem, path, options);\n }\n const stat = this.#nullStat;\n let closed = false;\n const check = (settings: FsOptions) => { settings.signal?.throwIfAborted(); if (closed) throw new FsError(\"EBADF\", { path }); };\n return {\n async stat(settings = {}) { check(settings); return { ...stat }; },\n async read(position, maxBytes, settings = {}) { check(settings); nonnegative(position, path); nonnegative(maxBytes, path); return new Uint8Array(); },\n async seekEnd(settings = {}) { check(settings); return 0n; },\n async close() { closed = true; },\n };\n }\n\n async open(path: string, options: OpenFileOptions): Promise<FileDescriptor> {\n options?.signal?.throwIfAborted();\n if (!options || typeof options !== \"object\") throw new FsError(\"EINVAL\", { syscall: \"open\", path });\n const resolved = await this.#resolve(path, options, options.creation !== \"exclusive\");\n options.signal?.throwIfAborted();\n if (resolved === nullPath || resolved === deviceDirectory) throw new FsError(\"ENOTSUP\", { syscall: \"open\", path });\n const query = this.#filesystem.capabilitiesFor;\n options.signal?.throwIfAborted();\n const capabilities = query && options.creation !== \"exclusive\" ? await Reflect.apply(query, this.#filesystem, [path, options]) : this.#filesystem.capabilities;\n options.signal?.throwIfAborted();\n const open = this.#filesystem.open;\n options.signal?.throwIfAborted();\n if (capabilities.readOnly === true && (options.access === \"write\" || options.access === \"readwrite\" || options.creation === \"ifMissing\" || options.creation === \"exclusive\" || options.truncate === true || options.append === true)) throw new FsError(\"EROFS\", { syscall: \"open\", path });\n if (capabilities.open === false || typeof open !== \"function\") throw new FsError(\"ENOTSUP\", { syscall: \"open\", path });\n let descriptor: FileDescriptor | undefined;\n try {\n descriptor = await Reflect.apply(open, this.#filesystem, [path, options]);\n options.signal?.throwIfAborted();\n return descriptor;\n } catch (error) {\n if (descriptor) await finishCleanup(() => descriptor!.close(), true);\n options.signal?.throwIfAborted();\n throw error;\n }\n }\n\n async resizeFile(path: string, operation: FileResizeOperation, options: FileResizeOptions = {}): Promise<void> {\n await this.#mutable(path, options);\n const capabilities = await this.capabilitiesFor(path, options);\n options.signal?.throwIfAborted();\n if (capabilities.readOnly === true) throw new FsError(\"EROFS\", { syscall: \"resizeFile\", path });\n const resize = this.#filesystem.resizeFile;\n options.signal?.throwIfAborted();\n if (capabilities.atomicResize !== true || typeof resize !== \"function\") throw new FsError(\"ENOTSUP\", { syscall: \"resizeFile\", path });\n await Reflect.apply(resize, this.#filesystem, [path, operation, options]);\n options.signal?.throwIfAborted();\n }\n\n async openResizeFile(path: string, options: OpenResizeFileOptions = {}): Promise<FileResizeHandle> {\n options.signal?.throwIfAborted();\n const resolution = this.#resolve(path, options, true, options.create ?? false);\n const signal = options.signal;\n const resolved = await (signal ? new Promise<string>((resolve, reject) => {\n const abort = (): void => { signal.removeEventListener(\"abort\", abort); reject(signal.reason); };\n signal.addEventListener(\"abort\", abort, { once: true });\n resolution.then(\n value => { signal.removeEventListener(\"abort\", abort); resolve(value); },\n error => { signal.removeEventListener(\"abort\", abort); reject(error); },\n );\n if (signal.aborted) abort();\n }) : resolution);\n options.signal?.throwIfAborted();\n if (resolved === deviceDirectory || resolved === \"/\") throw new FsError(\"EISDIR\", { syscall: \"openResizeFile\", path });\n if (resolved !== nullPath) return openRetainedResizeFile(this.#filesystem, path, options);\n const stat = this.#nullStat;\n let closing: Promise<void> | undefined;\n const check = (settings: FsOptions, syscall: string): void => {\n settings.signal?.throwIfAborted();\n if (closing) throw new FsError(\"EBADF\", { syscall, path });\n };\n return {\n async stat(settings = {}) { check(settings, \"fstat\"); return { ...stat }; },\n async seekEnd(settings = {}) { check(settings, \"lseek\"); return 0n; },\n async truncate(_length, settings = {}) {\n check(settings, \"ftruncate\");\n throw new FsError(\"EINVAL\", { syscall: \"ftruncate\", path });\n },\n close: () => closing ??= Promise.resolve(),\n };\n }\n\n async writeFile(path: string, data: Uint8Array, options: WriteFileOptions = {}): Promise<void> {\n if (await this.#writeTarget(path, options)) {\n if (!(data instanceof Uint8Array)) throw new TypeError(\"File data must be Uint8Array\");\n return;\n }\n await this.#filesystem.writeFile(path, data, options);\n }\n\n async appendFile(path: string, data: Uint8Array, options: AppendFileOptions = {}): Promise<void> {\n if (await this.#writeTarget(path, options)) {\n if (!(data instanceof Uint8Array)) throw new TypeError(\"File data must be Uint8Array\");\n return;\n }\n await this.#filesystem.appendFile(path, data, options);\n }\n\n async writeStream(path: string, source: ByteSource, options: WriteFileOptions = {}): Promise<void> {\n if (await this.#writeTarget(path, options)) return drainDeviceInput(source, options.signal);\n if (!this.#filesystem.writeStream) throw new FsError(\"ENOTSUP\", { path });\n await this.#filesystem.writeStream(path, source, options);\n }\n\n async readdir(path: string, options: ReadDirectoryOptions = {}): Promise<DirectoryEntry[]> {\n const resolved = await this.#resolve(path, options);\n if (resolved === nullPath) throw new FsError(\"ENOTDIR\", { path });\n if (resolved !== \"/\" && resolved !== deviceDirectory) return this.#filesystem.readdir(path, options);\n const limit = directoryEntryLimit(options, path);\n let entries: DirectoryEntry[];\n try { entries = await this.#filesystem.readdir(resolved, options); }\n catch (error) {\n options.signal?.throwIfAborted();\n if (!isFsError(error, \"ENOENT\") && !isFsError(error, \"ENOTDIR\")) throw error;\n entries = [];\n }\n options.signal?.throwIfAborted();\n const merged = new Map<string, DirectoryEntry>();\n for (const entry of entries) {\n if (entry.name === \".\" || entry.name === \"..\") continue;\n if (!entry.name || entry.name.includes(\"/\") || entry.name.includes(\"\\0\")) throw new FsError(\"EIO\", { path, message: \"invalid directory entry\" });\n merged.set(entry.name, { name: entry.name, type: entry.type });\n admitDirectoryEntries(merged.size, limit, path);\n }\n const name = resolved === \"/\" ? \"dev\" : \"null\";\n merged.set(name, { name, type: resolved === \"/\" ? \"directory\" : \"character\" });\n admitDirectoryEntries(merged.size, limit, path);\n return [...merged.values()];\n }\n\n async mkdir(path: string, options: MkdirOptions = {}): Promise<void> {\n const resolved = await this.#resolve(path, options);\n if (reserved(resolved)) {\n if (resolved !== nullPath && options.recursive) return;\n throw new FsError(\"EEXIST\", { path });\n }\n await this.#filesystem.mkdir(path, options);\n }\n\n async rm(path: string, options: RemoveOptions = {}): Promise<void> {\n await this.#mutable(path, options, false);\n await this.#filesystem.rm(path, options);\n }\n\n async unlink(path: string, options: FsOptions = {}): Promise<void> {\n await this.#mutable(path, options, false);\n if (!this.#filesystem.unlink) throw new FsError(\"ENOTSUP\", { syscall: \"unlink\", path });\n options.signal?.throwIfAborted();\n await this.#filesystem.unlink(path, options);\n }\n\n async rmdir(path: string, options: FsOptions = {}): Promise<void> {\n const resolved = await this.#resolve(path, options, false);\n if (resolved === nullPath) throw new FsError(\"ENOTDIR\", { path });\n if (reserved(resolved)) throw new FsError(\"EBUSY\", { path });\n if (!this.#filesystem.rmdir) throw new FsError(\"ENOTSUP\", { path });\n await this.#filesystem.rmdir(path, options);\n }\n\n async writeFileConditional(path: string, data: Uint8Array, options: ConditionalWriteFileOptions): Promise<FileStat> {\n await this.#mutable(path, options, false);\n await requireOwnedMutation(this.#filesystem, path, \"atomicFileMutation\", options, options.expected === null);\n if (!this.#filesystem.writeFileConditional) throw new FsError(\"ENOTSUP\", { path });\n return this.#filesystem.writeFileConditional(path, data, options);\n }\n\n async removeEntryConditional(path: string, options: ConditionalRemoveEntryOptions): Promise<void> {\n await this.#mutable(path, options, false);\n await requireOwnedMutation(this.#filesystem, path, \"atomicEntryRemoval\", options);\n if (!this.#filesystem.removeEntryConditional) throw new FsError(\"ENOTSUP\", { path });\n await this.#filesystem.removeEntryConditional(path, options);\n }\n\n async removeFileConditional(path: string, options: ConditionalRemoveFileOptions): Promise<void> {\n await this.#mutable(path, options, false);\n await requireOwnedMutation(this.#filesystem, path, \"atomicFileMutation\", options);\n if (!this.#filesystem.removeFileConditional) throw new FsError(\"ENOTSUP\", { path });\n await this.#filesystem.removeFileConditional(path, options);\n }\n\n async removeTreeConditional(path: string, options: ConditionalRemoveEntryOptions): Promise<void> {\n await this.#mutable(path, options, false);\n await requireOwnedMutation(this.#filesystem, path, \"atomicTreeRemoval\", options);\n if (!this.#filesystem.removeTreeConditional) throw new FsError(\"ENOTSUP\", { path });\n await this.#filesystem.removeTreeConditional(path, options);\n }\n\n async createStagedFile(path: string, name: string, content: StagedFileContent, options: CreateStagedFileOptions): Promise<FileStaging> {\n await this.#mutable(path, options, false);\n await requireOwnedMutation(this.#filesystem, path, \"atomicFileStaging\", options, true);\n if (!this.#filesystem.createStagedFile) throw new FsError(\"ENOTSUP\", { path });\n return this.#filesystem.createStagedFile(path, name, content, options);\n }\n\n async publishStagedFile(staging: FileStaging, destination: string, options: PublishStagedFileOptions): Promise<void> {\n for (const path of [staging.directory.path, staging.file.path, destination]) await this.#mutable(path, options, false);\n await requireOwnedMutation(this.#filesystem, staging.directory.path, \"atomicFileStaging\", options);\n if (!this.#filesystem.publishStagedFile) throw new FsError(\"ENOTSUP\", { path: destination });\n await this.#filesystem.publishStagedFile(staging, destination, options);\n }\n\n async removeStagedFile(staging: FileStaging, options: FsOptions = {}): Promise<void> {\n for (const path of [staging.directory.path, staging.file.path]) await this.#mutable(path, options, false);\n await requireOwnedMutation(this.#filesystem, staging.directory.path, \"atomicFileStaging\", options);\n if (!this.#filesystem.removeStagedFile) throw new FsError(\"ENOTSUP\", { path: staging.directory.path });\n await this.#filesystem.removeStagedFile(staging, options);\n }\n\n async prepareDirectory(path: string, options: PrepareDirectoryOptions): Promise<FileStat> {\n await this.#mutable(path, options, false);\n await requireOwnedMutation(this.#filesystem, path, \"atomicDirectoryMetadata\", options, options.expected === null);\n if (!this.#filesystem.prepareDirectory) throw new FsError(\"ENOTSUP\", { path });\n return this.#filesystem.prepareDirectory(path, options);\n }\n\n async rename(source: string, destination: string, options: RenameOptions = {}): Promise<void> {\n await this.#mutable(source, options, false); await this.#mutable(destination, options, false);\n if (options.noReplace) {\n const capabilities = await this.#filesystem.capabilitiesFor?.(destination, options) ?? this.#filesystem.capabilities;\n options.signal?.throwIfAborted();\n if (capabilities.atomicRenameNoReplace !== true) throw new FsError(\"ENOTSUP\", { syscall: \"rename\", path: source, dest: destination });\n }\n await this.#filesystem.rename(source, destination, options);\n }\n\n async copyFile(source: string, destination: string, options: CopyFileOptions = {}): Promise<void> {\n const target = await this.#resolve(destination, options);\n if (target === nullPath && options.exclusive) throw new FsError(\"EEXIST\", { path: destination });\n const origin = await this.#resolve(source, options);\n if (target !== nullPath && origin !== nullPath) {\n if (target === \"/\" || target === deviceDirectory) throw new FsError(\"EISDIR\", { path: destination });\n await this.#filesystem.copyFile(source, destination, options);\n return;\n }\n if (target === nullPath) {\n if (origin === nullPath) return;\n if (origin === \"/\" || origin === deviceDirectory) throw new FsError(\"EISDIR\", { path: source });\n const capabilities = await this.capabilitiesFor(source, options);\n if (this.#filesystem.readStream && capabilities.streamingRead !== false) {\n await drainDeviceInput(this.#filesystem.readStream(source, options), options.signal);\n } else if (this.#filesystem.openReadFile && capabilities.retainedRead !== false) {\n await drainDeviceFile(await this.#filesystem.openReadFile(source, options), options.signal);\n } else throw new FsError(\"ENOTSUP\", { path: source });\n return;\n }\n if (reserved(target)) throw new FsError(\"EISDIR\", { path: destination });\n await this.#filesystem.writeFile(destination, new Uint8Array(), { ...options, flag: options.exclusive ? \"wx\" : \"w\" });\n }\n\n async access(path: string, mode = 0, options: FsOptions = {}): Promise<void> {\n const resolved = await this.#resolve(path, options);\n if (resolved === nullPath || resolved === deviceDirectory) {\n if (!Number.isInteger(mode) || mode < 0 || mode > 7) throw new FsError(\"EINVAL\", { path });\n if ((resolved === nullPath && (mode & 1)) || (resolved === deviceDirectory && (mode & 2))) throw new FsError(\"EACCES\", { path });\n return;\n }\n await this.#filesystem.access(path, mode, options);\n }\n\n async readlink(path: string, options: FsOptions = {}): Promise<string> {\n if (reserved(await this.#resolve(path, options, false))) throw new FsError(\"EINVAL\", { path });\n if (!this.#filesystem.readlink) throw new FsError(\"ENOTSUP\", { path });\n return this.#filesystem.readlink(path, options);\n }\n\n async symlink(target: string, path: string, options: FsOptions = {}): Promise<void> {\n await this.#mutable(path, options, false);\n if (!this.#filesystem.symlink) throw new FsError(\"ENOTSUP\", { path });\n await this.#filesystem.symlink(target, path, options);\n }\n\n async link(existingPath: string, newPath: string, options: FsOptions = {}): Promise<void> {\n await this.#mutable(existingPath, options, false); await this.#mutable(newPath, options, false);\n if (!this.#filesystem.link) throw new FsError(\"ENOTSUP\", { path: newPath });\n await this.#filesystem.link(existingPath, newPath, options);\n }\n\n async chmod(path: string, mode: number, options: FsOptions = {}): Promise<void> {\n await this.#mutable(path, options);\n if (!this.#filesystem.chmod) throw new FsError(\"ENOTSUP\", { path });\n await this.#filesystem.chmod(path, mode, options);\n }\n\n async utimes(path: string, atimeMs: number, mtimeMs: number, options: FsOptions = {}): Promise<void> {\n await this.#mutable(path, options);\n if (!this.#filesystem.utimes) throw new FsError(\"ENOTSUP\", { path });\n await this.#filesystem.utimes(path, atimeMs, mtimeMs, options);\n }\n\n async truncate(path: string, length?: number, options: FsOptions = {}): Promise<void> {\n await this.#mutable(path, options);\n if (!this.#filesystem.truncate) throw new FsError(\"ENOTSUP\", { path });\n await this.#filesystem.truncate(path, length, options);\n }\n}\n\nexport function createDeviceFileSystem(filesystem: FileSystem): DeviceFileSystem {\n if (filesystem instanceof DeviceFileSystem) return filesystem;\n let view = views.get(filesystem);\n if (!view) { view = new DeviceFileSystem(filesystem); views.set(filesystem, view); }\n return view;\n}\n", "import { ACCESS_MODES } from \"../../contracts/filesystem.js\";\nimport { FsError } from \"../../contracts/errors.js\";\nimport { readBytes } from \"../../contracts/io.js\";\nimport { finishCleanup } from \"../../contracts/cleanup.js\";\nimport type { ByteSource } from \"../../contracts/io.js\";\nimport type {\n AppendFileOptions, CapabilityQueryOptions, CopyFileOptions, DirectoryEntry, FileResizeHandle, FileStat, OpenReadFileOptions, OpenResizeFileOptions,\n FileSystem, FileSystemCapabilities, FsOptions, RenameOptions, MkdirOptions, ReadDirectoryOptions, ReadFileOptions,\n ReadStreamOptions, RemoveOptions, WriteFileOptions,\n} from \"../../contracts/filesystem.js\";\nimport { compareEntries, registerEntryView } from \"../mount/comparison.js\";\nimport { openRetainedReadFile, readOnlyCapabilities, retainedReadCapabilities } from \"../capabilities.js\";\nimport { admitDirectoryEntries, directoryEntryLimit } from \"../directory-admission.js\";\nimport { forwardFileDescriptor, openFileDescriptor } from \"../descriptor.js\";\nimport type { FileDescriptor, OpenFileOptions } from \"../../contracts/descriptor.js\";\nimport { pathNamespace, readOnlyPathNamespace } from \"../path-namespace.js\";\n\nfunction readOnly(syscall: string, path: string, dest?: string): never {\n throw new FsError(\"EROFS\", { syscall, path, ...(dest === undefined ? {} : { dest }) });\n}\n\nfunction snapshotStat(stat: FileStat): FileStat {\n const { type, size, allocatedBytes, ioBlockSize, preferredIoBlockSize, mode, mtimeMs, atimeMs, ctimeMs, birthtimeMs, revision, identityScope, ino, dev, rdevMajor, rdevMinor, nlink, uid, gid } = stat;\n return {\n type, size, mode, mtimeMs, atimeMs, ctimeMs,\n ...(revision === undefined ? {} : { revision }),\n ...(allocatedBytes === undefined ? {} : { allocatedBytes }),\n ...(ioBlockSize === undefined ? {} : { ioBlockSize }),\n ...(preferredIoBlockSize === undefined ? {} : { preferredIoBlockSize }),\n ...(birthtimeMs === undefined ? {} : { birthtimeMs }),\n ...(identityScope === undefined ? {} : { identityScope }),\n ...(ino === undefined ? {} : { ino }),\n ...(dev === undefined ? {} : { dev }),\n ...(rdevMajor === undefined ? {} : { rdevMajor }),\n ...(rdevMinor === undefined ? {} : { rdevMinor }),\n ...(nlink === undefined ? {} : { nlink }),\n ...(uid === undefined ? {} : { uid }),\n ...(gid === undefined ? {} : { gid }),\n };\n}\n\nexport class ReadOnlyFileSystem implements FileSystem {\n readonly #filesystem: FileSystem;\n readonly #capabilities: FileSystemCapabilities;\n\n constructor(filesystem: FileSystem) {\n this.#filesystem = filesystem;\n if (Reflect.has(filesystem, pathNamespace)) Object.defineProperty(this, pathNamespace, {\n get: () => readOnlyPathNamespace(Reflect.get(filesystem, pathNamespace)),\n });\n registerEntryView(this, async (path) => ({ filesystem: this.#filesystem, path, readOnly: true }));\n const streamingRead = typeof filesystem.readStream === \"function\" ? filesystem.capabilities.streamingRead : false;\n this.#capabilities = readOnlyCapabilities({\n ...retainedReadCapabilities(filesystem),\n ...(typeof filesystem.open === \"function\" ? {} : { open: false }),\n readOnly: true,\n append: false,\n symlinks: filesystem.capabilities.symlinks === true && typeof filesystem.readlink === \"function\",\n hardlinks: false,\n permissions: false,\n timestamps: false,\n atomicRename: false,\n ...(streamingRead === undefined ? {} : { streamingRead }),\n streamingWrite: false,\n });\n }\n\n get capabilities(): FileSystemCapabilities {\n return this.#capabilities;\n }\n\n async capabilitiesFor(path: string, options?: CapabilityQueryOptions): Promise<FileSystemCapabilities> {\n options?.signal?.throwIfAborted();\n if (options?.create !== undefined) readOnly(\"capabilitiesFor\", path);\n const capabilities = await this.#filesystem.capabilitiesFor?.(path, options) ?? this.#filesystem.capabilities;\n return readOnlyCapabilities({ ...retainedReadCapabilities(this.#filesystem, capabilities), ...(typeof this.#filesystem.open === \"function\" ? {} : { open: false }) });\n }\n\n async open(path: string, options: OpenFileOptions): Promise<FileDescriptor> {\n options?.signal?.throwIfAborted();\n if (options && (options.access === \"write\" || options.access === \"readwrite\" || options.truncate === true || options.append === true\n || options.creation === \"ifMissing\" || options.creation === \"exclusive\")) readOnly(\"open\", path);\n return openFileDescriptor(path, options, {\n positionedRead: true, positionedWrite: false, truncate: false, synchronization: \"none\",\n }, async admitted => {\n const capabilities = await this.#filesystem.capabilitiesFor?.(path, admitted) ?? this.#filesystem.capabilities;\n if (!this.#filesystem.open || capabilities.open === false) throw new FsError(\"ENOTSUP\", { syscall: \"open\", path });\n admitted.signal?.throwIfAborted();\n const descriptor = await this.#filesystem.open(path, admitted);\n try {\n return forwardFileDescriptor(descriptor, async (_syscall, forwarded, action) => {\n forwarded.signal?.throwIfAborted();\n return action();\n }, { ...descriptor.capabilities,\n ...(descriptor.capabilities.openTruncate === undefined ? {} : { openTruncate: false }),\n positionedWrite: false, truncate: false, synchronization: \"none\" }, snapshotStat);\n } catch (error) {\n await finishCleanup(() => descriptor.close(), true);\n throw error;\n }\n });\n }\n\n openReadFile(path: string, options: OpenReadFileOptions = {}) {\n return openRetainedReadFile(this.#filesystem, path, options);\n }\n\n async readFile(path: string, options?: ReadFileOptions): Promise<Uint8Array> {\n return new Uint8Array(await this.#filesystem.readFile(path, options));\n }\n\n async stat(path: string, options?: FsOptions): Promise<FileStat> {\n return snapshotStat(await this.#filesystem.stat(path, options));\n }\n\n async lstat(path: string, options?: FsOptions): Promise<FileStat> {\n return snapshotStat(await this.#filesystem.lstat(path, options));\n }\n\n compareEntry(path: string, peer: FileSystem, peerPath: string, options: FsOptions = {}) {\n return compareEntries(this, path, peer, peerPath, options);\n }\n\n async readdir(path: string, options?: ReadDirectoryOptions): Promise<DirectoryEntry[]> {\n const limit = options?.maxEntries === undefined ? undefined : directoryEntryLimit(options, path);\n const entries = await this.#filesystem.readdir(path, options);\n if (limit !== undefined) options?.signal?.throwIfAborted();\n admitDirectoryEntries(entries.length, limit, path);\n return entries.map((entry) => ({ name: entry.name, type: entry.type }));\n }\n\n async realpath(path: string, options?: FsOptions): Promise<string> {\n return this.#filesystem.realpath(path, options);\n }\n\n async access(path: string, mode: number = ACCESS_MODES.F_OK, options?: FsOptions): Promise<void> {\n if (!Number.isInteger(mode) || mode < 0 || mode > 7) {\n throw new FsError(\"EINVAL\", { syscall: \"access\", path });\n }\n if ((mode & ACCESS_MODES.W_OK) !== 0) readOnly(\"access\", path);\n return this.#filesystem.access(path, mode, options);\n }\n\n async readlink(path: string, options?: FsOptions): Promise<string> {\n if (typeof this.#filesystem.readlink !== \"function\") {\n throw new FsError(\"ENOTSUP\", { syscall: \"readlink\", path });\n }\n return this.#filesystem.readlink(path, options);\n }\n\n async *readStream(path: string, options?: ReadStreamOptions): ByteSource {\n if (typeof this.#filesystem.readStream !== \"function\") {\n throw new FsError(\"ENOTSUP\", { syscall: \"readStream\", path });\n }\n for await (const chunk of readBytes(this.#filesystem.readStream(path, options), options?.signal)) {\n yield new Uint8Array(chunk);\n }\n }\n\n async writeFile(path: string, _data: Uint8Array, _options?: WriteFileOptions): Promise<void> {\n readOnly(\"writeFile\", path);\n }\n\n async appendFile(path: string, _data: Uint8Array, _options?: AppendFileOptions): Promise<void> {\n readOnly(\"appendFile\", path);\n }\n\n async writeStream(path: string, _source: ByteSource, _options?: WriteFileOptions): Promise<void> {\n readOnly(\"writeStream\", path);\n }\n\n async mkdir(path: string, _options?: MkdirOptions): Promise<void> {\n readOnly(\"mkdir\", path);\n }\n\n async rm(path: string, _options?: RemoveOptions): Promise<void> {\n readOnly(\"rm\", path);\n }\n\n async unlink(path: string, _options?: FsOptions): Promise<void> {\n readOnly(\"unlink\", path);\n }\n\n async rmdir(path: string, _options?: FsOptions): Promise<void> {\n readOnly(\"rmdir\", path);\n }\n\n async rename(source: string, destination: string, _options?: RenameOptions): Promise<void> {\n readOnly(\"rename\", source, destination);\n }\n\n async copyFile(source: string, destination: string, _options?: CopyFileOptions): Promise<void> {\n readOnly(\"copyFile\", source, destination);\n }\n\n async symlink(target: string, path: string, _options?: FsOptions): Promise<void> {\n readOnly(\"symlink\", target, path);\n }\n\n async link(existingPath: string, newPath: string, _options?: FsOptions): Promise<void> {\n readOnly(\"link\", existingPath, newPath);\n }\n\n async chmod(path: string, _mode: number, _options?: FsOptions): Promise<void> {\n readOnly(\"chmod\", path);\n }\n\n async utimes(path: string, _atimeMs: number, _mtimeMs: number, _options?: FsOptions): Promise<void> {\n readOnly(\"utimes\", path);\n }\n\n async truncate(path: string, _length?: number, _options?: FsOptions): Promise<void> {\n readOnly(\"truncate\", path);\n }\n\n async openResizeFile(path: string, options: OpenResizeFileOptions = {}): Promise<FileResizeHandle> {\n options.signal?.throwIfAborted();\n readOnly(\"openResizeFile\", path);\n }\n}\n\nexport function createReadOnlyFileSystem(filesystem: FileSystem): ReadOnlyFileSystem {\n return new ReadOnlyFileSystem(filesystem);\n}\n", "import { FsError, isFsError, toFsError } from \"../../contracts/errors.js\";\nimport type { ErrnoCode } from \"../../contracts/errors.js\";\nimport type {\n AppendFileOptions, CapabilityQueryOptions, CopyFileOptions, DirectoryEntry, FileReadHandle, FileResizeHandle, FileResizeOperation, FileResizeOptions, FileStat, FileSystem, OpenReadFileOptions, OpenResizeFileOptions,\n FileSystemCapabilities, FsOptions, RenameOptions, MkdirOptions, ReadDirectoryOptions, ReadFileOptions,\n ReadStreamOptions, RemoveOptions, WriteFileOptions,\n ConditionalWriteFileOptions, ConditionalRemoveFileOptions, ConditionalRemoveEntryOptions, CreateStagedFileOptions, FileStaging, FileStagingEntry, PublishStagedFileOptions, PrepareDirectoryOptions, StagedFileContent,\n} from \"../../contracts/filesystem.js\";\nimport type { ByteSource } from \"../../contracts/io.js\";\nimport { readBytes } from \"../../contracts/io.js\";\nimport { finishCleanup } from \"../../contracts/cleanup.js\";\nimport { requireOwnedMutation, ownedMutationCapabilities, openRetainedReadFile, openRetainedResizeFile, readOnlyCapabilities, retainedReadCapabilities, retainedResizeCapabilities } from \"../capabilities.js\";\nimport { admitDirectoryEntries, directoryEntryLimit } from \"../directory-admission.js\";\nimport { normalizePath, validatePath } from \"../../contracts/virtual-path.js\";\nimport { forwardFileDescriptor, openFileDescriptor } from \"../descriptor.js\";\nimport type { FileDescriptor, OpenFileOptions } from \"../../contracts/descriptor.js\";\nimport { pathNamespace } from \"../path-namespace.js\";\nimport { compareIdentity } from \"./identity.js\";\nimport { compareEntries, registerEntryAuthority, registerEntryView } from \"./comparison.js\";\n\nexport interface MountFileSystemOptions {\n readonly root: FileSystem;\n readonly mounts?: Readonly<Record<string, FileSystem>>;\n}\n\ninterface Mount {\n readonly path: string;\n readonly backend: FileSystem;\n}\n\ninterface Location {\n readonly path: string;\n readonly local: string;\n readonly mount: Mount;\n readonly stat: FileStat | undefined;\n readonly synthetic: boolean;\n}\n\ninterface Component {\n readonly name: string;\n readonly trailing?: boolean;\n}\n\ninterface ResolveOptions {\n readonly resizeCreate?: boolean;\n readonly followFinal?: boolean;\n readonly entry?: boolean;\n readonly allowMissing?: boolean;\n readonly missingDirectory?: boolean;\n readonly createDirectories?: Map<string, Location>;\n}\n\nconst syntheticStat: FileStat = Object.freeze({\n type: \"directory\", size: 0, mode: 0o40555,\n mtimeMs: 0, atimeMs: 0, ctimeMs: 0,\n});\n\nfunction within(parent: string, path: string): boolean {\n return parent === \"/\" || path === parent || path.startsWith(`${parent}/`);\n}\n\nfunction globalPath(path: string): string {\n return typeof path === \"string\" && path.startsWith(\"/\") ? path : `/${String(path)}`;\n}\n\nfunction fail(code: ErrnoCode): never {\n throw new FsError(code);\n}\n\nfunction snapshotStat(stat: FileStat): FileStat {\n const { type, size, allocatedBytes, ioBlockSize, preferredIoBlockSize, mode, mtimeMs, atimeMs, ctimeMs, birthtimeMs, revision, identityScope, ino, dev, rdevMajor, rdevMinor, nlink, uid, gid } = stat;\n return {\n type, size, mode, mtimeMs, atimeMs, ctimeMs,\n ...(revision === undefined ? {} : { revision }),\n ...(allocatedBytes === undefined ? {} : { allocatedBytes }),\n ...(ioBlockSize === undefined ? {} : { ioBlockSize }),\n ...(preferredIoBlockSize === undefined ? {} : { preferredIoBlockSize }),\n ...(birthtimeMs === undefined ? {} : { birthtimeMs }),\n ...(identityScope === undefined ? {} : { identityScope }),\n ...(ino === undefined ? {} : { ino }),\n ...(dev === undefined ? {} : { dev }),\n ...(rdevMajor === undefined ? {} : { rdevMajor }),\n ...(rdevMinor === undefined ? {} : { rdevMinor }),\n ...(nlink === undefined ? {} : { nlink }),\n ...(uid === undefined ? {} : { uid }),\n ...(gid === undefined ? {} : { gid }),\n };\n}\n\nexport class MountFileSystem implements FileSystem {\n readonly capabilities: FileSystemCapabilities;\n private readonly mounts: readonly Mount[];\n\n constructor(options: MountFileSystemOptions) {\n const mounts: Mount[] = [];\n const paths = new Set<string>();\n const add = (path: string, backend: FileSystem): void => {\n if (backend instanceof MountFileSystem) {\n for (const child of backend.mounts) {\n add(path === \"/\" ? child.path : child.path === \"/\" ? path : `${path}${child.path}`, child.backend);\n }\n return;\n }\n if (paths.has(path)) {\n throw new FsError(\"EINVAL\", { syscall: \"mount\", path });\n }\n paths.add(path);\n mounts.push({ path, backend });\n };\n add(\"/\", options.root);\n for (const [input, backend] of Object.entries(options.mounts ?? {})) {\n try { validatePath(input); } catch (error) {\n throw new FsError(\"EINVAL\", { syscall: \"mount\", path: globalPath(input), cause: error });\n }\n const path = normalizePath(input);\n if (!input.startsWith(\"/\") || path === \"/\") {\n throw new FsError(\"EINVAL\", { syscall: \"mount\", path: globalPath(input) });\n }\n add(path, backend);\n }\n this.mounts = mounts.sort((left, right) => right.path.length - left.path.length);\n const selectNamespace = this.select.bind(this);\n Object.defineProperty(this, pathNamespace, {\n value: Object.freeze({ select: (path: string) => selectNamespace(path).path }),\n });\n registerEntryView(this, (path, options) => this.operation(\"compareEntry\", path, options, async () => {\n const location = await this.resolve(path, options);\n if (location.synthetic) return { filesystem: this, path, stat: syntheticStat, readOnly: true };\n return { filesystem: location.mount.backend, path: location.local };\n }));\n registerEntryAuthority(this, async () => \"unknown\");\n const all = (capability: string, methods: readonly (keyof FileSystem)[] = []): boolean =>\n mounts.every(({ backend }) => backend.capabilities[capability] === true\n && methods.every((method) => typeof backend[method] === \"function\"));\n const streaming = (capability: \"streamingRead\" | \"streamingWrite\" | \"retainedRead\", method: \"readStream\" | \"writeStream\" | \"openReadFile\"): boolean | undefined =>\n all(capability, [method]) ? true : mounts.some(({ backend }) =>\n backend.capabilities[capability] !== false && typeof backend[method] === \"function\") ? undefined : false;\n const streamingRead = streaming(\"streamingRead\", \"readStream\");\n const streamingWrite = streaming(\"streamingWrite\", \"writeStream\");\n const retainedRead = streaming(\"retainedRead\", \"openReadFile\");\n const append = all(\"append\") ? true\n : mounts.every(({ backend }) => backend.capabilities.append === false) ? false : undefined;\n const common = (capability: string): boolean | undefined => {\n const optional: Record<string, readonly (keyof FileSystem)[]> = {\n open: [\"open\"],\n atomicEntryRemoval: [\"removeEntryConditional\"], atomicTreeRemoval: [\"removeTreeConditional\"], atomicFileMutation: [\"writeFileConditional\", \"removeFileConditional\"], atomicFileStaging: [\"createStagedFile\", \"publishStagedFile\", \"removeStagedFile\"], atomicDirectoryMetadata: [\"prepareDirectory\"],\n symlinks: [\"symlink\", \"readlink\"], hardlinks: [\"link\"], permissions: [\"chmod\"], timestamps: [\"utimes\"], readlink: [\"readlink\"],\n descriptorWriteStream: [\"writeStream\"], retainedResize: [\"openResizeFile\"], atomicResize: [\"resizeFile\"],\n };\n const values = mounts.map(({ backend }) => {\n if (backend.capabilities.readOnly === true\n && ![\"open\", \"read\", \"stat\", \"readdir\", \"realpath\", \"access\", \"readlink\", \"explicitDirectories\", \"implicitDirectories\"].includes(capability)) return false;\n const declared = backend.capabilities[capability];\n if (capability === \"descriptorWriteStream\" && backend.capabilities.streamingWrite === false) return false;\n return declared === true && optional[capability]?.some(method => typeof backend[method] !== \"function\") ? false : declared;\n });\n if ([\"rename\", \"atomicRenameNoReplace\", \"copy\", \"exclusiveCopy\"].includes(capability) && mounts.length > 1) return undefined;\n return values.every(value => value === true) ? true : values.every(value => value === false) ? false : undefined;\n };\n const semantics = Object.fromEntries([\n \"atomicEntryRemoval\", \"atomicTreeRemoval\", \"atomicFileMutation\", \"atomicFileStaging\", \"atomicDirectoryMetadata\", \"read\", \"stat\", \"readdir\", \"realpath\", \"access\", \"open\",\n \"write\", \"append\", \"exclusiveCreate\", \"explicitDirectories\", \"implicitDirectories\", \"mkdir\", \"recursiveMkdir\",\n \"remove\", \"removeDirectory\", \"recursiveRemove\", \"rename\", \"atomicRenameNoReplace\", \"copy\", \"exclusiveCopy\", \"readlink\", \"truncate\",\n \"streamingAppend\", \"randomAccessWrite\", \"descriptorWriteStream\", \"retainedResize\", \"atomicResize\", \"symlinks\", \"hardlinks\", \"permissions\", \"timestamps\",\n ].map(capability => [capability, common(capability)]).filter(([, value]) => value !== undefined));\n this.capabilities = Object.freeze({\n get snapshotRmdir() { return mounts.some(({ backend }) => backend.capabilities.snapshotRmdir === true); },\n readOnly: all(\"readOnly\"),\n ...(append === undefined ? {} : { append }),\n ...semantics,\n atomicRename: mounts.length === 1 && all(\"atomicRename\"),\n ...(streamingRead === undefined ? {} : { streamingRead }),\n ...(streamingWrite === undefined ? {} : { streamingWrite }),\n ...(retainedRead === undefined ? {} : { retainedRead }),\n });\n }\n\n private select(path: string): Mount {\n return this.mounts.find((mount) => within(mount.path, path))!;\n }\n\n async capabilitiesFor(path: string, options: CapabilityQueryOptions = {}): Promise<FileSystemCapabilities> {\n return this.operation(\"capabilitiesFor\", path, options, async () => {\n const location = await this.resolve(path, options, {\n allowMissing: options.create ?? true,\n ...(options.create === undefined ? {} : { resizeCreate: options.create }),\n });\n const observed = ownedMutationCapabilities(location.mount.backend, await location.mount.backend.capabilitiesFor?.(location.local, options)\n ?? location.mount.backend.capabilities);\n const declared = observed.descriptorWriteStream === true\n && (typeof location.mount.backend.writeStream !== \"function\" || observed.readOnly === true || observed.streamingWrite === false)\n ? { ...observed, descriptorWriteStream: false } : observed;\n const resize = declared.atomicResize === true && (typeof location.mount.backend.resizeFile !== \"function\" || declared.readOnly === true)\n ? { ...declared, atomicResize: false } : declared;\n const withOpen = { ...resize, ...(typeof location.mount.backend.open === \"function\" ? {} : { open: false }) };\n const capabilities = location.synthetic ? { ...withOpen, open: false, retainedRead: false }\n : retainedResizeCapabilities(location.mount.backend, retainedReadCapabilities(location.mount.backend, withOpen));\n if (location.synthetic) return readOnlyCapabilities(capabilities);\n if (this.mounts.length === 1 || capabilities.readOnly === true) return Object.freeze({ ...capabilities });\n const { rename: ignoredRename, copy: ignoredCopy, exclusiveCopy: ignoredExclusiveCopy, ...selected } = capabilities;\n const cannotPublish = capabilities.write === false && capabilities.streamingWrite === false && capabilities.exclusiveCreate === false;\n return Object.freeze({\n ...selected,\n ...(capabilities.copy === false && capabilities.exclusiveCopy === false && cannotPublish ? { copy: false } : {}),\n ...(capabilities.exclusiveCopy === false && capabilities.exclusiveCreate === false && capabilities.streamingWrite === false ? { exclusiveCopy: false } : {}),\n });\n });\n }\n\n private protected(path: string): boolean {\n return path === \"/\" || this.mounts.some((mount) => within(path, mount.path));\n }\n\n async openReadFile(path: string, options: OpenReadFileOptions = {}): Promise<FileReadHandle> {\n try {\n options.signal?.throwIfAborted();\n const location = await this.resolve(path, options);\n if (location.synthetic) fail(\"EISDIR\");\n return await openRetainedReadFile(location.mount.backend, location.local, options);\n } catch (error) {\n throw error ? this.error(error, \"openReadFile\", path, options) : error;\n }\n }\n\n async resizeFile(path: string, operation: FileResizeOperation, options: FileResizeOptions = {}): Promise<void> {\n return this.operation(\"resizeFile\", path, options, async () => {\n const location = await this.resolve(path, options, { allowMissing: options.create === true, resizeCreate: options.create ?? false });\n if (location.synthetic) fail(\"EROFS\");\n const backend = location.mount.backend;\n const capabilities = await backend.capabilitiesFor?.(location.local, options) ?? backend.capabilities;\n options.signal?.throwIfAborted();\n if (capabilities.readOnly === true) fail(\"EROFS\");\n const resize = backend.resizeFile;\n options.signal?.throwIfAborted();\n if (capabilities.atomicResize !== true || typeof resize !== \"function\") fail(\"ENOTSUP\");\n await Reflect.apply(resize!, backend, [location.local, operation, options]);\n });\n }\n\n async openResizeFile(path: string, options: OpenResizeFileOptions = {}): Promise<FileResizeHandle> {\n try {\n options.signal?.throwIfAborted();\n const resolution = this.resolve(path, options, { allowMissing: options.create === true, resizeCreate: options.create ?? false });\n const signal = options.signal;\n const location = await (signal ? new Promise<Location>((resolve, reject) => {\n const abort = (): void => { signal.removeEventListener(\"abort\", abort); reject(signal.reason); };\n signal.addEventListener(\"abort\", abort, { once: true });\n resolution.then(\n value => { signal.removeEventListener(\"abort\", abort); resolve(value); },\n error => { signal.removeEventListener(\"abort\", abort); reject(error); },\n );\n if (signal.aborted) abort();\n }) : resolution);\n options.signal?.throwIfAborted();\n if (location.synthetic) fail(\"EROFS\");\n return await openRetainedResizeFile(location.mount.backend, location.local, options);\n } catch (error) {\n throw error ? this.error(error, \"openResizeFile\", path, options) : error;\n }\n }\n\n private error(error: unknown, syscall: string, path: string, options: FsOptions, dest?: string): unknown {\n if (options.signal?.aborted && error === options.signal.reason) return error;\n return new FsError(toFsError(error).code, {\n cause: error, syscall, path: globalPath(path), ...(dest === undefined ? {} : { dest: globalPath(dest) }),\n });\n }\n\n private async operation<Result>(\n syscall: string, path: string, options: FsOptions,\n action: () => Promise<Result>, dest?: string, preserveReceipt = false,\n ): Promise<Result> {\n try {\n options.signal?.throwIfAborted();\n const result = await action();\n if (!preserveReceipt) options.signal?.throwIfAborted();\n return result;\n } catch (error) {\n throw this.error(error, syscall, path, options, dest);\n }\n }\n\n private components(path: string): Component[] {\n validatePath(path);\n if (!path) fail(\"ENOENT\");\n const parts: Component[] = path.split(\"/\").filter(Boolean).map((name) => ({ name }));\n if (path.endsWith(\"/\")) parts.push({ name: \".\", trailing: true });\n return parts;\n }\n\n private async lookup(path: string, options: FsOptions, parent?: Location, plannedParent = false): Promise<Location> {\n options.signal?.throwIfAborted();\n const mount = this.select(path);\n const local = mount.path === \"/\" ? path : path.slice(mount.path.length) || \"/\";\n let stat: FileStat | undefined;\n if (!parent?.synthetic && !plannedParent || parent?.mount !== mount) {\n try {\n stat = await mount.backend.lstat(local, options);\n } catch (error) {\n if (toFsError(error).code !== \"ENOENT\") throw error;\n }\n }\n options.signal?.throwIfAborted();\n if (path === mount.path && stat?.type !== \"directory\") fail(stat ? \"ENOTDIR\" : \"ENOENT\");\n const synthetic = this.protected(path) && stat?.type !== \"directory\";\n return { path, mount, local, stat: synthetic ? syntheticStat : stat, synthetic };\n }\n\n private async resolve(path: string, options: FsOptions, settings: ResolveOptions = {}): Promise<Location> {\n let pending = this.components(path);\n const stack = [await this.lookup(\"/\", options)];\n let boundary: Mount | undefined;\n let verification: { mount: Mount; path: string; finalName: string | undefined } | undefined;\n let creationVerification: typeof verification;\n const verified = async (location: Location): Promise<Location> => {\n const inspection = !location.stat && settings.resizeCreate === true ? creationVerification : verification;\n if (inspection) {\n const canonical = await inspection.mount.backend.realpath(inspection.path, options);\n validatePath(canonical);\n if (!canonical.startsWith(\"/\") || normalizePath(canonical) !== canonical) fail(\"EIO\");\n if (inspection.finalName !== undefined) {\n try {\n await inspection.mount.backend.lstat(`${inspection.path}/${inspection.finalName}`, options);\n if (!location.stat && settings.resizeCreate === true) fail(\"ENOTSUP\");\n } catch (error) {\n if (location.stat || toFsError(error).code !== \"ENOENT\") throw error;\n }\n }\n const expected = inspection.finalName === undefined ? canonical\n : `${canonical === \"/\" ? \"\" : canonical}/${inspection.finalName}`;\n if (location.mount !== inspection.mount || location.local !== expected) fail(\"ENOTSUP\");\n }\n return location;\n };\n let links = 0;\n while (pending.length > 0) {\n options.signal?.throwIfAborted();\n const component = pending.shift()!;\n const current = stack[stack.length - 1]!;\n if (current.stat?.type !== \"directory\") fail(\"ENOTDIR\");\n if (component.trailing && pending.length === 0 && settings.resizeCreate !== undefined) fail(\"EISDIR\");\n if (!current.synthetic && !settings.createDirectories?.has(current.path)) {\n const mode = settings.resizeCreate === undefined && current.mount.backend.capabilities.permissions === false ? 0 : 1;\n await current.mount.backend.access(current.local, mode, options);\n }\n if (component.name === \".\") continue;\n if (component.name === \"..\") {\n if (boundary && current.path === boundary.path) fail(\"EACCES\");\n if (stack.length > 1) stack.pop();\n if (boundary && stack[stack.length - 1]!.mount !== boundary) fail(\"EACCES\");\n continue;\n }\n const nextPath = `${current.path === \"/\" ? \"\" : current.path}/${component.name}`;\n if (boundary && this.select(nextPath) !== boundary) fail(\"EACCES\");\n if (settings.resizeCreate === true && pending.length === 1 && pending[0]!.trailing) fail(\"EISDIR\");\n let next = settings.createDirectories?.get(nextPath)\n ?? await this.lookup(nextPath, options, current, settings.createDirectories?.has(current.path));\n if (!next.stat) {\n if (settings.createDirectories) {\n if (current.synthetic) fail(\"ENOTSUP\");\n this.mutable(next);\n next = { ...next, stat: syntheticStat };\n settings.createDirectories.set(nextPath, next);\n } else if (settings.allowMissing && (pending.length === 0\n || settings.missingDirectory && pending.length === 1 && pending[0]!.trailing)) {\n if (current.synthetic) fail(\"ENOTSUP\");\n return verified(next);\n } else {\n fail(\"ENOENT\");\n }\n }\n const final = pending.length === 0\n || settings.entry && pending.length === 1 && pending[0]!.trailing;\n if (next.stat?.type === \"symlink\" && (settings.followFinal !== false || !final)) {\n if (++links > 40) fail(\"ELOOP\");\n boundary ??= next.mount;\n if (boundary !== next.mount) fail(\"EACCES\");\n if (!verification) {\n const suffix = pending.map((part) => part.name);\n const last = suffix.at(-1);\n const finalName = settings.followFinal === false && last !== undefined && last !== \".\" && last !== \"..\"\n ? suffix.pop() : undefined;\n verification = {\n mount: next.mount,\n path: `${next.local}${suffix.length === 0 ? \"\" : `/${suffix.join(\"/\")}`}`,\n finalName,\n };\n }\n const readlink = this.optional(next, \"readlink\", \"symlinks\");\n const target = await readlink.call(next.mount.backend, next.local, options);\n const targetParts = this.components(target);\n if (settings.resizeCreate !== undefined && targetParts.at(-1)?.trailing && pending[0]?.trailing) targetParts.pop();\n if (settings.resizeCreate === true) {\n const remainder = [...targetParts, ...pending];\n const finalName = remainder.at(-1)?.name;\n if (finalName !== undefined && finalName !== \".\" && finalName !== \"..\") {\n const parent = target.startsWith(\"/\") ? \"\" : next.local.slice(0, next.local.lastIndexOf(\"/\"));\n creationVerification = {\n mount: next.mount,\n path: `${parent}/${remainder.slice(0, -1).map(part => part.name).join(\"/\")}`,\n finalName,\n };\n }\n }\n if (target.startsWith(\"/\")) {\n const rootIndex = stack.findIndex((entry) => entry.path === next.mount.path);\n if (rootIndex < 0) fail(\"EACCES\");\n stack.splice(rootIndex + 1);\n }\n pending = [...targetParts, ...pending];\n } else {\n stack.push(next);\n }\n }\n return verified(stack[stack.length - 1]!);\n }\n\n private mutable(location: Location): void {\n if (this.protected(location.path)) fail(\"EBUSY\");\n if (location.mount.backend.capabilities.readOnly) fail(\"EROFS\");\n }\n\n private entryPath(path: string): void {\n const terminal = path.split(\"/\").filter(Boolean).at(-1);\n if (terminal === \".\" || terminal === \"..\") fail(\"EINVAL\");\n }\n\n private optional<Method extends \"readlink\" | \"symlink\" | \"link\" | \"chmod\" | \"utimes\" | \"truncate\" | \"readStream\" | \"writeStream\">(\n location: Location, method: Method, capability?: string,\n ): NonNullable<FileSystem[Method]> {\n const backend = location.mount.backend;\n const implementation = backend[method];\n if (!implementation || capability && backend.capabilities[capability] === false) fail(\"ENOTSUP\");\n return implementation as NonNullable<FileSystem[Method]>;\n }\n\n readFile(path: string, options: ReadFileOptions = {}): Promise<Uint8Array> {\n return this.operation(\"readFile\", path, options, async () => {\n const location = await this.resolve(path, options);\n if (location.synthetic) fail(\"EISDIR\");\n return location.mount.backend.readFile(location.local, options);\n });\n }\n\n open(path: string, options: OpenFileOptions): Promise<FileDescriptor> {\n return openFileDescriptor(globalPath(path), options, {\n positionedRead: true, positionedWrite: true, truncate: true, synchronization: \"storage\",\n }, async admitted => {\n try {\n const location = await this.resolve(path, admitted, {\n allowMissing: admitted.creation !== \"never\", followFinal: admitted.creation !== \"exclusive\",\n });\n if (location.synthetic) fail(\"EISDIR\");\n if (admitted.access !== \"read\" || admitted.creation !== \"never\" || admitted.truncate || admitted.append) this.mutable(location);\n const backend = location.mount.backend;\n const capabilities = await backend.capabilitiesFor?.(location.local, admitted) ?? backend.capabilities;\n if (!backend.open || capabilities.open === false) fail(\"ENOTSUP\");\n admitted.signal?.throwIfAborted();\n const descriptor = await backend.open(location.local, admitted);\n try {\n return forwardFileDescriptor(descriptor, (syscall, forwarded, action) => this.operation(syscall, path, forwarded, action), descriptor.capabilities, snapshotStat);\n } catch (error) {\n await finishCleanup(() => descriptor.close(), true);\n throw error;\n }\n } catch (error) {\n admitted.signal?.throwIfAborted();\n throw this.error(error, \"open\", path, admitted);\n }\n });\n }\n\n writeFile(path: string, data: Uint8Array, options: WriteFileOptions = {}): Promise<void> {\n return this.operation(\"writeFile\", path, options, async () => {\n const location = await this.resolve(path, options, { allowMissing: true, followFinal: !options.flag?.endsWith(\"x\") });\n this.mutable(location);\n await location.mount.backend.writeFile(location.local, data, options);\n });\n }\n\n appendFile(path: string, data: Uint8Array, options: AppendFileOptions = {}): Promise<void> {\n return this.operation(\"appendFile\", path, options, async () => {\n const location = await this.resolve(path, options, { allowMissing: true });\n this.mutable(location);\n await location.mount.backend.appendFile(location.local, data, options);\n });\n }\n\n stat(path: string, options: FsOptions = {}): Promise<FileStat> {\n return this.operation(\"stat\", path, options, async () => snapshotStat((await this.resolve(path, options)).stat!));\n }\n\n lstat(path: string, options: FsOptions = {}): Promise<FileStat> {\n return this.operation(\"lstat\", path, options, async () => snapshotStat((await this.resolve(path, options, { followFinal: false })).stat!));\n }\n\n readdir(path: string, options: ReadDirectoryOptions = {}): Promise<DirectoryEntry[]> {\n return this.operation(\"readdir\", path, options, async () => {\n const limit = directoryEntryLimit(options, path);\n const location = await this.resolve(path, options);\n if (location.stat?.type !== \"directory\") fail(\"ENOTDIR\");\n const entries = new Map<string, DirectoryEntry>();\n if (!location.synthetic) {\n const children = await location.mount.backend.readdir(location.local, options);\n options.signal?.throwIfAborted();\n admitDirectoryEntries(children.length, limit, path);\n for (const entry of children) {\n options.signal?.throwIfAborted();\n const { name, type } = entry;\n if (!name || name === \".\" || name === \"..\" || name.includes(\"/\") || name.includes(\"\\0\")) fail(\"EIO\");\n if (!entries.has(name)) admitDirectoryEntries(entries.size + 1, limit, path);\n entries.set(name, { name, type });\n }\n }\n for (const mount of this.mounts) {\n if (mount.path !== location.path && within(location.path, mount.path)) {\n const suffix = mount.path.slice(location.path === \"/\" ? 1 : location.path.length + 1);\n const name = suffix.split(\"/\")[0]!;\n if (!entries.has(name)) admitDirectoryEntries(entries.size + 1, limit, path);\n entries.set(name, { name, type: \"directory\" });\n }\n }\n return [...entries.values()].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);\n });\n }\n\n mkdir(path: string, options: MkdirOptions = {}): Promise<void> {\n return this.operation(\"mkdir\", path, options, async () => {\n const directories = new Map<string, Location>();\n const location = await this.resolve(path, options, options.recursive\n ? { createDirectories: directories }\n : { followFinal: false, allowMissing: true, missingDirectory: true, entry: true });\n if (options.recursive) {\n if (location.stat?.type !== \"directory\") fail(\"EEXIST\");\n for (const directory of directories.values()) {\n options.signal?.throwIfAborted();\n await directory.mount.backend.mkdir(directory.local, { ...options, recursive: false });\n }\n return;\n }\n this.mutable(location);\n await location.mount.backend.mkdir(location.local, options);\n });\n }\n\n rmdir(path: string, options: FsOptions = {}): Promise<void> {\n return this.operation(\"rmdir\", path, options, async () => {\n const location = await this.resolve(path, options, { followFinal: false, entry: true });\n this.mutable(location);\n this.entryPath(path);\n if (location.stat?.type !== \"directory\") fail(\"ENOTDIR\");\n const backend = location.mount.backend;\n if (!backend.rmdir) fail(\"ENOTSUP\");\n options.signal?.throwIfAborted();\n await backend.rmdir(location.local, options);\n });\n }\n\n unlink(path: string, options: FsOptions = {}): Promise<void> {\n return this.operation(\"unlink\", path, options, async () => {\n const location = await this.resolve(path, options, { followFinal: false, entry: true });\n this.mutable(location);\n this.entryPath(path);\n const backend = location.mount.backend;\n if (!backend.unlink) fail(\"ENOTSUP\");\n options.signal?.throwIfAborted();\n await backend.unlink(location.local, options);\n });\n }\n\n rm(path: string, options: RemoveOptions = {}): Promise<void> {\n return this.operation(\"rm\", path, options, async () => {\n let location: Location;\n try {\n location = await this.resolve(path, options, { followFinal: false, entry: true });\n } catch (error) {\n if (options.force && isFsError(error, \"ENOENT\")) return;\n throw error;\n }\n this.mutable(location);\n this.entryPath(path);\n await location.mount.backend.rm(location.local, options);\n });\n }\n\n private async localStaging(staging: FileStaging, options: FsOptions): Promise<{ mount: Mount; staging: FileStaging }> {\n const parent = await this.resolve(staging.parent.path, options, { followFinal: false, entry: true });\n const directory = await this.resolve(staging.directory.path, options, { followFinal: false, entry: true });\n const file = await this.resolve(staging.file.path, options, { followFinal: false, entry: true, allowMissing: true });\n if (parent.mount !== directory.mount || directory.mount !== file.mount) fail(\"EXDEV\");\n if (this.protected(directory.path) || this.protected(file.path)) fail(\"EBUSY\");\n for (const location of [directory, file]) this.mutable(location);\n return { mount: directory.mount, staging: {\n parent: { path: parent.local, stat: staging.parent.stat },\n directory: { path: directory.local, stat: staging.directory.stat },\n file: { path: file.local, stat: staging.file.stat },\n } };\n }\n\n writeFileConditional(path: string, data: Uint8Array, options: ConditionalWriteFileOptions): Promise<FileStat> {\n return this.operation(\"writeFileConditional\", path, options, async () => {\n const location = await this.resolve(path, options, { followFinal: false, entry: true, allowMissing: true });\n if (this.protected(location.path)) fail(\"EBUSY\");\n this.mutable(location);\n const backend = location.mount.backend;\n await requireOwnedMutation(backend, location.local, \"atomicFileMutation\", options, options.expected === null);\n if (!backend.writeFileConditional) fail(\"ENOTSUP\");\n return snapshotStat(await backend.writeFileConditional(location.local, data, options));\n }, undefined, true);\n }\n\n removeEntryConditional(path: string, options: ConditionalRemoveEntryOptions): Promise<void> {\n return this.operation(\"removeEntryConditional\", path, options, async () => {\n const location = await this.resolve(path, options, { followFinal: false, entry: true, allowMissing: true });\n if (this.protected(location.path)) fail(\"EBUSY\");\n this.mutable(location);\n const backend = location.mount.backend;\n await requireOwnedMutation(backend, location.local, \"atomicEntryRemoval\", options);\n if (!backend.removeEntryConditional) fail(\"ENOTSUP\");\n await backend.removeEntryConditional(location.local, options);\n });\n }\n\n removeFileConditional(path: string, options: ConditionalRemoveFileOptions): Promise<void> {\n return this.operation(\"removeFileConditional\", path, options, async () => {\n const location = await this.resolve(path, options, { followFinal: false, entry: true, allowMissing: true });\n if (this.protected(location.path)) fail(\"EBUSY\");\n this.mutable(location);\n const backend = location.mount.backend;\n await requireOwnedMutation(backend, location.local, \"atomicFileMutation\", options);\n if (!backend.removeFileConditional) fail(\"ENOTSUP\");\n await backend.removeFileConditional(location.local, options);\n });\n }\n\n removeTreeConditional(path: string, options: ConditionalRemoveEntryOptions): Promise<void> {\n return this.operation(\"removeTreeConditional\", path, options, async () => {\n const location = await this.resolve(path, options, { followFinal: false, entry: true, allowMissing: true });\n if (this.protected(location.path)) fail(\"EBUSY\");\n this.mutable(location);\n const backend = location.mount.backend;\n await requireOwnedMutation(backend, location.local, \"atomicTreeRemoval\", options);\n if (!backend.removeTreeConditional) fail(\"ENOTSUP\");\n await backend.removeTreeConditional(location.local, options);\n });\n }\n\n createStagedFile(path: string, name: string, content: StagedFileContent, options: CreateStagedFileOptions): Promise<FileStaging> {\n return this.operation(\"createStagedFile\", path, options, async () => {\n const location = await this.resolve(path, options, { followFinal: false, entry: true, allowMissing: true, missingDirectory: true });\n if (this.protected(location.path)) fail(\"EBUSY\");\n this.mutable(location);\n const backend = location.mount.backend;\n await requireOwnedMutation(backend, location.local, \"atomicFileStaging\", options, true);\n if (!backend.createStagedFile) fail(\"ENOTSUP\");\n const receipt = await backend.createStagedFile(location.local, name, content, options);\n const map = (entry: FileStagingEntry): FileStagingEntry => Object.freeze({\n path: location.mount.path === \"/\" ? entry.path : `${location.mount.path}${entry.path === \"/\" ? \"\" : entry.path}`,\n stat: Object.freeze(snapshotStat(entry.stat)),\n });\n return Object.freeze({ parent: map(receipt.parent), directory: map(receipt.directory), file: map(receipt.file) });\n }, undefined, true);\n }\n\n publishStagedFile(staging: FileStaging, destination: string, options: PublishStagedFileOptions): Promise<void> {\n return this.operation(\"publishStagedFile\", staging.file.path, options, async () => {\n const local = await this.localStaging(staging, options);\n const target = await this.resolve(destination, options, { followFinal: false, entry: true, allowMissing: true });\n if (this.protected(target.path)) fail(\"EBUSY\");\n if (local.mount !== target.mount) fail(\"EXDEV\");\n this.mutable(target);\n await requireOwnedMutation(local.mount.backend, local.staging.directory.path, \"atomicFileStaging\", options);\n if (!local.mount.backend.publishStagedFile) fail(\"ENOTSUP\");\n await local.mount.backend.publishStagedFile(local.staging, target.local, options);\n }, destination);\n }\n\n removeStagedFile(staging: FileStaging, options: FsOptions = {}): Promise<void> {\n return this.operation(\"removeStagedFile\", staging.directory.path, options, async () => {\n const local = await this.localStaging(staging, options);\n await requireOwnedMutation(local.mount.backend, local.staging.directory.path, \"atomicFileStaging\", options);\n if (!local.mount.backend.removeStagedFile) fail(\"ENOTSUP\");\n await local.mount.backend.removeStagedFile(local.staging, options);\n });\n }\n\n prepareDirectory(path: string, options: PrepareDirectoryOptions): Promise<FileStat> {\n return this.operation(\"prepareDirectory\", path, options, async () => {\n const location = await this.resolve(path, options, { followFinal: false, entry: true, allowMissing: true, missingDirectory: true });\n if (this.protected(location.path)) fail(\"EBUSY\");\n this.mutable(location);\n await requireOwnedMutation(location.mount.backend, location.local, \"atomicDirectoryMetadata\", options, options.expected === null);\n if (!location.mount.backend.prepareDirectory) fail(\"ENOTSUP\");\n return snapshotStat(await location.mount.backend.prepareDirectory(location.local, options));\n }, undefined, true);\n }\n\n rename(source: string, destination: string, options: RenameOptions = {}): Promise<void> {\n return this.operation(\"rename\", source, options, async () => {\n const origin = await this.resolve(source, options, { followFinal: false, entry: true });\n const target = await this.resolve(destination, options, {\n followFinal: false, allowMissing: true, entry: true, missingDirectory: origin.stat?.type === \"directory\",\n });\n if (this.protected(origin.path) || this.protected(target.path)) fail(\"EBUSY\");\n if (origin.mount !== target.mount) fail(\"EXDEV\");\n this.mutable(origin);\n this.mutable(target);\n this.entryPath(source);\n this.entryPath(destination);\n if (options.noReplace) {\n const capabilities = await target.mount.backend.capabilitiesFor?.(target.local, options) ?? target.mount.backend.capabilities;\n options.signal?.throwIfAborted();\n if (capabilities.atomicRenameNoReplace !== true) fail(\"ENOTSUP\");\n }\n await origin.mount.backend.rename(origin.local, target.local, options);\n }, destination);\n }\n\n copyFile(source: string, destination: string, options: CopyFileOptions = {}): Promise<void> {\n return this.operation(\"copyFile\", source, options, async () => {\n const origin = await this.resolve(source, options);\n if (origin.stat?.type === \"directory\") fail(\"EISDIR\");\n const target = await this.resolve(destination, options, { allowMissing: true, followFinal: !options.exclusive });\n if (this.protected(target.path)) fail(\"EBUSY\");\n this.mutable(target);\n if (options.exclusive && target.stat) fail(\"EEXIST\");\n if (origin.mount.backend === target.mount.backend && origin.local === target.local) fail(\"EINVAL\");\n let identity = compareIdentity(origin.stat, target.stat);\n if (identity === \"same\") fail(\"EINVAL\");\n if (target.stat?.type === \"directory\") fail(\"EISDIR\");\n if (target.stat && identity === \"unknown\") {\n identity = await compareEntries(origin.mount.backend, origin.local, target.mount.backend, target.local, options);\n if (identity === \"same\") fail(\"EINVAL\");\n }\n if (target.stat && identity === \"unknown\") fail(\"ENOTSUP\");\n if (origin.mount.backend === target.mount.backend) {\n await origin.mount.backend.copyFile(origin.local, target.local, { ...options, exclusive: options.exclusive || !target.stat });\n return;\n }\n const reader = origin.mount.backend;\n const writer = target.mount.backend;\n const writeOptions: WriteFileOptions = {\n ...(options.signal ? { signal: options.signal } : {}), flag: options.exclusive || !target.stat ? \"wx\" : \"w\",\n ...(writer.capabilities.permissions === true ? { mode: origin.stat!.mode & 0o7777 } : {}),\n };\n if (reader.readStream && reader.capabilities.streamingRead !== false\n && writer.writeStream && writer.capabilities.streamingWrite !== false) {\n const source = readBytes(reader.readStream(origin.local, options), options.signal);\n let failed = false;\n try { await writer.writeStream(target.local, source, writeOptions); }\n catch (error) { failed = true; throw error; }\n finally { await finishCleanup(() => source.return(undefined), failed); }\n } else {\n const maxBytes = 64 * 1024 * 1024;\n const data = await reader.readFile(origin.local, { ...options, maxBytes });\n if (data.byteLength > maxBytes) fail(\"EFBIG\");\n options.signal?.throwIfAborted();\n await writer.writeFile(target.local, data, writeOptions);\n }\n }, destination);\n }\n\n realpath(path: string, options: FsOptions = {}): Promise<string> {\n return this.operation(\"realpath\", path, options, async () => (await this.resolve(path, options)).path);\n }\n\n compareEntry(path: string, peer: FileSystem, peerPath: string, options: FsOptions = {}) {\n return this.operation(\"compareEntry\", path, options, () => compareEntries(this, path, peer, peerPath, options), peerPath);\n }\n\n access(path: string, mode = 0, options: FsOptions = {}): Promise<void> {\n return this.operation(\"access\", path, options, async () => {\n if (!Number.isInteger(mode) || mode < 0 || mode > 7) fail(\"EINVAL\");\n const location = await this.resolve(path, options);\n if (location.synthetic) {\n if (mode & 2) fail(\"EACCES\");\n } else {\n await location.mount.backend.access(location.local, mode, options);\n }\n });\n }\n\n readlink(path: string, options: FsOptions = {}): Promise<string> {\n return this.operation(\"readlink\", path, options, async () => {\n const location = await this.resolve(path, options, { followFinal: false });\n if (location.stat?.type !== \"symlink\") fail(\"EINVAL\");\n return this.optional(location, \"readlink\", \"symlinks\").call(location.mount.backend, location.local, options);\n });\n }\n\n symlink(target: string, path: string, options: FsOptions = {}): Promise<void> {\n return this.operation(\"symlink\", path, options, async () => {\n this.components(target);\n const location = await this.resolve(path, options, { followFinal: false, allowMissing: true });\n this.mutable(location);\n await this.optional(location, \"symlink\", \"symlinks\").call(location.mount.backend, target, location.local, options);\n });\n }\n\n link(existingPath: string, newPath: string, options: FsOptions = {}): Promise<void> {\n return this.operation(\"link\", existingPath, options, async () => {\n const origin = await this.resolve(existingPath, options, { followFinal: false, entry: true });\n const target = await this.resolve(newPath, options, { followFinal: false, allowMissing: true, entry: true });\n if (this.protected(origin.path) || this.protected(target.path)) fail(\"EBUSY\");\n if (origin.mount !== target.mount) fail(\"EXDEV\");\n this.mutable(origin);\n this.mutable(target);\n await this.optional(origin, \"link\", \"hardlinks\").call(origin.mount.backend, origin.local, target.local, options);\n }, newPath);\n }\n\n chmod(path: string, mode: number, options: FsOptions = {}): Promise<void> {\n return this.operation(\"chmod\", path, options, async () => {\n const location = await this.resolve(path, options);\n this.mutable(location);\n await this.optional(location, \"chmod\", \"permissions\").call(location.mount.backend, location.local, mode, options);\n });\n }\n\n utimes(path: string, atimeMs: number, mtimeMs: number, options: FsOptions = {}): Promise<void> {\n return this.operation(\"utimes\", path, options, async () => {\n const location = await this.resolve(path, options);\n this.mutable(location);\n await this.optional(location, \"utimes\", \"timestamps\").call(location.mount.backend, location.local, atimeMs, mtimeMs, options);\n });\n }\n\n truncate(path: string, length = 0, options: FsOptions = {}): Promise<void> {\n return this.operation(\"truncate\", path, options, async () => {\n const location = await this.resolve(path, options);\n this.mutable(location);\n await this.optional(location, \"truncate\").call(location.mount.backend, location.local, length, options);\n });\n }\n\n async *readStream(path: string, options: ReadStreamOptions = {}): ByteSource {\n try {\n options.signal?.throwIfAborted();\n const location = await this.resolve(path, options);\n if (location.synthetic) fail(\"EISDIR\");\n const source = this.optional(location, \"readStream\", \"streamingRead\").call(location.mount.backend, location.local, options);\n for await (const chunk of readBytes(source, options.signal)) {\n options.signal?.throwIfAborted();\n yield chunk;\n }\n options.signal?.throwIfAborted();\n } catch (error) {\n throw this.error(error, \"readStream\", path, options);\n }\n }\n\n writeStream(path: string, source: ByteSource, options: WriteFileOptions = {}): Promise<void> {\n return this.operation(\"writeStream\", path, options, async () => {\n const location = await this.resolve(path, options, { allowMissing: true, followFinal: !options.flag?.endsWith(\"x\") });\n this.mutable(location);\n await this.optional(location, \"writeStream\", \"streamingWrite\").call(location.mount.backend, location.local, source, options);\n });\n }\n}\n\nexport function createMountFileSystem(options: MountFileSystemOptions): MountFileSystem {\n return new MountFileSystem(options);\n}\n", "import { platform } from \"#safe-fs-platform\";\nimport { openRetainedReadFile, requireCapabilities, retainedReadCapabilities } from \"../capabilities.js\";\nimport { finishCleanup } from \"../../contracts/cleanup.js\";\nimport { collectBytes, readBytes } from \"../../contracts/io.js\";\nimport type { ByteSource } from \"../../contracts/io.js\";\nimport { FsError, toFsError } from \"../../contracts/errors.js\";\nimport type { ErrnoCode } from \"../../contracts/errors.js\";\nimport { dirname, isPathWithin, normalizePath, validatePath } from \"../../contracts/virtual-path.js\";\nimport { compareIdentity } from \"../mount/identity.js\";\nimport { compareEntries, registerEntryView } from \"../mount/comparison.js\";\nimport { admitDirectoryEntries, directoryEntryLimit } from \"../directory-admission.js\";\nimport type { FileDescriptor, OpenFileOptions } from \"../../contracts/descriptor.js\";\nimport type {\n AppendFileOptions, CapabilityQueryOptions, CopyFileOptions, DirectoryEntry, OpenReadFileOptions,\n FileStat, FileSystem, FileSystemCapabilities, FsOptions, RenameOptions, MkdirOptions,\n ReadDirectoryOptions, ReadFileOptions, ReadStreamOptions, RemoveOptions, WriteFileOptions,\n} from \"../../contracts/filesystem.js\";\n\nexport interface OverlayFileSystemOptions {\n readonly upper: FileSystem;\n readonly lower: FileSystem;\n readonly maxBufferBytes?: number;\n}\n\ninterface Entry {\n path: string;\n backend: FileSystem;\n stat: FileStat;\n}\n\ninterface Location {\n path: string;\n entry?: Entry;\n}\n\ninterface LinkVerification {\n backend: FileSystem;\n path: string;\n finalName: string | undefined;\n moves?: readonly PathMove[];\n}\n\ninterface PathMove {\n source: string;\n destination: string;\n}\n\ninterface LinkOrigin {\n path: string;\n target: string;\n canonical: string;\n moves: readonly PathMove[];\n}\n\ntype LinkMetadata = Pick<FileStat, \"mode\" | \"atimeMs\" | \"mtimeMs\">;\n\nfunction snapshotStat(stat: FileStat): FileStat {\n const { type, size, allocatedBytes, ioBlockSize, preferredIoBlockSize, mode, mtimeMs, atimeMs, ctimeMs, birthtimeMs, revision, identityScope, ino, dev, rdevMajor, rdevMinor, nlink, uid, gid } = stat;\n return {\n type, size, mode, mtimeMs, atimeMs, ctimeMs,\n ...(allocatedBytes === undefined ? {} : { allocatedBytes }),\n ...(ioBlockSize === undefined ? {} : { ioBlockSize }),\n ...(preferredIoBlockSize === undefined ? {} : { preferredIoBlockSize }),\n ...(birthtimeMs === undefined ? {} : { birthtimeMs }),\n ...(revision === undefined ? {} : { revision }),\n ...(identityScope === undefined ? {} : { identityScope }),\n ...(ino === undefined ? {} : { ino }),\n ...(dev === undefined ? {} : { dev }),\n ...(rdevMajor === undefined ? {} : { rdevMajor }),\n ...(rdevMinor === undefined ? {} : { rdevMinor }),\n ...(nlink === undefined ? {} : { nlink }),\n ...(uid === undefined ? {} : { uid }),\n ...(gid === undefined ? {} : { gid }),\n };\n}\n\nfunction hasCode(error: unknown, code: ErrnoCode): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error && error.code === code;\n}\n\nfunction fail(code: ErrnoCode, path: string, message?: string): never {\n throw new FsError(code, { syscall: \"overlay\", path, ...(message === undefined ? {} : { message }) });\n}\n\nfunction integer(value: number, path: string): void {\n if (!Number.isSafeInteger(value) || value < 0) fail(\"EINVAL\", path);\n}\n\nfunction mode(value: number | undefined, path: string): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0 || value > 0o7777)) fail(\"EINVAL\", path);\n}\n\nfunction movedPath(path: string, moves: readonly PathMove[]): string {\n for (const move of moves) {\n if (isPathWithin(move.source, path)) path = move.destination + path.slice(move.source.length);\n }\n return path;\n}\n\nasync function waitForTurn(previous: Promise<void>, signal?: AbortSignal): Promise<void> {\n signal?.throwIfAborted();\n if (!signal) return previous;\n return new Promise<void>((resolve, reject) => {\n const abort = (): void => { signal.removeEventListener(\"abort\", abort); reject(signal.reason); };\n signal.addEventListener(\"abort\", abort, { once: true });\n void previous.then(() => { signal.removeEventListener(\"abort\", abort); resolve(); });\n });\n}\n\nexport class OverlayFileSystem implements FileSystem {\n readonly capabilities: FileSystemCapabilities;\n readonly #upper: FileSystem;\n readonly #lower: FileSystem;\n private readonly maxBufferBytes: number;\n private readonly whiteouts = new Set<string>();\n private readonly opaque = new Set<string>();\n private readonly garbage = new Set<string>();\n private readonly activeStages = new Set<string>();\n private readonly linkMetadata = new Map<string, LinkMetadata>();\n private readonly linkOrigins = new Map<string, LinkOrigin>();\n private queue: Promise<void> = Promise.resolve();\n\n constructor(options: OverlayFileSystemOptions) {\n if (options.upper === options.lower) throw new TypeError(\"Overlay upper and lower must be distinct backends\");\n this.#upper = options.upper;\n this.#lower = options.lower;\n registerEntryView(this, (path, options) => this.run(options, async () => {\n const entry = await this.required(path, options);\n return { filesystem: entry.backend, path: entry.path, readOnly: this.capabilities.readOnly === true };\n }, false));\n this.maxBufferBytes = options.maxBufferBytes ?? 64 * 1024 * 1024;\n integer(this.maxBufferBytes, \"/\");\n const writable = !this.#upper.capabilities.readOnly && this.#upper.capabilities.atomicRename === true;\n const readable = [this.#upper, this.#lower].map((backend) =>\n typeof backend.readStream === \"function\" ? backend.capabilities.streamingRead : false);\n const streamingRead = readable.every((capability) => capability === true) ? true\n : readable.every((capability) => capability === false) ? false : undefined;\n const retained = [this.#upper, this.#lower].map((backend) => retainedReadCapabilities(backend).retainedRead);\n const retainedRead = retained.every((capability) => capability === true) ? true\n : retained.every((capability) => capability === false) ? false : undefined;\n const streamingWrite = writable && this.#upper.capabilities.streamingWrite === true\n && this.#upper.capabilities.streamingRead === true\n && typeof this.#upper.writeStream === \"function\" && typeof this.#upper.readStream === \"function\"\n ? readable.every((capability) => capability === true) ? true : undefined : false;\n const append = !writable || this.#upper.capabilities.append === false ? false\n : this.#upper.capabilities.append === true ? true : undefined;\n const upper = this.#upper.capabilities;\n const mutation = requireCapabilities(writable, upper.mkdir, upper.rename, upper.remove,\n upper.exclusiveCreate, upper.timestamps, upper.permissions);\n const effectiveAppend = requireCapabilities(append, mutation);\n const effectiveStreamingWrite = requireCapabilities(streamingWrite, mutation);\n const semantics = Object.fromEntries([\n ...[\"read\", \"stat\", \"readdir\", \"realpath\", \"access\"].map(capability => [capability,\n requireCapabilities(upper[capability], this.#lower.capabilities[capability])]),\n [\"write\", requireCapabilities(mutation, upper.write)],\n [\"exclusiveCreate\", requireCapabilities(mutation, upper.exclusiveCreate)],\n [\"mkdir\", requireCapabilities(mutation, upper.mkdir)],\n [\"recursiveMkdir\", requireCapabilities(mutation, upper.recursiveMkdir)],\n [\"remove\", requireCapabilities(mutation, upper.remove)],\n [\"removeDirectory\", requireCapabilities(mutation, upper.removeDirectory)],\n [\"recursiveRemove\", requireCapabilities(mutation, upper.recursiveRemove)],\n [\"rename\", requireCapabilities(mutation, upper.rename, upper.write)],\n [\"copy\", requireCapabilities(mutation, upper.write)],\n [\"exclusiveCopy\", requireCapabilities(mutation, upper.exclusiveCreate)],\n [\"truncate\", requireCapabilities(mutation, upper.truncate)],\n [\"streamingAppend\", requireCapabilities(mutation, streamingWrite, upper.streamingAppend)],\n [\"randomAccessWrite\", requireCapabilities(mutation, upper.randomAccessWrite)],\n [\"explicitDirectories\", requireCapabilities(upper.explicitDirectories, this.#lower.capabilities.explicitDirectories)],\n ].filter(([, value]) => value !== undefined));\n this.capabilities = Object.freeze({\n ...semantics,\n open: false,\n atomicFileMutation: false, atomicFileStaging: false, atomicDirectoryMetadata: false,\n implicitDirectories: false,\n readlink: upper.readlink === true && this.#lower.capabilities.readlink === true ? true\n : upper.readlink === false && this.#lower.capabilities.readlink === false ? false : undefined,\n ...(upper.readOnly === undefined ? {} : { readOnly: upper.readOnly }),\n ...(effectiveAppend === undefined ? {} : { append: effectiveAppend }),\n atomicRename: false, atomicRenameNoReplace: false,\n descriptorWriteStream: false,\n retainedResize: false, atomicResize: false,\n hardlinks: false,\n symlinks: writable && this.#upper.capabilities.symlinks === true\n && typeof this.#upper.symlink === \"function\" && typeof this.#upper.readlink === \"function\"\n && (this.#lower.capabilities.symlinks !== true || typeof this.#lower.readlink === \"function\"),\n permissions: writable && this.#upper.capabilities.permissions === true && typeof this.#upper.chmod === \"function\",\n timestamps: writable && this.#upper.capabilities.timestamps === true && typeof this.#upper.utimes === \"function\",\n ...(streamingRead === undefined ? {} : { streamingRead }),\n ...(retainedRead === undefined ? {} : { retainedRead }),\n ...(effectiveStreamingWrite === undefined ? {} : { streamingWrite: effectiveStreamingWrite }),\n });\n Object.defineProperty(this, \"capabilities\", { writable: false, configurable: false });\n }\n\n async open(path: string, options: OpenFileOptions): Promise<FileDescriptor> {\n options.signal?.throwIfAborted();\n throw new FsError(\"ENOTSUP\", { syscall: \"open\", path });\n }\n\n private async run<Result>(options: FsOptions, operation: () => Promise<Result>, cleanup = true): Promise<Result> {\n options.signal?.throwIfAborted();\n const previous = this.queue;\n let release!: () => void;\n this.queue = new Promise<void>((resolve) => { release = resolve; });\n try { await waitForTurn(previous, options.signal); }\n catch (error) {\n void previous.then(release);\n throw error;\n }\n try {\n options.signal?.throwIfAborted();\n if (cleanup) await this.cleanGarbage(false);\n return await operation();\n } finally {\n release();\n }\n }\n\n capabilitiesFor(path: string, options: CapabilityQueryOptions = {}): Promise<FileSystemCapabilities> {\n return this.run(options, async () => {\n const location = await this.resolve(path, options, true, true);\n const backend = location.entry?.backend ?? this.#upper;\n const capabilities = await backend.capabilitiesFor?.(location.path, options) ?? backend.capabilities;\n options.signal?.throwIfAborted();\n const { retainedRead: ignoredRetainedRead, ...composed } = this.capabilities;\n const retainedRead = retainedReadCapabilities(backend, capabilities).retainedRead;\n return Object.freeze({ ...composed, ...(retainedRead === undefined ? {} : { retainedRead }) });\n }, false);\n }\n\n openReadFile(path: string, options: OpenReadFileOptions = {}) {\n return this.run(options, async () => {\n const entry = await this.required(path, options);\n if (entry.stat.type !== \"file\") {\n const allowDirectory = options.allowDirectory === true;\n options.signal?.throwIfAborted();\n if (entry.stat.type !== \"directory\" || !allowDirectory) fail(\"EISDIR\", path);\n }\n this.permission(entry, 4);\n return openRetainedReadFile(entry.backend, entry.path, options);\n }, false);\n }\n\n private writable(path: string): void {\n if (this.#upper.capabilities.readOnly) fail(\"EROFS\", path);\n if (this.#upper.capabilities.atomicRename !== true) fail(\"ENOTSUP\", path, \"staged mutations require an atomic-rename-capable upper\");\n }\n\n private permission(entry: Entry, mask: number): void {\n if (entry.backend.capabilities.permissions && ((entry.stat.mode >> 6) & mask) !== mask) fail(\"EACCES\", entry.path);\n }\n\n private async maybeStat(backend: FileSystem, path: string, options: FsOptions): Promise<FileStat | undefined> {\n options.signal?.throwIfAborted();\n let stat: FileStat;\n try { stat = await backend.lstat(path, options); }\n catch (error) {\n options.signal?.throwIfAborted();\n if (hasCode(error, \"ENOENT\")) return undefined;\n throw error;\n }\n return snapshotStat(stat);\n }\n\n private hidden(path: string): boolean {\n return [...this.garbage, ...this.activeStages].some((root) => isPathWithin(root, path));\n }\n\n private async lowerVisible(path: string, options: FsOptions): Promise<boolean> {\n for (const root of this.whiteouts) if (isPathWithin(root, path)) return false;\n for (const root of this.opaque) if (root !== path && isPathWithin(root, path)) return false;\n const ancestors = path.split(\"/\").filter(Boolean).slice(0, -1);\n let parent = \"\";\n for (const component of ancestors) {\n parent += `/${component}`;\n const stat = await this.maybeStat(this.#lower, parent, options);\n if (!stat || stat.type !== \"directory\") return false;\n }\n return true;\n }\n\n private async lookup(path: string, options: FsOptions): Promise<Entry | undefined> {\n if (this.hidden(path)) return undefined;\n const upper = await this.maybeStat(this.#upper, path, options);\n if (upper) return { path, backend: this.#upper, stat: { ...upper, ...(upper.type === \"symlink\" ? this.linkMetadata.get(path) : {}) } };\n if (!await this.lowerVisible(path, options)) return undefined;\n const lower = await this.maybeStat(this.#lower, path, options);\n return lower ? { path, backend: this.#lower, stat: lower } : undefined;\n }\n\n private async resolve(path: string, options: FsOptions, followFinal = true, allowMissing = false, createMode?: number): Promise<Location> {\n validatePath(path);\n if (!path) fail(\"ENOENT\", path);\n const pending = path.split(\"/\").filter(Boolean);\n if (path.endsWith(\"/\")) pending.push(\".\");\n const verifications: LinkVerification[] = [];\n const verified = async (location: Location): Promise<Location> => {\n for (const verification of verifications) {\n const canonical = await verification.backend.realpath(verification.path, options);\n options.signal?.throwIfAborted();\n validatePath(canonical);\n if (!canonical.startsWith(\"/\")) fail(\"EIO\", verification.path, \"backend returned a nonabsolute realpath\");\n if (verification.finalName !== undefined) {\n try {\n await verification.backend.lstat(`${verification.path}/${verification.finalName}`, options);\n } catch (error) {\n if (location.entry || !hasCode(error, \"ENOENT\")) throw error;\n }\n }\n const expected = verification.finalName === undefined ? canonical\n : `${canonical === \"/\" ? \"\" : canonical}/${verification.finalName}`;\n if (location.path !== movedPath(expected, verification.moves ?? [])) fail(\"ENOTSUP\", path, \"backend cannot confirm the overlay symlink namespace\");\n }\n options.signal?.throwIfAborted();\n return location;\n };\n let current = \"/\";\n let links = 0;\n while (pending.length) {\n options.signal?.throwIfAborted();\n const parent = await this.lookup(current, options);\n if (!parent) fail(\"ENOENT\", current);\n if (parent.stat.type !== \"directory\") fail(\"ENOTDIR\", current);\n this.permission(parent, 1);\n const component = pending.shift()!;\n if (component === \".\") continue;\n if (component === \"..\") { current = dirname(current); continue; }\n if (new TextEncoder().encode(component).byteLength > 255) fail(\"ENAMETOOLONG\", path);\n const candidate = current === \"/\" ? `/${component}` : `${current}/${component}`;\n if (this.hidden(candidate)) fail(allowMissing || createMode !== undefined ? \"EBUSY\" : \"ENOENT\", candidate);\n let entry = await this.lookup(candidate, options);\n if (!entry && createMode !== undefined) {\n if (verifications.length) fail(\"ENOTSUP\", path, \"recursive creation through symlinks cannot be verified before mutation\");\n await this.makeDirectory(candidate, createMode, options);\n entry = await this.lookup(candidate, options);\n }\n if (!entry) {\n if (allowMissing && pending.length === 0) return verified({ path: candidate });\n fail(\"ENOENT\", candidate);\n }\n if (entry.stat.type === \"symlink\" && (followFinal || pending.length > 0)) {\n if (++links > 40) fail(\"ELOOP\", path);\n const suffix = [...pending];\n const last = suffix.at(-1);\n const finalName = !followFinal && last !== undefined && last !== \".\" && last !== \"..\" ? suffix.pop() : undefined;\n verifications.push({\n backend: entry.backend,\n path: candidate + (suffix.length ? `/${suffix.join(\"/\")}` : \"\"),\n finalName,\n });\n const origin = entry.backend === this.#upper ? this.linkOrigins.get(candidate) : undefined;\n if (origin) verifications.push({\n backend: this.#lower,\n path: origin.path + (suffix.length ? `/${suffix.join(\"/\")}` : \"\"),\n finalName,\n moves: origin.moves,\n });\n const target = await this.linkTarget(entry, options);\n const parts = target.split(\"/\").filter(Boolean);\n if (target.endsWith(\"/\")) parts.push(\".\");\n pending.unshift(...parts);\n if (target.startsWith(\"/\")) current = \"/\";\n } else current = candidate;\n }\n const entry = await this.lookup(current, options);\n if (!entry) fail(\"ENOENT\", current);\n return verified({ path: current, entry });\n }\n\n private async linkTarget(entry: Entry, options: FsOptions): Promise<string> {\n if (!entry.backend.readlink) fail(\"ENOTSUP\", entry.path);\n const target = await entry.backend.readlink(entry.path, options);\n options.signal?.throwIfAborted();\n validatePath(target);\n if (!target) fail(\"ENOENT\", entry.path);\n return target;\n }\n\n private async movableLinkTarget(entry: Entry, options: FsOptions): Promise<string> {\n const target = await this.linkTarget(entry, options);\n const canonical = await entry.backend.realpath(entry.path, options);\n options.signal?.throwIfAborted();\n const parts = target.split(\"/\").filter(Boolean);\n if (target.endsWith(\"/\")) parts.push(\".\");\n let current = target.startsWith(\"/\") ? \"/\" : dirname(entry.path);\n let stat = await this.maybeStat(entry.backend, current, options);\n for (const part of parts) {\n if (!stat) fail(\"ENOENT\", current);\n if (stat.type !== \"directory\") fail(\"ENOTSUP\", entry.path, \"symlink copy-up requires an alias-free target path\");\n if (part === \".\") continue;\n current = part === \"..\" ? dirname(current) : `${current === \"/\" ? \"\" : current}/${part}`;\n stat = await this.maybeStat(entry.backend, current, options);\n if (stat?.type === \"symlink\") fail(\"ENOTSUP\", entry.path, \"symlink copy-up cannot preserve an ambiguous target alias\");\n }\n if (!stat) fail(\"ENOENT\", current);\n if (canonical !== current) fail(\"ENOTSUP\", entry.path, \"backend cannot prove symlink semantics survive copy-up\");\n return target;\n }\n\n private async required(path: string, options: FsOptions, followFinal = true): Promise<Entry> {\n return (await this.resolve(path, options, followFinal)).entry!;\n }\n\n private async listing(entry: Entry, options: FsOptions, limit?: number): Promise<DirectoryEntry[]> {\n if (entry.stat.type !== \"directory\") fail(\"ENOTDIR\", entry.path);\n this.permission(entry, 4);\n const names = new Set<string>();\n const admit = (name: string): void => {\n options.signal?.throwIfAborted();\n if (!names.has(name)) admitDirectoryEntries(names.size + 1, limit, entry.path);\n names.add(name);\n };\n const upper = await this.maybeStat(this.#upper, entry.path, options);\n if (upper?.type === \"directory\") {\n const children = await this.#upper.readdir(entry.path, options);\n options.signal?.throwIfAborted();\n admitDirectoryEntries(children.length, limit, entry.path);\n for (const child of children) admit(child.name);\n }\n if (await this.lowerVisible(entry.path, options) && !this.opaque.has(entry.path)) {\n const lower = await this.maybeStat(this.#lower, entry.path, options);\n if (lower?.type === \"directory\") {\n const children = await this.#lower.readdir(entry.path, options);\n options.signal?.throwIfAborted();\n admitDirectoryEntries(children.length, limit, entry.path);\n for (const child of children) admit(child.name);\n }\n }\n const entries: DirectoryEntry[] = [];\n for (const name of [...names].sort()) {\n if (!name || name === \".\" || name === \"..\" || name.includes(\"/\") || name.includes(\"\\0\")) fail(\"EIO\", entry.path, \"invalid backend directory entry\");\n const child = await this.lookup(entry.path === \"/\" ? `/${name}` : `${entry.path}/${name}`, options);\n if (child) entries.push({ name, type: child.stat.type });\n }\n return entries;\n }\n\n private async bytes(entry: Entry, options: ReadFileOptions): Promise<Uint8Array> {\n if (entry.stat.type !== \"file\") fail(\"EISDIR\", entry.path);\n this.permission(entry, 4);\n if (options.maxBytes !== undefined) integer(options.maxBytes, entry.path);\n const limit = Math.min(options.maxBytes ?? this.maxBufferBytes, this.maxBufferBytes);\n if (entry.stat.size > limit) fail(\"EFBIG\", entry.path);\n const result = await entry.backend.readFile(entry.path, { ...options, maxBytes: limit });\n options.signal?.throwIfAborted();\n if (!(result instanceof Uint8Array)) fail(\"EIO\", entry.path, \"backend returned non-byte data\");\n if (result.byteLength > limit) fail(\"EFBIG\", entry.path);\n return new Uint8Array(result);\n }\n\n private async cleanGarbage(strict: boolean): Promise<void> {\n const failures: unknown[] = [];\n for (const path of this.garbage) {\n try {\n await this.#upper.rm(path, { recursive: true, force: true });\n this.garbage.delete(path);\n } catch (error) { failures.push(error); }\n }\n if (strict && failures.length) throw new AggregateError(failures, \"Overlay staging cleanup failed\");\n }\n\n async cleanup(options: FsOptions = {}): Promise<void> {\n return this.run(options, () => this.cleanGarbage(true));\n }\n\n private async staged<Result>(options: FsOptions, operation: (path: string) => Promise<Result>): Promise<Result> {\n const root = `/.virtual-bash-overlay-${platform.randomUUID()}`;\n if (await this.maybeStat(this.#upper, root, options) || await this.maybeStat(this.#lower, root, options)) fail(\"EEXIST\", root);\n this.activeStages.add(root);\n try {\n await this.#upper.mkdir(root, { ...options, mode: 0o700 });\n return await operation(`${root}/entry`);\n } finally {\n this.activeStages.delete(root);\n this.garbage.add(root);\n await this.cleanGarbage(false);\n }\n }\n\n private async preserve(path: string, stat: FileStat, options: FsOptions): Promise<void> {\n if (this.#upper.chmod) await this.#upper.chmod(path, stat.mode & 0o7777, options);\n else if (((await this.#upper.lstat(path, options)).mode & 0o7777) !== (stat.mode & 0o7777)) fail(\"ENOTSUP\", path, \"upper cannot preserve modes\");\n if (!this.#upper.utimes) fail(\"ENOTSUP\", path, \"upper cannot preserve timestamps during copy-up\");\n await this.#upper.utimes(path, stat.atimeMs, stat.mtimeMs, options);\n }\n\n private async clone(entry: Entry, destination: string, options: FsOptions, streaming = false): Promise<void> {\n if (entry.stat.type !== \"directory\" && ((entry.stat.nlink ?? 1) > 1\n || (entry.backend.capabilities.hardlinks === true && entry.stat.nlink === undefined))) {\n fail(\"ENOTSUP\", entry.path, \"copy-up cannot preserve hardlink identity\");\n }\n if (entry.stat.type === \"symlink\") {\n if (!this.capabilities.symlinks || !entry.backend.readlink || !this.#upper.symlink) fail(\"ENOTSUP\", entry.path);\n await this.#upper.symlink(await this.movableLinkTarget(entry, options), destination, options);\n return;\n }\n if (entry.stat.type === \"directory\") await this.#upper.mkdir(destination, { ...options, mode: entry.stat.mode & 0o7777 });\n else if (streaming && entry.backend.readStream && entry.backend.capabilities.streamingRead !== false && this.#upper.writeStream) {\n this.permission(entry, 4);\n if (entry.stat.size > this.maxBufferBytes) fail(\"EFBIG\", entry.path);\n const source = this.bounded(entry.backend.readStream(entry.path, options), entry.path, options);\n await this.streamToUpper(destination, source, { ...options, mode: 0o600, flag: \"wx\" });\n } else await this.#upper.writeFile(destination, await this.bytes(entry, options), { ...options, mode: 0o600, flag: \"wx\" });\n await this.preserve(destination, entry.stat, options);\n }\n\n private rememberLink(entry: Entry, destination: string): void {\n this.linkMetadata.delete(destination);\n if (entry.stat.type === \"symlink\") {\n this.linkMetadata.set(destination, { mode: entry.stat.mode, atimeMs: entry.stat.atimeMs, mtimeMs: entry.stat.mtimeMs });\n }\n }\n\n private async ensureDirectory(path: string, options: FsOptions): Promise<void> {\n const entry = await this.lookup(path, options);\n if (!entry) fail(\"ENOENT\", path);\n if (entry.stat.type !== \"directory\") fail(\"ENOTDIR\", path);\n if (entry.backend === this.#upper) return;\n await this.copyUp(entry, options);\n }\n\n private async copyUp(entry: Entry, options: FsOptions): Promise<void> {\n if (entry.backend === this.#upper) return;\n if (entry.path === \"/\") fail(\"ENOTSUP\", entry.path, \"upper must have a directory root\");\n let origin: LinkOrigin | undefined;\n if (entry.stat.type === \"symlink\") {\n const target = await this.movableLinkTarget(entry, options);\n origin = { path: entry.path, target, canonical: normalizePath(target, dirname(entry.path)), moves: [] };\n }\n await this.ensureDirectory(dirname(entry.path), options);\n await this.staged(options, async (temporary) => {\n await this.clone(entry, temporary, options);\n options.signal?.throwIfAborted();\n await this.#upper.rename(temporary, entry.path, options);\n this.rememberLink(entry, entry.path);\n if (origin) this.linkOrigins.set(entry.path, origin);\n });\n }\n\n private async parent(path: string, options: FsOptions): Promise<void> {\n const parent = await this.lookup(dirname(path), options);\n if (!parent) fail(\"ENOENT\", dirname(path));\n if (parent.stat.type !== \"directory\") fail(\"ENOTDIR\", dirname(path));\n this.permission(parent, 3);\n await this.ensureDirectory(parent.path, options);\n }\n\n private async makeDirectory(path: string, permissions: number, options: FsOptions): Promise<void> {\n await this.parent(path, options);\n await this.staged(options, async (temporary) => {\n await this.#upper.mkdir(temporary, { ...options, mode: permissions });\n options.signal?.throwIfAborted();\n await this.#upper.rename(temporary, path, options);\n this.opaque.add(path);\n this.linkMetadata.delete(path);\n this.linkOrigins.delete(path);\n });\n }\n\n private writeOptions(path: string, options: WriteFileOptions): void {\n this.writable(path);\n mode(options.mode, path);\n if (![\"w\", \"wx\", \"a\", \"ax\"].includes(options.flag ?? \"w\")) fail(\"EINVAL\", path);\n }\n\n private async writeLocation(path: string, options: WriteFileOptions): Promise<Location> {\n const exclusive = options.flag === \"wx\" || options.flag === \"ax\";\n const location = await this.resolve(path, options, !exclusive, true);\n if (exclusive && location.entry) fail(\"EEXIST\", path);\n if (location.entry) {\n if (location.entry.stat.type !== \"file\") fail(\"EISDIR\", path);\n this.permission(location.entry, 2);\n }\n return location;\n }\n\n private async replace(location: Location, options: FsOptions, operation: (temporary: string) => Promise<void>, streaming = false): Promise<void> {\n await this.parent(location.path, options);\n await this.staged(options, async (temporary) => {\n if (location.entry) await this.clone(location.entry, temporary, options, streaming);\n await operation(temporary);\n options.signal?.throwIfAborted();\n await this.#upper.rename(temporary, location.path, options);\n this.linkMetadata.delete(location.path);\n this.linkOrigins.delete(location.path);\n });\n }\n\n async readFile(path: string, options: ReadFileOptions = {}): Promise<Uint8Array> {\n return this.run(options, async () => this.bytes(await this.required(path, options), options));\n }\n\n async writeFile(path: string, data: Uint8Array, options: WriteFileOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n this.writeOptions(path, options);\n if (!(data instanceof Uint8Array)) throw new TypeError(\"Overlay files require Uint8Array data\");\n if (data.byteLength > this.maxBufferBytes) fail(\"EFBIG\", path);\n const bytes = new Uint8Array(data);\n return this.run(options, async () => {\n const location = await this.writeLocation(path, options);\n const append = options.flag === \"a\" || options.flag === \"ax\";\n if (append && (location.entry?.stat.size ?? 0) + bytes.byteLength > this.maxBufferBytes) fail(\"EFBIG\", path);\n await this.replace(location, options, async (temporary) => {\n await this.#upper.writeFile(temporary, bytes, { ...options, flag: append ? \"a\" : \"w\" });\n });\n });\n }\n\n async appendFile(path: string, data: Uint8Array, options: AppendFileOptions = {}): Promise<void> {\n return this.writeFile(path, data, { ...options, flag: \"a\" });\n }\n\n async stat(path: string, options: FsOptions = {}): Promise<FileStat> {\n return this.run(options, async () => snapshotStat((await this.required(path, options)).stat), false);\n }\n\n async lstat(path: string, options: FsOptions = {}): Promise<FileStat> {\n return this.run(options, async () => snapshotStat((await this.required(path, options, false)).stat), false);\n }\n\n compareEntry(path: string, peer: FileSystem, peerPath: string, options: FsOptions = {}) {\n return compareEntries(this, path, peer, peerPath, options);\n }\n\n async readdir(path: string, options: ReadDirectoryOptions = {}): Promise<DirectoryEntry[]> {\n const limit = directoryEntryLimit(options, path);\n return this.run(options, async () => this.listing(await this.required(path, options), options, limit), false);\n }\n\n async realpath(path: string, options: FsOptions = {}): Promise<string> {\n return this.run(options, async () => (await this.required(path, options)).path, false);\n }\n\n async access(path: string, requestedMode = 0, options: FsOptions = {}): Promise<void> {\n return this.run(options, async () => {\n if (!Number.isInteger(requestedMode) || requestedMode < 0 || requestedMode > 7) fail(\"EINVAL\", path);\n const entry = await this.required(path, options);\n if (requestedMode & 2) this.writable(path);\n this.permission(entry, requestedMode);\n await entry.backend.access(entry.path, requestedMode & ~2, options);\n }, false);\n }\n\n async mkdir(path: string, options: MkdirOptions = {}): Promise<void> {\n return this.run(options, async () => {\n this.writable(path);\n mode(options.mode, path);\n validatePath(path);\n if (options.recursive) {\n const entry = (await this.resolve(path, options, true, false, options.mode ?? 0o777)).entry!;\n if (entry.stat.type !== \"directory\") fail(\"EEXIST\", path);\n } else {\n const location = await this.resolve(path.replace(/\\/+$/, \"\") || (path ? \"/\" : \"\"), options, false, true);\n if (location.entry) fail(\"EEXIST\", path);\n await this.makeDirectory(location.path, options.mode ?? 0o777, options);\n }\n });\n }\n\n async rmdir(path: string, options: FsOptions = {}): Promise<void> {\n try {\n await this.run(options, async () => {\n this.writable(path);\n validatePath(path);\n const entry = await this.required(path.replace(/\\/+$/, \"\") || (path ? \"/\" : \"\"), options, false);\n if (/(?:^|\\/)\\.{1,2}\\/*$/.test(path)) fail(\"EINVAL\", path);\n if (entry.path === \"/\") fail(\"EBUSY\", path);\n if (entry.stat.type !== \"directory\") fail(\"ENOTDIR\", path);\n const parent = await this.required(dirname(entry.path), options);\n this.permission(parent, 3);\n if ((await this.listing(entry, options)).length) fail(\"ENOTEMPTY\", path);\n options.signal?.throwIfAborted();\n if (this.#upper.capabilities.snapshotRmdir === true) {\n fail(\"ENOTSUP\", path, \"snapshot-marker upper removal cannot safely publish an overlay whiteout\");\n }\n if (entry.backend === this.#upper) {\n if (!this.#upper.rmdir) fail(\"ENOTSUP\", path);\n await this.#upper.rmdir(entry.path, options);\n }\n this.whiteouts.add(entry.path);\n for (const key of this.linkMetadata.keys()) if (isPathWithin(entry.path, key)) this.linkMetadata.delete(key);\n for (const key of this.linkOrigins.keys()) if (isPathWithin(entry.path, key)) this.linkOrigins.delete(key);\n }, false);\n } catch (error) {\n options.signal?.throwIfAborted();\n throw new FsError(toFsError(error).code, { syscall: \"rmdir\", path, cause: error });\n }\n }\n\n async rm(path: string, options: RemoveOptions = {}): Promise<void> {\n return this.run(options, async () => {\n this.writable(path);\n let entry: Entry;\n try { entry = await this.required(path, options, false); }\n catch (error) { if (options.force && hasCode(error, \"ENOENT\")) return; throw error; }\n if (entry.path === \"/\") fail(\"EBUSY\", path);\n if (entry.stat.type === \"directory\" && !options.recursive && (await this.listing(entry, options)).length) fail(\"ENOTEMPTY\", path);\n await this.parent(entry.path, options);\n if (entry.backend === this.#upper) {\n await this.staged(options, async (temporary) => {\n options.signal?.throwIfAborted();\n await this.#upper.rename(entry.path, temporary, options);\n this.whiteouts.add(entry.path);\n });\n } else {\n options.signal?.throwIfAborted();\n this.whiteouts.add(entry.path);\n }\n for (const key of this.linkMetadata.keys()) if (isPathWithin(entry.path, key)) this.linkMetadata.delete(key);\n for (const key of this.linkOrigins.keys()) if (isPathWithin(entry.path, key)) this.linkOrigins.delete(key);\n });\n }\n\n private async materialize(entry: Entry, options: FsOptions): Promise<void> {\n if (entry.stat.type === \"symlink\" && entry.backend === this.#upper) await this.movableLinkTarget(entry, options);\n const children = entry.stat.type === \"directory\" ? await this.listing(entry, options) : [];\n await this.copyUp(entry, options);\n for (const child of children) {\n const path = `${entry.path}/${child.name}`;\n const visible = await this.lookup(path, options);\n if (!visible) fail(\"EIO\", path, \"visible tree changed during materialization\");\n await this.materialize(visible, options);\n }\n if (entry.stat.type === \"directory\") await this.preserve(entry.path, entry.stat, options);\n }\n\n async rename(source: string, destination: string, options: RenameOptions = {}): Promise<void> {\n return this.run(options, async () => {\n if (options.noReplace) fail(\"ENOTSUP\", source, \"atomic no-replace rename is unsupported\");\n this.writable(source);\n const original = await this.required(source, options, false);\n const target = await this.resolve(destination, options, false, true);\n if (original.path === target.path) return;\n if (original.path === \"/\" || target.path === \"/\") fail(\"EBUSY\", source);\n if (original.stat.type === \"directory\" && isPathWithin(original.path, target.path)) fail(\"EINVAL\", destination);\n if (target.entry) {\n if (original.stat.type === \"directory\" && target.entry.stat.type !== \"directory\") fail(\"ENOTDIR\", destination);\n if (original.stat.type !== \"directory\" && target.entry.stat.type === \"directory\") fail(\"EISDIR\", destination);\n if (target.entry.stat.type === \"directory\" && (await this.listing(target.entry, options)).length) fail(\"ENOTEMPTY\", destination);\n }\n await this.parent(original.path, options);\n await this.parent(target.path, options);\n await this.materialize(original, options);\n options.signal?.throwIfAborted();\n const move = { source: original.path, destination: target.path };\n const movedOrigins: [string, LinkOrigin][] = [];\n for (const [path, origin] of this.linkOrigins) {\n if (!isPathWithin(original.path, path)) continue;\n const destination = movedPath(path, [move]);\n const moves = origin.target.startsWith(\"/\") ? origin.moves : [...origin.moves, move];\n if (normalizePath(origin.target, dirname(destination)) !== movedPath(origin.canonical, moves)) {\n fail(\"ENOTSUP\", path, \"relocation changes an unprovable relative symlink target\");\n }\n movedOrigins.push([destination, { ...origin, moves }]);\n }\n options.signal?.throwIfAborted();\n await this.#upper.rename(original.path, target.path, options);\n this.whiteouts.add(original.path);\n if (original.stat.type === \"directory\") this.opaque.add(target.path);\n const moved = [...this.linkMetadata].filter(([path]) => isPathWithin(original.path, path));\n for (const path of this.linkMetadata.keys()) {\n if (isPathWithin(original.path, path) || isPathWithin(target.path, path)) this.linkMetadata.delete(path);\n }\n for (const [path, metadata] of moved) this.linkMetadata.set(target.path + path.slice(original.path.length), metadata);\n for (const path of this.linkOrigins.keys()) {\n if (isPathWithin(original.path, path) || isPathWithin(target.path, path)) this.linkOrigins.delete(path);\n }\n for (const [path, origin] of movedOrigins) this.linkOrigins.set(path, origin);\n });\n }\n\n async copyFile(source: string, destination: string, options: CopyFileOptions = {}): Promise<void> {\n return this.run(options, async () => {\n this.writable(destination);\n const original = await this.required(source, options);\n const target = await this.writeLocation(destination, { ...options, flag: options.exclusive ? \"wx\" : \"w\" });\n if (original.path === target.path) fail(\"EINVAL\", destination, \"source and destination are the same file\");\n if (target.entry) {\n let identity = compareIdentity(original.stat, target.entry.stat);\n if (identity === \"unknown\") identity = await compareEntries(original.backend, original.path, target.entry.backend, target.entry.path, options);\n if (identity === \"same\") fail(\"EINVAL\", destination, \"source and destination are the same file\");\n if (identity === \"unknown\") fail(\"ENOTSUP\", destination, \"backing-entry identity is unknown\");\n }\n if (target.entry?.backend !== this.#upper) {\n const upper = await this.maybeStat(this.#upper, target.path, options);\n if (upper) {\n let identity = compareIdentity(original.stat, upper);\n if (identity === \"unknown\") identity = await compareEntries(original.backend, original.path, this.#upper, target.path, options);\n if (identity === \"same\") fail(\"EINVAL\", destination, \"source and destination are the same file\");\n if (identity === \"unknown\") fail(\"ENOTSUP\", destination, \"upper backing-entry identity is unknown\");\n }\n }\n await this.cleanGarbage(false);\n const bytes = await this.bytes(original, options);\n await this.replace(target, options, async (temporary) => {\n await this.#upper.writeFile(temporary, bytes, { ...options, mode: original.stat.mode & 0o7777, flag: \"w\" });\n if (this.#upper.chmod) await this.#upper.chmod(temporary, original.stat.mode & 0o7777, options);\n else if (((await this.#upper.lstat(temporary, options)).mode & 0o7777) !== (original.stat.mode & 0o7777)) fail(\"ENOTSUP\", destination);\n });\n }, false);\n }\n\n async readlink(path: string, options: FsOptions = {}): Promise<string> {\n return this.run(options, async () => {\n const entry = await this.required(path, options, false);\n if (entry.stat.type !== \"symlink\") fail(\"EINVAL\", path);\n if (!entry.backend.readlink) fail(\"ENOTSUP\", path);\n return entry.backend.readlink(entry.path, options);\n }, false);\n }\n\n async symlink(target: string, path: string, options: FsOptions = {}): Promise<void> {\n return this.run(options, async () => {\n this.writable(path);\n if (!this.capabilities.symlinks || !this.#upper.symlink) fail(\"ENOTSUP\", path);\n validatePath(target);\n if (!target) fail(\"ENOENT\", path);\n const location = await this.resolve(path, options, false, true);\n if (location.entry) fail(\"EEXIST\", path);\n await this.replace(location, options, (temporary) => this.#upper.symlink!(target, temporary, options));\n });\n }\n\n async link(_existingPath: string, newPath: string, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n fail(\"ENOTSUP\", newPath, \"overlay hardlinks are not supported\");\n }\n\n private async metadata(path: string, capability: \"permissions\" | \"timestamps\", options: FsOptions, operation: (path: string) => Promise<void>): Promise<void> {\n return this.run(options, async () => {\n this.writable(path);\n if (!this.capabilities[capability]) fail(\"ENOTSUP\", path);\n const entry = await this.required(path, options);\n if (entry.stat.type === \"directory\") {\n await this.copyUp(entry, options);\n await operation(entry.path);\n } else await this.replace({ path: entry.path, entry }, options, operation);\n });\n }\n\n async chmod(path: string, permissions: number, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n if (permissions === undefined) fail(\"EINVAL\", path);\n mode(permissions, path);\n return this.metadata(path, \"permissions\", options, (target) => this.#upper.chmod!(target, permissions, options));\n }\n\n async utimes(path: string, atimeMs: number, mtimeMs: number, options: FsOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n if (!Number.isFinite(atimeMs) || !Number.isFinite(mtimeMs)) fail(\"EINVAL\", path);\n return this.metadata(path, \"timestamps\", options, (target) => this.#upper.utimes!(target, atimeMs, mtimeMs, options));\n }\n\n async truncate(path: string, length = 0, options: FsOptions = {}): Promise<void> {\n integer(length, path);\n return this.run(options, async () => {\n this.writable(path);\n if (length > this.maxBufferBytes) fail(\"EFBIG\", path);\n const entry = await this.required(path, options);\n if (entry.stat.type !== \"file\") fail(\"EISDIR\", path);\n this.permission(entry, 2);\n await this.replace({ path: entry.path, entry }, options, async (temporary) => {\n if (this.#upper.truncate) await this.#upper.truncate(temporary, length, options);\n else {\n const previous = await this.#upper.readFile(temporary, { ...options, maxBytes: this.maxBufferBytes });\n const bytes = new Uint8Array(length);\n bytes.set(previous.subarray(0, length));\n await this.#upper.writeFile(temporary, bytes, options);\n }\n });\n });\n }\n\n async *readStream(path: string, options: ReadStreamOptions = {}): ByteSource {\n options.signal?.throwIfAborted();\n const start = options.start ?? 0;\n const chunkSize = options.chunkSize ?? 64 * 1024;\n integer(start, path);\n integer(chunkSize, path);\n if (!chunkSize) fail(\"EINVAL\", path);\n if (options.endExclusive !== undefined) {\n integer(options.endExclusive, path);\n if (options.endExclusive < start) fail(\"EINVAL\", path);\n }\n const entry = await this.run(options, async () => {\n const entry = await this.required(path, options);\n if (entry.stat.type !== \"file\") fail(\"EISDIR\", path);\n this.permission(entry, 4);\n return entry;\n });\n if (entry.backend.readStream && entry.backend.capabilities.streamingRead !== false) {\n for await (const chunk of readBytes(entry.backend.readStream(entry.path, options), options.signal)) {\n yield new Uint8Array(chunk);\n }\n options.signal?.throwIfAborted();\n return;\n }\n const bytes = await this.bytes(entry, options);\n const end = Math.min(bytes.byteLength, options.endExclusive ?? bytes.byteLength);\n for (let offset = start; offset < end; offset += chunkSize) {\n options.signal?.throwIfAborted();\n yield bytes.slice(offset, Math.min(end, offset + chunkSize));\n }\n options.signal?.throwIfAborted();\n }\n\n private async *bounded(source: ByteSource, path: string, options: FsOptions): AsyncGenerator<Uint8Array> {\n let size = 0;\n for await (const chunk of readBytes(source, options.signal)) {\n if (chunk.byteLength > this.maxBufferBytes - size) fail(\"EFBIG\", path);\n size += chunk.byteLength;\n yield new Uint8Array(chunk);\n }\n }\n\n private async streamToUpper(path: string, source: ByteSource, options: WriteFileOptions): Promise<void> {\n if (!this.#upper.writeStream) fail(\"ENOTSUP\", path);\n const input = readBytes(source, options.signal);\n let failed = false;\n try { await this.#upper.writeStream(path, input, options); }\n catch (error) { failed = true; throw error; }\n finally { await finishCleanup(() => input.return(undefined), failed); }\n }\n\n async writeStream(path: string, source: ByteSource, options: WriteFileOptions = {}): Promise<void> {\n options.signal?.throwIfAborted();\n this.writeOptions(path, options);\n await this.run(options, () => this.writeLocation(path, options));\n if (this.capabilities.streamingWrite !== false) {\n await this.staged(options, async (incoming) => {\n const bounded = this.bounded(source, path, options);\n await this.streamToUpper(incoming, bounded, { ...options, flag: \"wx\", mode: 0o600 });\n const size = (await this.#upper.stat(incoming, options)).size;\n await this.run(options, async () => {\n const location = await this.writeLocation(path, options);\n const append = options.flag === \"a\" || options.flag === \"ax\";\n if (append && (location.entry?.stat.size ?? 0) + size > this.maxBufferBytes) fail(\"EFBIG\", path);\n await this.replace(location, options, async (temporary) => {\n await this.streamToUpper(temporary, this.#upper.readStream!(incoming, options), { ...options, flag: append ? \"a\" : \"w\" });\n }, true);\n });\n });\n return;\n }\n const bytes = await collectBytes(source, { maxBytes: this.maxBufferBytes, ...(options.signal ? { signal: options.signal } : {}) });\n await this.writeFile(path, bytes, options);\n }\n}\n\nexport function createOverlayFileSystem(options: OverlayFileSystemOptions): OverlayFileSystem {\n return new OverlayFileSystem(options);\n}\n", "import type { FileDescriptor, FileResizeHandle, FileStat, FileSystem, FsOptions, OpenReadFileOptions, OpenResizeFileOptions } from \"../../contracts/filesystem.js\";\nimport { FsError } from \"../../contracts/errors.js\";\nimport { finishCleanup } from \"../../contracts/cleanup.js\";\nimport type { ByteSource } from \"../../contracts/io.js\";\nimport { openRetainedReadFile, openRetainedResizeFile, quotaCapabilities, retainedReadCapabilities, retainedResizeCapabilities } from \"../capabilities.js\";\nimport { admitDirectoryEntries } from \"../directory-admission.js\";\nimport { forwardFileDescriptor, openFileDescriptor } from \"../descriptor.js\";\n\nexport interface FileSystemQuotaOptions {\n readonly maxBytes: number;\n readonly maxScanEntries?: number;\n readonly maxScanDepth?: number;\n}\n\nexport class FileSystemQuotaError extends Error {\n readonly code = \"ENOSPC\";\n constructor(readonly maxBytes: number) {\n super(`Filesystem quota exceeded (${maxBytes} bytes)`);\n this.name = \"FileSystemQuotaError\";\n }\n}\n\nfunction completeIdentity(stat: FileStat): boolean {\n return (typeof stat.identityScope === \"symbol\" || typeof stat.identityScope === \"object\" && stat.identityScope !== null)\n && [stat.dev, stat.ino].every(value => typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0);\n}\n\nfunction namespaceMetadata<Value>(metadata: Promise<Value>, signal?: AbortSignal): Promise<Value> {\n if (!signal) return metadata;\n return new Promise<Value>((resolve, reject) => {\n const abort = (): void => { signal.removeEventListener(\"abort\", abort); reject(signal.reason); };\n signal.addEventListener(\"abort\", abort, { once: true });\n metadata.then(\n value => { signal.removeEventListener(\"abort\", abort); resolve(value); },\n error => { signal.removeEventListener(\"abort\", abort); reject(error); },\n );\n if (signal.aborted) abort();\n });\n}\n\nasync function usedBytes(fs: FileSystem, limits: { maxScanEntries: number; maxScanDepth: number }, options?: FsOptions, change?: { path: string; stat: FileStat; delta: number; retained?: boolean }, retained = change?.retained === true): Promise<number> {\n let total = 0;\n let retainedTotal = 0n;\n let shrinkCredited = false;\n let possibleAliases = 0;\n let remaining = limits.maxScanEntries;\n const pending = [{ path: \"/\", depth: 0 }];\n while (pending.length) {\n options?.signal?.throwIfAborted();\n const directory = pending.pop();\n if (!directory) break;\n const signal = options?.signal;\n const listing = fs.readdir(directory.path, { ...options, ...(signal ? { signal } : {}), maxEntries: remaining });\n const entries = await (retained ? namespaceMetadata(listing, signal) : listing);\n options?.signal?.throwIfAborted();\n const count = entries.length;\n admitDirectoryEntries(count, remaining, directory.path);\n remaining -= count;\n let processed = 0;\n for (const entry of entries) {\n options?.signal?.throwIfAborted();\n if (processed >= count) {\n admitDirectoryEntries(1, remaining, directory.path);\n remaining--;\n }\n processed++;\n const path = `${directory.path === \"/\" ? \"\" : directory.path}/${entry.name}`;\n if (entry.type === \"directory\") {\n const depth = directory.depth + 1;\n if (depth > limits.maxScanDepth) throw new FsError(\"EFBIG\", { syscall: \"readdir\", path, message: \"quota scan depth limit exceeded\" });\n pending.push({ path, depth });\n }\n else {\n const metadata = fs.lstat(path, options);\n const stat = await (retained ? namespaceMetadata(metadata, signal) : metadata);\n if (retained) {\n options?.signal?.throwIfAborted();\n if (!Number.isSafeInteger(stat.size) || stat.size < 0) throw new FsError(\"EIO\", { syscall: \"lstat\", path, message: \"invalid quota entry size\" });\n retainedTotal += BigInt(stat.size);\n if (!change || stat.type !== \"file\") continue;\n const known = completeIdentity(stat);\n const same = known && change.stat.identityScope === stat.identityScope && change.stat.dev === stat.dev && change.stat.ino === stat.ino;\n const nextBytes = change.stat.size + change.delta;\n if (same) {\n possibleAliases++;\n retainedTotal += BigInt(Math.max(0, nextBytes - stat.size));\n if (!shrinkCredited && change.delta < 0) {\n retainedTotal -= BigInt(Math.max(0, Math.min(stat.size, change.stat.size) - nextBytes));\n shrinkCredited = true;\n }\n } else if (!known) {\n possibleAliases++;\n retainedTotal += BigInt(Math.max(0, change.delta, nextBytes - stat.size));\n }\n continue;\n }\n total += stat.size;\n if (!change || stat.type !== \"file\") continue;\n const scope = change.stat.identityScope;\n const comparable = [scope, stat.identityScope].every(value => typeof value === \"symbol\" || typeof value === \"object\" && value !== null)\n && [change.stat.dev, change.stat.ino, stat.dev, stat.ino].every(value => typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0);\n const compare = comparable ? undefined : fs.compareEntry;\n const comparison = comparable\n ? scope === stat.identityScope && change.stat.dev === stat.dev && change.stat.ino === stat.ino ? \"same\" : \"distinct\"\n : compare === undefined ? \"unknown\" : await compare.call(fs, change.path, fs, path, options);\n options?.signal?.throwIfAborted();\n if (comparison !== \"same\" && comparison !== \"distinct\" && comparison !== \"unknown\") throw new FsError(\"EIO\", { syscall: \"compareEntry\", path: change.path, dest: path, message: \"invalid entry comparison\" });\n if (comparison === \"same\") { total += change.delta; possibleAliases++; }\n else if (comparison !== \"distinct\") { total += Math.max(0, change.delta); possibleAliases++; }\n }\n }\n }\n if (retained) {\n if (change && possibleAliases === 0) retainedTotal += BigInt(Math.max(0, change.delta));\n return Number(retainedTotal);\n }\n if (change && possibleAliases === 0) total += Math.max(0, change.delta);\n return total;\n}\n\nasync function existingBytes(fs: FileSystem, path: string, options?: FsOptions): Promise<number> {\n try {\n const stat = await fs.stat(path, options);\n return stat.type === \"directory\" ? 0 : stat.size;\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") return 0;\n throw error;\n }\n}\n\nexport function withFileSystemQuota(fs: FileSystem, options: FileSystemQuotaOptions): FileSystem {\n if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 0) throw new RangeError(\"maxBytes must be a nonnegative safe integer\");\n const scanLimits = {\n maxScanEntries: options.maxScanEntries === undefined ? 4096 : options.maxScanEntries,\n maxScanDepth: options.maxScanDepth === undefined ? 64 : options.maxScanDepth,\n };\n for (const [name, value] of Object.entries(scanLimits)) {\n if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name} must be a nonnegative safe integer`);\n }\n let queue: Promise<unknown> = Promise.resolve();\n const mutate = <Result>(operation: () => Promise<Result>): Promise<Result> => {\n const result = queue.then(operation);\n queue = result.catch(() => undefined);\n return result;\n };\n const resizeBackend = new Proxy(Object.create(fs) as FileSystem, {\n get(_target, property) {\n const original: unknown = Reflect.get(fs, property);\n if (property === \"openResizeFile\" && typeof original === \"function\") return async (path: string, resizeOptions: OpenResizeFileOptions) => {\n resizeOptions.signal?.throwIfAborted();\n if (resizeOptions.create) {\n const total = await usedBytes(fs, scanLimits, resizeOptions, undefined, true);\n resizeOptions.signal?.throwIfAborted();\n if (total > options.maxBytes) throw new FileSystemQuotaError(options.maxBytes);\n }\n resizeOptions.signal?.throwIfAborted();\n return Reflect.apply(original as NonNullable<FileSystem[\"openResizeFile\"]>, fs, [path, resizeOptions]);\n };\n return typeof original === \"function\" ? original.bind(fs) : original;\n },\n });\n const assertDelta = async (path: string, nextBytes: number, fsOptions?: FsOptions): Promise<void> => {\n fsOptions?.signal?.throwIfAborted();\n let current: FileStat | undefined;\n try { current = await fs.stat(path, fsOptions); }\n catch (error) {\n if (!(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")) throw error;\n }\n const projected = current?.type === \"file\" && nextBytes > current.size\n ? await usedBytes(fs, scanLimits, fsOptions, { path, stat: current, delta: nextBytes - current.size })\n : await usedBytes(fs, scanLimits, fsOptions) - (current?.type === \"directory\" ? 0 : current?.size ?? 0) + nextBytes;\n fsOptions?.signal?.throwIfAborted();\n if (projected > options.maxBytes) throw new FileSystemQuotaError(options.maxBytes);\n };\n const mutations: Partial<FileSystem> = {\n open(path, openOptions) {\n return openFileDescriptor<FileDescriptor>(path, openOptions, {\n positionedRead: true, positionedWrite: true, truncate: true, synchronization: \"storage\",\n }, admitted => mutate(async () => {\n admitted.signal?.throwIfAborted();\n const open = fs.open;\n const capabilities = admitted.creation === \"exclusive\" ? fs.capabilities : await fs.capabilitiesFor?.(path, admitted) ?? fs.capabilities;\n admitted.signal?.throwIfAborted();\n if (!open || capabilities.open === false) throw new FsError(\"ENOTSUP\", { syscall: \"open\", path });\n admitted.signal?.throwIfAborted();\n const descriptor = await open.call(fs, path, admitted);\n try {\n admitted.signal?.throwIfAborted();\n const pinned = admitted.access === \"read\" ? undefined : { ...await descriptor.stat(admitted) };\n admitted.signal?.throwIfAborted();\n if (pinned && (pinned.type !== \"file\" || !completeIdentity(pinned))) {\n throw new FsError(\"ENOTSUP\", { syscall: \"open\", path, message: \"quota requires complete retained file identity\" });\n }\n if (pinned && (!Number.isSafeInteger(pinned.size) || pinned.size < 0)) {\n throw new FsError(\"EIO\", { syscall: \"fstat\", path, message: \"invalid retained file size\" });\n }\n const current = async (operationOptions: FsOptions): Promise<FileStat> => {\n const stat = { ...await descriptor.stat(operationOptions) };\n operationOptions.signal?.throwIfAborted();\n if (!pinned || stat.type !== \"file\" || !completeIdentity(stat)\n || stat.identityScope !== pinned.identityScope || stat.dev !== pinned.dev || stat.ino !== pinned.ino\n || !Number.isSafeInteger(stat.size) || stat.size < 0) {\n throw new FsError(\"EIO\", { syscall: \"fstat\", path, message: \"invalid retained quota identity or size\" });\n }\n return stat;\n };\n const admitSize = async (stat: FileStat, nextBytes: number, operationOptions: FsOptions): Promise<void> => {\n if (!Number.isSafeInteger(nextBytes) || nextBytes < 0) throw new FsError(\"EFBIG\", { syscall: \"write\", path });\n const projected = await usedBytes(fs, scanLimits, operationOptions, { path, stat, delta: nextBytes - stat.size, retained: true });\n operationOptions.signal?.throwIfAborted();\n if (projected > options.maxBytes) throw new FileSystemQuotaError(options.maxBytes);\n };\n const forwarded = forwardFileDescriptor(descriptor, (syscall, operationOptions, action) => syscall === \"close\" ? action() : mutate(async () => {\n operationOptions.signal?.throwIfAborted();\n return action();\n }));\n return {\n ...forwarded,\n write: (retained, buffer, position, operationOptions) => mutate(async () => {\n operationOptions.signal?.throwIfAborted();\n if (buffer.byteLength === 0) return retained.write(buffer, position, operationOptions);\n const stat = await current(operationOptions);\n let offset = position;\n if (offset === null) {\n if (admitted.append) offset = stat.size;\n else {\n if (forwarded.capabilities?.position !== true || !forwarded.getPosition) {\n throw new FsError(\"ENOTSUP\", { syscall: \"getPosition\", path });\n }\n offset = await retained.getPosition!(operationOptions);\n operationOptions.signal?.throwIfAborted();\n }\n }\n if (!Number.isSafeInteger(offset) || offset < 0) throw new FsError(\"EIO\", { syscall: \"getPosition\", path });\n await admitSize(stat, Math.max(stat.size, offset + buffer.byteLength), operationOptions);\n return retained.write(buffer, position, operationOptions);\n }),\n truncate: (retained, length, operationOptions) => mutate(async () => {\n operationOptions.signal?.throwIfAborted();\n await admitSize(await current(operationOptions), length, operationOptions);\n await retained.truncate(length, operationOptions);\n }),\n };\n } catch (error) {\n await finishCleanup(() => descriptor.close(), true);\n admitted.signal?.throwIfAborted();\n throw error;\n }\n }));\n },\n openResizeFile(path, resizeOptions = {}) {\n return mutate(async () => {\n let retained: FileResizeHandle | undefined;\n try {\n retained = await openRetainedResizeFile(resizeBackend, path, resizeOptions);\n const pinned = { ...await retained.stat(resizeOptions) };\n resizeOptions.signal?.throwIfAborted();\n if (pinned.type !== \"file\" || !completeIdentity(pinned)) throw new FsError(\"ENOTSUP\", { syscall: \"openResizeFile\", path, message: \"quota requires complete retained file identity\" });\n if (!Number.isSafeInteger(pinned.size) || pinned.size < 0) throw new FsError(\"EIO\", { syscall: \"stat\", path, message: \"invalid retained file size\" });\n const handle = retained;\n const seekEnd = handle.seekEnd;\n resizeOptions.signal?.throwIfAborted();\n let pending: Promise<unknown> = Promise.resolve();\n let closing: Promise<void> | undefined;\n const admit = <Result>(operation: () => Promise<Result>, operationOptions?: FsOptions): Promise<Result> => {\n if (closing) return Promise.reject(new FsError(\"EBADF\", { path }));\n const result = mutate(async () => {\n operationOptions?.signal?.throwIfAborted();\n const value = await operation();\n operationOptions?.signal?.throwIfAborted();\n return value;\n });\n pending = result.catch(() => undefined);\n return result;\n };\n const current = async (operationOptions?: FsOptions): Promise<FileStat> => {\n const stat = { ...await handle.stat(operationOptions) };\n operationOptions?.signal?.throwIfAborted();\n if (stat.type !== \"file\" || !completeIdentity(stat) || stat.identityScope !== pinned.identityScope || stat.dev !== pinned.dev || stat.ino !== pinned.ino\n || !Number.isSafeInteger(stat.size) || stat.size < 0) throw new FsError(\"EIO\", { syscall: \"stat\", path, message: \"invalid retained quota identity or size\" });\n return stat;\n };\n return {\n stat(operationOptions) { return admit(() => current(operationOptions), operationOptions); },\n ...(typeof seekEnd === \"function\" ? {\n seekEnd(operationOptions?: FsOptions) {\n return admit(() => Reflect.apply(seekEnd, handle, [operationOptions]), operationOptions);\n },\n } : {}),\n truncate(length, operationOptions) {\n return admit(async () => {\n if (!Number.isSafeInteger(length) || length < 0) throw new FsError(\"EINVAL\", { syscall: \"truncate\", path });\n const stat = await current(operationOptions);\n const projected = await usedBytes(fs, scanLimits, operationOptions, { path, stat, delta: length - stat.size, retained: true });\n operationOptions?.signal?.throwIfAborted();\n if (projected > options.maxBytes) throw new FileSystemQuotaError(options.maxBytes);\n await handle.truncate(length, operationOptions);\n }, operationOptions);\n },\n close() {\n closing ??= pending.then(() => handle.close());\n return closing;\n },\n };\n } catch (error) {\n if (retained) await finishCleanup(() => retained!.close(), true);\n resizeOptions.signal?.throwIfAborted();\n throw error;\n }\n });\n },\n writeFile(path, data, writeOptions) {\n return mutate(async () => {\n const append = writeOptions?.flag === \"a\" || writeOptions?.flag === \"ax\";\n const current = append ? await existingBytes(fs, path, writeOptions) : 0;\n await assertDelta(path, current + data.length, writeOptions);\n await fs.writeFile(path, data, writeOptions);\n });\n },\n appendFile(path, data, appendOptions) {\n return mutate(async () => {\n await assertDelta(path, await existingBytes(fs, path, appendOptions) + data.length, appendOptions);\n await fs.appendFile(path, data, appendOptions);\n });\n },\n async rename(source, destination, renameOptions) {\n if (renameOptions?.noReplace) {\n renameOptions.signal?.throwIfAborted();\n const capabilities = await fs.capabilitiesFor?.(destination, renameOptions) ?? fs.capabilities;\n renameOptions?.signal?.throwIfAborted();\n if (capabilities.atomicRenameNoReplace !== true) throw new FsError(\"ENOTSUP\", { syscall: \"rename\", path: source, dest: destination });\n }\n await fs.rename(source, destination, renameOptions);\n },\n copyFile(source, destination, copyOptions) {\n return mutate(async () => {\n await assertDelta(destination, (await fs.stat(source, copyOptions)).size, copyOptions);\n await fs.copyFile(source, destination, copyOptions);\n });\n },\n truncate(path, length = 0, truncateOptions) {\n return mutate(async () => {\n await assertDelta(path, length, truncateOptions);\n await fs.truncate!(path, length, truncateOptions);\n });\n },\n link(source, destination, linkOptions) {\n return mutate(async () => {\n await assertDelta(destination, (await fs.lstat(source, linkOptions)).size, linkOptions);\n await fs.link!(source, destination, linkOptions);\n });\n },\n symlink(target, path, linkOptions) {\n return mutate(async () => {\n await assertDelta(path, new TextEncoder().encode(target).length, linkOptions);\n await fs.symlink!(target, path, linkOptions);\n });\n },\n writeStream(path, source, writeOptions) {\n return mutate(async () => {\n const append = writeOptions?.flag === \"a\" || writeOptions?.flag === \"ax\";\n if (!append) await fs.writeFile(path, new Uint8Array(), writeOptions);\n for await (const chunk of source as ByteSource) {\n await assertDelta(path, await existingBytes(fs, path, writeOptions) + chunk.length, writeOptions);\n await fs.appendFile(path, chunk, writeOptions);\n }\n });\n },\n };\n // Backend descriptors may be frozen. An independent view lets us adapt\n // capabilities and methods without violating invariants on own properties.\n return new Proxy(Object.create(fs) as FileSystem, {\n get(_target, property) {\n if (property === \"removeEntryConditional\" || property === \"writeFileConditional\" || property === \"removeFileConditional\" || property === \"resizeFile\" || property === \"canonicalizeMissingTarget\" || property === \"createStagedFile\" || property === \"publishStagedFile\" || property === \"removeStagedFile\" || property === \"prepareDirectory\") return undefined;\n if (property === \"capabilities\") return quotaCapabilities({ ...retainedResizeCapabilities(fs, retainedReadCapabilities(fs)), ...(typeof fs.open === \"function\" ? {} : { open: false }) });\n if (property === \"capabilitiesFor\") return async (path: string, fsOptions?: FsOptions) => {\n const capabilities = await fs.capabilitiesFor?.(path, fsOptions) ?? fs.capabilities;\n return quotaCapabilities({ ...retainedResizeCapabilities(fs, retainedReadCapabilities(fs, capabilities)), ...(typeof fs.open === \"function\" ? {} : { open: false }) });\n };\n if (property === \"openReadFile\") return (path: string, fsOptions: OpenReadFileOptions = {}) => openRetainedReadFile(fs, path, fsOptions);\n const replacement = Reflect.get(mutations, property) as unknown;\n if (typeof replacement === \"function\") return replacement;\n const original = Reflect.get(fs, property) as unknown;\n return typeof original === \"function\" ? original.bind(fs) : original;\n },\n });\n}\n", "import type { FileStaging, FileReadHandle, FileResizeHandle, FileSystem, FsOptions, OpenResizeFileOptions, RenameOptions } from \"../contracts/filesystem.js\";\nimport type { FileDescriptor, OpenFileOptions } from \"../contracts/descriptor.js\";\nimport { FsError } from \"../contracts/errors.js\";\nimport type { ByteSource } from \"../contracts/io.js\";\nimport { finishCleanup } from \"../contracts/cleanup.js\";\nimport { registerEntryView } from \"./mount/comparison.js\";\nimport { openRetainedResizeFile, retainedResizeCapabilities, ownedMutationCapabilities, requireOwnedMutation } from \"./capabilities.js\";\n\nconst originals = new WeakMap<FileSystem, { filesystem: FileSystem; signal: AbortSignal; cleanupCharge: () => void }>();\nconst operations = new Set<keyof FileSystem>([\n \"removeEntryConditional\", \"removeTreeConditional\", \"writeFileConditional\", \"removeFileConditional\", \"createStagedFile\", \"publishStagedFile\", \"removeStagedFile\", \"prepareDirectory\",\n \"access\", \"appendFile\", \"canonicalizeMissingTarget\", \"capabilitiesFor\", \"chmod\", \"compareEntry\",\n \"copyFile\", \"link\", \"lstat\", \"mkdir\", \"openReadFile\", \"openResizeFile\", \"readFile\", \"readStream\", \"readdir\",\n \"readlink\", \"realpath\", \"rename\", \"resizeFile\", \"rm\", \"rmdir\", \"unlink\", \"stat\", \"symlink\", \"truncate\", \"utimes\",\n \"writeFile\", \"writeStream\",\n]);\n\nexport function scopeFileSystem(filesystem: FileSystem, charge: () => void, signal: AbortSignal, cleanupCharge = charge): FileSystem {\n const original = originals.get(filesystem)?.filesystem ?? filesystem;\n const methods = new Map<PropertyKey, { original: unknown; scoped: unknown }>();\n const assertOpen = (options?: FsOptions): void => {\n signal.throwIfAborted();\n options?.signal?.throwIfAborted();\n };\n const admit = (options?: FsOptions): void => {\n assertOpen(options);\n charge();\n };\n const wrapHandle = (handle: FileReadHandle): FileReadHandle => {\n let closed = false;\n const close = handle.close.bind(handle);\n return {\n async stat(options) { admit(options); return handle.stat(options); },\n async read(position, maxBytes, options) { admit(options); return handle.read(position, maxBytes, options); },\n get seekEnd() {\n const seek = handle.seekEnd;\n if (typeof seek !== \"function\") return undefined;\n return async (options: FsOptions = {}) => {\n assertOpen(options);\n if (closed) throw new FsError(\"EBADF\");\n admit(options);\n assertOpen(options);\n if (closed) throw new FsError(\"EBADF\");\n try {\n const result = await Reflect.apply(seek, handle, [resizeOptions(options)]);\n assertOpen(options);\n return result;\n } catch (error) { assertOpen(options); throw error; }\n };\n },\n close() { closed = true; return close(); },\n };\n };\n const resizeOptions = <Options extends FsOptions>(options: Options): Options => {\n const scopedOptions = {\n ...options, signal: options.signal ? AbortSignal.any([signal, options.signal]) : signal,\n };\n scopedOptions.signal.throwIfAborted();\n return scopedOptions;\n };\n const wrapResizeHandle = (handle: FileResizeHandle): FileResizeHandle => {\n let closing: Promise<void> | undefined;\n const admitOperation = (options: FsOptions): FsOptions => {\n assertOpen(options);\n if (closing) throw new FsError(\"EBADF\");\n admit(options);\n assertOpen(options);\n if (closing) throw new FsError(\"EBADF\");\n return resizeOptions(options);\n };\n return {\n async stat(options = {}) {\n try {\n const result = await handle.stat(admitOperation(options));\n assertOpen(options);\n return result;\n } catch (error) { assertOpen(options); throw error; }\n },\n async truncate(length, options = {}) {\n try {\n await handle.truncate(length, admitOperation(options));\n assertOpen(options);\n } catch (error) { assertOpen(options); throw error; }\n },\n get seekEnd() {\n const seek = handle.seekEnd;\n if (typeof seek !== \"function\") return undefined;\n return async (options: FsOptions = {}) => {\n try {\n const result = await Reflect.apply(seek, handle, [admitOperation(options)]);\n assertOpen(options);\n return result;\n } catch (error) { assertOpen(options); throw error; }\n };\n },\n close: () => closing ??= Promise.resolve().then(() => handle.close()),\n };\n };\n const wrapDescriptor = (descriptor: FileDescriptor): FileDescriptor => {\n let closing: Promise<void> | undefined;\n const invoke = async <Result>(options: FsOptions, action: (options: FsOptions) => Promise<Result>): Promise<Result> => {\n assertOpen(options);\n if (closing) throw new FsError(\"EBADF\");\n admit(options);\n assertOpen(options);\n if (closing) throw new FsError(\"EBADF\");\n try {\n const result = await action(resizeOptions(options));\n assertOpen(options);\n return result;\n } catch (error) { assertOpen(options); throw error; }\n };\n const getPosition = descriptor.getPosition;\n const probeRead = descriptor.probeRead;\n return {\n capabilities: Object.freeze({ ...descriptor.capabilities }),\n ...(getPosition === undefined ? {} : { getPosition: (options: FsOptions = {}) => invoke(options, scoped => getPosition.call(descriptor, scoped)) }),\n ...(probeRead === undefined ? {} : { probeRead: (options: FsOptions = {}) => invoke(options, scoped => probeRead.call(descriptor, scoped)) }),\n stat: (options = {}) => invoke(options, scoped => descriptor.stat(scoped)),\n read: (buffer, position, options = {}) => invoke(options, scoped => descriptor.read(buffer, position, scoped)),\n write: (buffer, position, options = {}) => invoke(options, scoped => descriptor.write(buffer, position, scoped)),\n truncate: (length, options = {}) => invoke(options, scoped => descriptor.truncate(length, scoped)),\n sync: (dataOnly, options = {}) => invoke(options, scoped => descriptor.sync(dataOnly, scoped)),\n close: () => closing ??= Promise.resolve().then(() => descriptor.close()),\n };\n };\n const wrapStream = (source: ByteSource, options?: FsOptions): ByteSource => ({\n [Symbol.asyncIterator]() {\n assertOpen(options);\n const iterator = source[Symbol.asyncIterator]();\n let closing: Promise<IteratorResult<Uint8Array>> | undefined;\n const close = (value?: unknown): Promise<IteratorResult<Uint8Array>> => closing ??= Promise.resolve().then(\n () => iterator.return ? iterator.return(value) : { done: true, value: undefined },\n );\n const advance = async (operation: () => Promise<IteratorResult<Uint8Array>>): Promise<IteratorResult<Uint8Array>> => {\n try {\n assertOpen(options);\n if (closing) { await closing; return { done: true, value: undefined }; }\n const result = await operation();\n assertOpen(options);\n if (closing) { await closing; return { done: true, value: undefined }; }\n return result;\n } catch (error) {\n await finishCleanup(close, true);\n throw error;\n }\n };\n return {\n next: () => advance(() => iterator.next()),\n return: close,\n ...(iterator.throw ? { throw: (error?: unknown) => advance(() => iterator.throw!(error)) } : {}),\n };\n },\n });\n const view = new Proxy(Object.create(original) as FileSystem, {\n set(_target, property, value) {\n return Reflect.set(original, property, value, original);\n },\n get(_target, property) {\n if (property === \"capabilities\") return ownedMutationCapabilities(original, retainedResizeCapabilities(original));\n const method: unknown = Reflect.get(original, property, original);\n if (typeof method !== \"function\") return method;\n const cached = methods.get(property);\n if (cached?.original === method) return cached.scoped;\n const dispatch = (...args: unknown[]): unknown => {\n if (operations.has(property as keyof FileSystem)) {\n const options = args.at(-1);\n admit(options && typeof options === \"object\" && \"signal\" in options ? options as FsOptions : undefined);\n }\n if ([\"removeEntryConditional\", \"removeTreeConditional\", \"writeFileConditional\", \"removeFileConditional\", \"createStagedFile\", \"publishStagedFile\", \"removeStagedFile\", \"prepareDirectory\"].includes(String(property))) return (async () => {\n const path = typeof args[0] === \"string\" ? args[0] : (args[0] as FileStaging).directory.path;\n const options = args[property === \"createStagedFile\" ? 3 : property === \"publishStagedFile\" || property === \"writeFileConditional\" ? 2 : 1] as FsOptions | undefined;\n const create = property === \"createStagedFile\" || (property === \"writeFileConditional\" || property === \"prepareDirectory\") && options !== undefined && \"expected\" in options && options.expected === null;\n await requireOwnedMutation(original, path, property === \"removeEntryConditional\" ? \"atomicEntryRemoval\" : property === \"removeTreeConditional\" ? \"atomicTreeRemoval\" : property === \"prepareDirectory\" ? \"atomicDirectoryMetadata\" : property === \"writeFileConditional\" || property === \"removeFileConditional\" ? \"atomicFileMutation\" : \"atomicFileStaging\", options ?? {}, create);\n assertOpen(options);\n return Reflect.apply(method, original, args);\n })();\n if (property === \"compareEntry\") {\n const peer = args[1] as FileSystem;\n args[1] = originals.get(peer)?.filesystem ?? peer;\n }\n if (property === \"rename\" && (args[2] as RenameOptions | undefined)?.noReplace) return (async () => {\n const options = args[2] as RenameOptions;\n const capabilities = await original.capabilitiesFor?.(args[1] as string, options) ?? original.capabilities;\n assertOpen(options);\n if (capabilities.atomicRenameNoReplace !== true) throw new FsError(\"ENOTSUP\", {\n syscall: \"rename\", path: args[0] as string, dest: args[1] as string,\n });\n return Reflect.apply(method, original, args);\n })();\n return Reflect.apply(method, original, args);\n };\n const scoped = property === \"open\"\n ? async (path: string, options: OpenFileOptions) => {\n admit(options);\n const selected = resizeOptions(options);\n let descriptor: FileDescriptor | undefined;\n try {\n descriptor = await Reflect.apply(method, original, [path, selected]) as FileDescriptor;\n assertOpen(options);\n return wrapDescriptor(descriptor);\n } catch (error) {\n if (descriptor) await finishCleanup(() => descriptor!.close(), true);\n assertOpen(options);\n throw error;\n }\n }\n : property === \"openResizeFile\"\n ? async (path: string, options: OpenResizeFileOptions = {}) => {\n admit(options);\n assertOpen(options);\n return wrapResizeHandle(await openRetainedResizeFile(original, path, resizeOptions(options)));\n }\n : property === \"capabilitiesFor\"\n ? async (...args: unknown[]) => ownedMutationCapabilities(original, retainedResizeCapabilities(original, await dispatch(...args) as FileSystem[\"capabilities\"]))\n : property === \"openReadFile\"\n ? async (...args: unknown[]) => wrapHandle(await dispatch(...args) as FileReadHandle)\n : property === \"readStream\"\n ? (...args: unknown[]) => wrapStream(dispatch(...args) as ByteSource, args[1] as FsOptions | undefined)\n : operations.has(property as keyof FileSystem) && property !== \"canonicalizeMissingTarget\"\n ? async (...args: unknown[]) => dispatch(...args)\n : dispatch;\n methods.set(property, { original: method, scoped });\n return scoped;\n },\n });\n originals.set(view, { filesystem: original, signal, cleanupCharge });\n registerEntryView(view, async (path, options) => {\n assertOpen(options);\n return { filesystem: original, path };\n });\n return view;\n}\n\nexport interface RetainedFileSystemCleanupView {\n readonly removeFileConditional?: NonNullable<FileSystem[\"removeFileConditional\"]>;\n readonly removeStagedFile?: NonNullable<FileSystem[\"removeStagedFile\"]>;\n readonly lstat: FileSystem[\"lstat\"];\n readonly realpath: FileSystem[\"realpath\"];\n readonly rm: (path: string, options?: FsOptions) => Promise<void>;\n readonly rmdir?: NonNullable<FileSystem[\"rmdir\"]>;\n}\n\nexport interface RetainedFileSystemCleanupOptions {\n readonly maxOperations?: number;\n}\n\nexport function retainFileSystemCleanup(\n filesystem: FileSystem,\n cleanupCallback: (view: RetainedFileSystemCleanupView) => void | PromiseLike<void>,\n options?: RetainedFileSystemCleanupOptions,\n): () => Promise<void> {\n const maximum = options?.maxOperations === undefined ? 256 : options.maxOperations;\n if (!Number.isSafeInteger(maximum) || maximum < 0 || maximum > 4096) throw new RangeError(\"cleanup maxOperations must be an integer between 0 and 4096\");\n if (typeof cleanupCallback !== \"function\") throw new TypeError(\"cleanup callback must be a function\");\n const scope = originals.get(filesystem);\n scope?.signal.throwIfAborted();\n const backing = scope?.filesystem ?? filesystem;\n const pending = new Set<Promise<PromiseSettledResult<void>>>();\n let operations = 0;\n let active = false;\n let closing: Promise<void> | undefined;\n const invoke = (method: keyof RetainedFileSystemCleanupView, input: string | FileStaging, settings?: FsOptions): Promise<unknown> => {\n const path = typeof input === \"string\" ? input : input.directory.path;\n if (!active) {\n const rejected = Promise.reject(new FsError(\"EBADF\", { syscall: method, path, message: \"cleanup callback is not active\" }));\n void rejected.catch(() => {});\n return rejected;\n }\n let result: Promise<unknown>;\n try {\n settings?.signal?.throwIfAborted();\n if (operations >= maximum) throw new FsError(\"EFBIG\", { syscall: method, path, message: \"cleanup operation limit exceeded\" });\n operations++;\n scope?.cleanupCharge();\n settings?.signal?.throwIfAborted();\n const operation = backing[method];\n if (typeof operation !== \"function\") throw new FsError(\"ENOTSUP\", { syscall: method, path });\n const parameters = method === \"rm\" ? { ...settings, recursive: false, force: false } : settings;\n result = method === \"removeStagedFile\" || method === \"removeFileConditional\"\n ? requireOwnedMutation(backing, path, method === \"removeFileConditional\" ? \"atomicFileMutation\" : \"atomicFileStaging\", settings ?? {}).then(() => Reflect.apply(operation, backing, [input, parameters]))\n : Promise.resolve(Reflect.apply(operation, backing, [input, parameters]));\n } catch (error) {\n result = Promise.reject(error);\n void result.catch(() => {});\n return result;\n }\n const completion = result.then<PromiseSettledResult<void>, PromiseSettledResult<void>>(\n () => { pending.delete(completion); return { status: \"fulfilled\", value: undefined }; },\n error => { pending.delete(completion); return { status: \"rejected\", reason: error }; },\n );\n pending.add(completion);\n return result;\n };\n const view: RetainedFileSystemCleanupView = Object.freeze(Object.assign(Object.create(null) as RetainedFileSystemCleanupView, {\n ...(typeof backing.removeFileConditional === \"function\" ? { removeFileConditional: invoke.bind(undefined, \"removeFileConditional\") as NonNullable<RetainedFileSystemCleanupView[\"removeFileConditional\"]> } : {}),\n ...(typeof backing.removeStagedFile === \"function\" ? { removeStagedFile: invoke.bind(undefined, \"removeStagedFile\") as NonNullable<RetainedFileSystemCleanupView[\"removeStagedFile\"]> } : {}),\n lstat: invoke.bind(undefined, \"lstat\") as RetainedFileSystemCleanupView[\"lstat\"],\n realpath: invoke.bind(undefined, \"realpath\") as RetainedFileSystemCleanupView[\"realpath\"],\n rm: invoke.bind(undefined, \"rm\") as RetainedFileSystemCleanupView[\"rm\"],\n ...(typeof backing.rmdir === \"function\" ? { rmdir: invoke.bind(undefined, \"rmdir\") as NonNullable<RetainedFileSystemCleanupView[\"rmdir\"]> } : {}),\n }));\n scope?.signal.throwIfAborted();\n return () => {\n if (!closing) {\n closing = Promise.resolve().then(async () => {\n active = true;\n let callbackFailed = false;\n let callbackFailure: unknown;\n try {\n const result = cleanupCallback(view);\n if (result !== undefined) await result;\n } catch (error) { callbackFailed = true; callbackFailure = error; }\n finally { active = false; }\n const outcomes = await Promise.all(pending);\n if (callbackFailed) throw callbackFailure;\n const failures: unknown[] = [];\n for (const outcome of outcomes) if (outcome.status === \"rejected\") failures.push(outcome.reason);\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) throw new AggregateError(failures, \"retained filesystem cleanup failed\");\n });\n void closing.catch(() => {});\n }\n return closing;\n };\n}\n", "export interface AbortSignalScope {\n readonly signal: AbortSignal;\n dispose(): void;\n}\n\nexport function composeAbortSignals(signals: readonly AbortSignal[]): AbortSignalScope {\n const controller = new AbortController();\n const listeners = new Map<AbortSignal, () => void>();\n const dispose = (): void => {\n for (const [signal, listener] of listeners) signal.removeEventListener(\"abort\", listener);\n listeners.clear();\n };\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n return { signal: controller.signal, dispose };\n }\n }\n try {\n for (const signal of new Set(signals)) {\n const listener = (): void => {\n dispose();\n controller.abort(signal.reason);\n };\n listeners.set(signal, listener);\n signal.addEventListener(\"abort\", listener, { once: true });\n if (signal.aborted) listener();\n if (controller.signal.aborted) break;\n }\n } catch (error) {\n dispose();\n throw error;\n }\n return { signal: controller.signal, dispose };\n}\n", "export interface XmlName {\n readonly name: string;\n readonly namespace: string;\n readonly localName: string;\n}\nexport interface XmlAttribute extends XmlName { readonly value: string; }\nexport type XmlContent = XmlElement | { readonly kind: \"text\" | \"cdata\" | \"comment\"; readonly text: string }\n | { readonly kind: \"processing-instruction\"; readonly target: string; readonly text: string };\nexport interface XmlElement extends XmlName {\n readonly kind: \"element\";\n readonly children: XmlElement[];\n readonly content: readonly XmlContent[];\n readonly attributes: readonly XmlAttribute[];\n readonly namespaces: ReadonlyMap<string, string>;\n text: string;\n readonly declaration?: string;\n readonly prolog?: readonly XmlContent[];\n readonly epilog?: readonly XmlContent[];\n}\nexport interface XmlLimits {\n readonly expectedEncoding?: \"UTF-8\" | \"UTF-16\" | \"UTF-16LE\" | \"UTF-16BE\";\n readonly retainContent?: boolean;\n readonly maxDepth?: number;\n readonly maxNodes?: number;\n readonly maxAttributes?: number;\n readonly maxAttributesPerElement?: number;\n readonly maxNamespaces?: number;\n readonly maxContentNodes?: number;\n readonly maxTextLength?: number;\n readonly onElement?: (element: XmlName, parent: XmlName | undefined, depth: number) => void;\n}\nexport class XmlLimitError extends SyntaxError {\n constructor(readonly limit: string, message: string) { super(message); }\n}\n\nfunction* find(source: string, needle: string, start: number): Generator<number, number, void> {\n let work = 0;\n for (let offset = start; offset < source.length; offset++) {\n if (source.startsWith(needle, offset)) { if (work) yield work; return offset; }\n if (++work === 512) { yield work; work = 0; }\n }\n if (work) yield work;\n return -1;\n}\n\nconst xmlNamespace = \"http://www.w3.org/XML/1998/namespace\";\nconst xmlnsNamespace = \"http://www.w3.org/2000/xmlns/\";\n\nfunction invalid(message: string): never {\n throw new SyntaxError(`Invalid XML: ${message}`);\n}\n\nfunction validCharacter(point: number): boolean {\n return point === 9 || point === 10 || point === 13\n || (point >= 0x20 && point <= 0xd7ff)\n || (point >= 0xe000 && point <= 0xfffd)\n || (point >= 0x10000 && point <= 0x10ffff);\n}\n\nfunction nameStart(point: number): boolean {\n return point === 95 || (point >= 65 && point <= 90) || (point >= 97 && point <= 122)\n || (point >= 0xc0 && point <= 0xd6) || (point >= 0xd8 && point <= 0xf6)\n || (point >= 0xf8 && point <= 0x2ff) || (point >= 0x370 && point <= 0x37d)\n || (point >= 0x37f && point <= 0x1fff) || (point >= 0x200c && point <= 0x200d)\n || (point >= 0x2070 && point <= 0x218f) || (point >= 0x2c00 && point <= 0x2fef)\n || (point >= 0x3001 && point <= 0xd7ff) || (point >= 0xf900 && point <= 0xfdcf)\n || (point >= 0xfdf0 && point <= 0xfffd) || (point >= 0x10000 && point <= 0xeffff);\n}\n\nfunction namePart(point: number): boolean {\n return nameStart(point) || point === 45 || point === 46 || point === 0xb7\n || (point >= 48 && point <= 57) || (point >= 0x300 && point <= 0x36f)\n || (point >= 0x203f && point <= 0x2040);\n}\n\nfunction* qualifiedName(name: string): Generator<number, [string, string], void> {\n let prefix = \"\";\n let start = 0;\n let first = true;\n let work = 0;\n for (let offset = 0; offset < name.length;) {\n const point = name.codePointAt(offset)!;\n if (point === 58) {\n if (start !== 0 || first) invalid(\"invalid qualified name\");\n prefix = name.slice(0, offset);\n start = offset + 1;\n first = true;\n } else {\n if (!(first ? nameStart(point) : namePart(point))) invalid(\"invalid qualified name\");\n first = false;\n }\n const width = point > 0xffff ? 2 : 1;\n offset += width;\n work += width;\n if (work >= 512) { yield work; work = 0; }\n }\n if (first) invalid(\"invalid qualified name\");\n if (work) yield work;\n return [prefix, name.slice(start)];\n}\n\nfunction* entities(text: string): Generator<number, string, void> {\n let result = \"\";\n let offset = 0;\n while (offset < text.length) {\n const start = yield* find(text, \"&\", offset);\n if (start < 0) return result + text.slice(offset);\n result += text.slice(offset, start);\n const end = yield* find(text, \";\", start + 1);\n if (end < 0) invalid(\"unterminated entity\");\n const entity = text.slice(start + 1, end);\n const predefined: Record<string, string> = { amp: \"&\", lt: \"<\", gt: \">\", quot: '\"', apos: \"'\" };\n if (Object.hasOwn(predefined, entity)) result += predefined[entity];\n else {\n const hexadecimal = entity.startsWith(\"#x\");\n const digits = entity.slice(hexadecimal ? 2 : 1);\n if (!entity.startsWith(\"#\") || !digits.length) invalid(\"undeclared entity\");\n let point = 0;\n for (let index = 0; index < digits.length; index++) {\n const code = digits.charCodeAt(index);\n const digit = code >= 48 && code <= 57 ? code - 48 : hexadecimal && code >= 65 && code <= 70 ? code - 55\n : hexadecimal && code >= 97 && code <= 102 ? code - 87 : -1;\n if (digit < 0) invalid(\"undeclared entity\");\n point = point * (hexadecimal ? 16 : 10) + digit;\n if (point > 0x10ffff) invalid(\"invalid character reference\");\n if ((index + 1) % 512 === 0) yield 512;\n }\n if (digits.length % 512) yield digits.length % 512;\n if (!validCharacter(point)) invalid(\"invalid character reference\");\n result += String.fromCodePoint(point);\n }\n offset = end + 1;\n }\n return result;\n}\n\nfunction* validDeclaration(content: string, expectedEncoding: XmlLimits[\"expectedEncoding\"]): Generator<number, boolean, void> {\n let offset = 0;\n const whitespace = function* (): Generator<number, number, void> {\n const start = offset;\n while (offset < content.length && \" \\t\\n\\r\".includes(content[offset]!)) {\n offset++;\n if ((offset - start) % 512 === 0) yield 512;\n }\n if ((offset - start) % 512) yield (offset - start) % 512;\n return offset - start;\n };\n const field = function* (name: string): Generator<number, string | undefined, void> {\n if (content.slice(offset, offset + name.length) !== name) return undefined;\n offset += name.length;\n yield name.length;\n yield* whitespace();\n if (content[offset++] !== \"=\") return undefined;\n yield* whitespace();\n const quote = content[offset++];\n if (quote !== \"'\" && quote !== '\"') return undefined;\n const start = offset;\n while (offset < content.length && content[offset] !== quote) {\n offset++;\n if ((offset - start) % 512 === 0) yield 512;\n }\n if ((offset - start) % 512) yield (offset - start) % 512;\n if (offset >= content.length) return undefined;\n return content.slice(start, offset++);\n };\n if (!(yield* whitespace()) || (yield* field(\"version\")) !== \"1.0\") return false;\n let spacing = yield* whitespace();\n if (content.slice(offset, offset + 8) === \"encoding\") {\n if (!spacing) return false;\n const encoding = yield* field(\"encoding\");\n if (encoding === undefined || encoding.length > 8 || ![\"utf-8\", \"utf-16\", \"utf-16le\", \"utf-16be\"].includes(encoding.toLowerCase())) return false;\n if (expectedEncoding !== undefined && encoding.toLowerCase() !== expectedEncoding.toLowerCase()\n && !(encoding.toLowerCase() === \"utf-16\" && (expectedEncoding === \"UTF-16LE\" || expectedEncoding === \"UTF-16BE\"))) return false;\n spacing = yield* whitespace();\n }\n if (content.slice(offset, offset + 10) === \"standalone\") {\n if (!spacing) return false;\n const standalone = yield* field(\"standalone\");\n if (standalone === undefined || standalone.length > 3 || ![\"yes\", \"no\"].includes(standalone)) return false;\n yield* whitespace();\n }\n return offset === content.length;\n}\n\nexport function* parseXmlSteps(input: string, limits: XmlLimits = {}): Generator<number, XmlElement, void> {\n const maxDepth = limits.maxDepth ?? 64;\n const maxNodes = limits.maxNodes ?? 100_000;\n const maxAttributes = limits.maxAttributes ?? 10_000;\n const retainContent = limits.retainContent !== false;\n const maxContentNodes = limits.maxContentNodes ?? (retainContent ? 100_000 : maxNodes);\n const emptyContent: readonly XmlContent[] = Object.freeze([]);\n const emptyAttributes: readonly XmlAttribute[] = Object.freeze([]);\n const emptyNamespaces: ReadonlyMap<string, string> = new Map();\n const maxAttributesPerElement = limits.maxAttributesPerElement ?? 128;\n const maxNamespaces = limits.maxNamespaces ?? 256;\n for (const limit of [maxDepth, maxNodes, maxAttributes, maxContentNodes, maxAttributesPerElement, maxNamespaces]) {\n if (!Number.isSafeInteger(limit) || limit < 1) throw new RangeError(\"XML limits must be positive integers\");\n }\n const maxTextLength = limits.maxTextLength ?? Number.MAX_SAFE_INTEGER;\n if (!Number.isSafeInteger(maxTextLength) || maxTextLength < 1) throw new RangeError(\"XML limits must be positive integers\");\n let textLength = 0;\n const admitText = (text: string): void => {\n if (text.length > maxTextLength - textLength) throw new XmlLimitError(\"maxTextLength\", \"XML text limit exceeded\");\n textLength += text.length;\n };\n const chunks: string[] = [];\n let chunk = \"\";\n for (let index = input.charCodeAt(0) === 0xfeff ? 1 : 0; index < input.length; index++) {\n const point = input.codePointAt(index)!;\n if (!validCharacter(point)) invalid(\"invalid character\");\n if (point === 13) {\n chunk += \"\\n\";\n if (input.charCodeAt(index + 1) === 10) index++;\n } else {\n chunk += String.fromCodePoint(point);\n if (point > 0xffff) index++;\n }\n if (chunk.length >= 512) { chunks.push(chunk); chunk = \"\"; yield 512; }\n }\n chunks.push(chunk);\n if (chunk.length) yield chunk.length;\n const source = chunks.join(\"\");\n const stack: { element: XmlElement; content: XmlContent[] | undefined; name: string; namespaces: Map<string, string> }[] = [];\n let root: XmlElement | undefined;\n const prolog: XmlContent[] = [];\n const epilog: XmlContent[] = [];\n let declaration: string | undefined;\n let offset = 0;\n let nodes = 0;\n let attributeCount = 0;\n let contentNodes = 0;\n const admitContent = (): void => {\n if (++contentNodes > maxContentNodes) throw new XmlLimitError(\"maxContentNodes\", \"XML content node limit exceeded\");\n };\n const whitespace = function* (): Generator<number, void, void> {\n let work = 0;\n while (offset < source.length && \" \\t\\n\\r\".includes(source[offset]!)) {\n offset++;\n if (++work === 512) { yield work; work = 0; }\n }\n if (work) yield work;\n };\n const readName = function* (): Generator<number, string, void> {\n const start = offset;\n while (offset < source.length && !\" \\t\\r\\n/=>?\".includes(source[offset]!)) {\n offset++;\n if ((offset - start) % 512 === 0) yield 512;\n }\n if ((offset - start) % 512) yield (offset - start) % 512;\n const name = source.slice(start, offset);\n yield* qualifiedName(name);\n return name;\n };\n const appendText = function* (text: string, kind: \"text\" | \"cdata\" = \"text\"): Generator<number, void, void> {\n admitText(text);\n const parent = stack.at(-1);\n if (parent) {\n parent.element.text += text;\n if (retainContent && (text.length || kind === \"cdata\")) {\n admitContent();\n parent.content!.push({ kind, text });\n }\n }\n else {\n for (let index = 0; index < text.length; index++) {\n if (!\" \\t\\r\\n\".includes(text[index]!)) invalid(\"text outside the root\");\n if ((index + 1) % 512 === 0) yield 512;\n }\n if (text.length % 512) yield text.length % 512;\n if (retainContent && text.length) { admitContent(); (root ? epilog : prolog).push({ kind, text }); }\n }\n };\n while (offset < source.length) {\n yield 1;\n if (source[offset] !== \"<\") {\n const next = yield* find(source, \"<\", offset);\n const text = source.slice(offset, next < 0 ? source.length : next);\n if ((yield* find(text, \"]]>\", 0)) >= 0) invalid(\"CDATA terminator in text\");\n yield* appendText(stack.length ? yield* entities(text) : text);\n offset += text.length;\n } else if (source.startsWith(\"<!--\", offset)) {\n const end = yield* find(source, \"-->\", offset + 4);\n if (end < 0 || (yield* find(source.slice(offset + 4, end), \"--\", 0)) >= 0 || source.slice(offset + 4, end).endsWith(\"-\")) {\n invalid(\"malformed comment\");\n }\n const parent = stack.at(-1);\n const text = source.slice(offset + 4, end);\n admitText(text);\n if (retainContent) { admitContent(); (parent?.content ?? (root ? epilog : prolog)).push({ kind: \"comment\", text }); }\n offset = end + 3;\n } else if (source.startsWith(\"<![CDATA[\", offset)) {\n if (!stack.length) invalid(\"CDATA outside root\");\n const end = yield* find(source, \"]]>\", offset + 9);\n if (end < 0) invalid(\"unterminated CDATA\");\n yield* appendText(source.slice(offset + 9, end), \"cdata\");\n offset = end + 3;\n } else if (source.startsWith(\"<?\", offset)) {\n const start = offset;\n offset += 2;\n const target = yield* readName();\n const end = yield* find(source, \"?>\", offset);\n if (end < 0) invalid(\"unterminated processing instruction\");\n const content = source.slice(offset, end);\n if (target.length === 3 && target.toLowerCase() === \"xml\") {\n if (start !== 0 || target !== \"xml\"\n || !(yield* validDeclaration(content, limits.expectedEncoding))) {\n invalid(\"unsupported XML declaration\");\n }\n if (retainContent) declaration = source.slice(start, end + 2);\n } else if (content && !\" \\t\\n\\r\".includes(content[0]!)) invalid(\"invalid processing instruction\");\n if (!(target.length === 3 && target.toLowerCase() === \"xml\")) {\n const parent = stack.at(-1);\n let start = 0;\n while (start < content.length && \" \\t\\n\\r\".includes(content[start]!)) {\n start++;\n if (start % 512 === 0) yield 512;\n }\n if (start % 512) yield start % 512;\n const text = content.slice(start);\n admitText(text);\n if (retainContent) {\n admitContent();\n (parent?.content ?? (root ? epilog : prolog)).push({ kind: \"processing-instruction\", target, text });\n }\n }\n offset = end + 2;\n } else if (source.startsWith(\"<!\", offset)) {\n invalid(\"DTD and entity declarations are forbidden\");\n } else if (source.startsWith(\"</\", offset)) {\n offset += 2;\n const name = yield* readName();\n yield* whitespace();\n if (source[offset++] !== \">\" || stack.pop()?.name !== name) invalid(\"mismatched closing tag\");\n } else {\n offset++;\n const name = yield* readName();\n const attributes = new Map<string, string>();\n let namespaces = stack.at(-1)?.namespaces ?? new Map([[\"xml\", xmlNamespace]]);\n let ownsNamespaces = stack.length === 0;\n while (true) {\n const beforeSpace = offset;\n yield* whitespace();\n if (source[offset] === \"/\" || source[offset] === \">\") break;\n if (offset === beforeSpace) invalid(\"attributes require whitespace\");\n const attribute = yield* readName();\n if (attributes.has(attribute)) invalid(\"duplicate attribute\");\n if (++attributeCount > maxAttributes) throw new XmlLimitError(\"maxAttributes\", \"XML attribute limit exceeded\");\n if (attributes.size >= maxAttributesPerElement) throw new XmlLimitError(\"maxAttributesPerElement\", \"XML attribute limit exceeded\");\n yield* whitespace();\n if (source[offset++] !== \"=\") invalid(\"missing attribute equals\");\n yield* whitespace();\n const quote = source[offset++];\n if (quote !== '\"' && quote !== \"'\") invalid(\"unquoted attribute\");\n const end = yield* find(source, quote, offset);\n if (end < 0) invalid(\"unterminated attribute\");\n const raw = source.slice(offset, end);\n if ((yield* find(raw, \"<\", 0)) >= 0) invalid(\"less-than in attribute\");\n let normalized = \"\";\n for (let index = 0; index < raw.length; index++) {\n const character = raw[index]!;\n normalized += character === \"\\t\" || character === \"\\n\" || character === \"\\r\" ? \" \" : character;\n if ((index + 1) % 512 === 0) yield 512;\n }\n if (raw.length % 512) yield raw.length % 512;\n const value = yield* entities(normalized);\n admitText(value);\n attributes.set(attribute, value);\n offset = end + 1;\n if (attribute === \"xmlns\" || attribute.startsWith(\"xmlns:\")) {\n const prefix = attribute === \"xmlns\" ? \"\" : attribute.slice(6);\n if (prefix === \"xmlns\" || value === xmlnsNamespace\n || (prefix === \"xml\") !== (value === xmlNamespace)\n || (prefix !== \"\" && value === \"\")) invalid(\"invalid namespace binding\");\n if (!ownsNamespaces) {\n const copy = new Map<string, string>();\n for (const [key, uri] of namespaces) { copy.set(key, uri); yield 1; }\n namespaces = copy;\n ownsNamespaces = true;\n }\n namespaces.set(prefix, value);\n if (namespaces.size > maxNamespaces) throw new XmlLimitError(\"maxNamespaces\", \"XML namespace scope limit exceeded\");\n }\n }\n const expanded = new Set<string>();\n for (const attribute of attributes.keys()) {\n if (attribute === \"xmlns\" || attribute.startsWith(\"xmlns:\")) continue;\n const [prefix, localName] = yield* qualifiedName(attribute);\n if (prefix && !namespaces.has(prefix)) invalid(\"unbound attribute prefix\");\n const key = JSON.stringify([prefix ? namespaces.get(prefix) : \"\", localName]);\n if (expanded.has(key)) invalid(\"duplicate expanded attribute\");\n expanded.add(key);\n }\n const [prefix, localName] = yield* qualifiedName(name);\n if (prefix === \"xmlns\" || (prefix && !namespaces.has(prefix))) invalid(\"unbound element prefix\");\n if (++nodes > maxNodes) throw new XmlLimitError(\"maxNodes\", \"XML resource limit exceeded\");\n if (stack.length + 1 > maxDepth) throw new XmlLimitError(\"maxDepth\", \"XML resource limit exceeded\");\n const namespace = namespaces.get(prefix) ?? \"\";\n limits.onElement?.({ name, namespace, localName }, stack.at(-1)?.element, stack.length + 1);\n admitContent();\n const retainedAttributes: XmlAttribute[] = [];\n for (const [attribute, value] of retainContent ? attributes : []) {\n const [prefix, localName] = yield* qualifiedName(attribute);\n admitContent();\n retainedAttributes.push({ name: attribute, localName,\n namespace: attribute === \"xmlns\" || prefix === \"xmlns\" ? xmlnsNamespace : prefix ? namespaces.get(prefix)! : \"\", value });\n yield 1;\n }\n const content: XmlContent[] | undefined = retainContent ? [] : undefined;\n const element: XmlElement = { kind: \"element\", name, namespace, localName, children: [], text: \"\", content: content ?? emptyContent, attributes: retainContent ? retainedAttributes : emptyAttributes, namespaces: retainContent ? namespaces : emptyNamespaces, ...(root === undefined && retainContent ? { prolog, epilog, ...(declaration === undefined ? {} : { declaration }) } : {}) };\n const parent = stack.at(-1);\n if (parent) { parent.element.children.push(element); parent.content?.push(element); }\n else if (root) invalid(\"multiple root elements\");\n else root = element;\n const empty = source[offset] === \"/\";\n if (empty) offset++;\n if (source[offset++] !== \">\") invalid(\"unterminated start tag\");\n if (!empty) stack.push({ element, content, name, namespaces });\n }\n }\n if (stack.length || !root) invalid(\"incomplete document\");\n return root;\n}\n\nexport function parseXml(input: string, limits: XmlLimits = {}): XmlElement {\n const parser = parseXmlSteps(input, limits);\n let result = parser.next();\n while (!result.done) result = parser.next();\n return result.value;\n}\n", "import { parseXml as parseDocument, XmlLimitError, type XmlLimits as DocumentLimits } from \"../../xml.js\";\nimport type { XmlElement } from \"../../xml.js\";\nexport type { XmlElement } from \"../../xml.js\";\nexport interface XmlLimits extends Omit<DocumentLimits, \"onElement\"> { readonly maxResponses?: number; }\nexport class XmlResponseLimitError extends SyntaxError {}\nfunction invalid(message: string): never { throw new SyntaxError(`Invalid WebDAV XML: ${message}`); }\n\nexport function parseXml(input: string, limits: XmlLimits = {}): XmlElement {\n const { maxResponses, ...documentLimits } = limits;\n if (maxResponses !== undefined && (!Number.isSafeInteger(maxResponses) || maxResponses < 1)) {\n throw new RangeError(\"XML limits must be positive integers\");\n }\n let responses = 0;\n try {\n return parseDocument(input, { ...documentLimits, retainContent: false,\n onElement(element, parent, depth) {\n if (maxResponses !== undefined && depth === 2 && parent?.namespace === \"DAV:\" && parent.localName === \"multistatus\"\n && element.namespace === \"DAV:\" && element.localName === \"response\" && ++responses > maxResponses) {\n throw new XmlResponseLimitError(\"WebDAV XML response limit exceeded\");\n }\n }\n });\n } catch (error) {\n if (error instanceof XmlLimitError) invalid(error.message);\n if (error instanceof SyntaxError && error.message.startsWith(\"Invalid XML:\")) {\n error.message = error.message.replace(\"Invalid XML:\", \"Invalid WebDAV XML:\");\n }\n throw error;\n }\n}\n\nexport function davChildren(element: XmlElement, localName: string): XmlElement[] {\n return element.children.filter((child) => child.namespace === \"DAV:\" && child.localName === localName);\n}\n\nexport function davChild(element: XmlElement, localName: string): XmlElement | undefined {\n const children = davChildren(element, localName);\n if (children.length > 1) invalid(`duplicate DAV:${localName}`);\n return children[0];\n}\n\nexport function scalar(element: XmlElement): string {\n if (element.children.length) invalid(\"expected text-only element\");\n return element.text.trim();\n}\n", "import { FsError, isErrnoCode, isFsError } from \"../../contracts/errors.js\";\nimport { composeAbortSignals } from \"../../contracts/abort.js\";\nimport type { AbortSignalScope } from \"../../contracts/abort.js\";\nimport type { PlatformComparisonCallback } from \"#safe-fs-platform\";\nimport type { ErrnoCode } from \"../../contracts/errors.js\";\nimport { readBytes } from \"../../contracts/io.js\";\nimport type { ByteSource } from \"../../contracts/io.js\";\nimport type {\n AppendFileOptions, CopyFileOptions, DirectoryEntry, EntryComparison, FileStat, FileSystem, FileSystemCapabilities,\n FsOptions, RenameOptions, MkdirOptions, ReadDirectoryOptions, ReadFileOptions, ReadStreamOptions, RemoveOptions, WriteFileOptions,\n} from \"../../contracts/filesystem.js\";\nimport { davChild, davChildren, parseXml, scalar, XmlResponseLimitError } from \"./xml.js\";\nimport { admitDirectoryEntries, directoryEntryLimit } from \"../directory-admission.js\";\nimport type { FileDescriptor, OpenFileOptions } from \"../../contracts/descriptor.js\";\nimport type { XmlElement } from \"./xml.js\";\nimport { assertCallbackAuthorityAllowed, compareEntries, registerEntryAuthority } from \"../mount/comparison.js\";\nimport { compareWebDavResources, ownedResponseIdentifier, recordOwnedResourceStat, registerResourceQuery, resourceIdentifier } from \"./resource-id.js\";\n\nexport type WebDavFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nexport interface WebDavAtomicEmptyDirectoryRequest {\n readonly operation: \"atomic-empty-rmdir/v1\";\n readonly namespaceUrl: string;\n readonly path: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface WebDavAtomicEmptyDirectoryResult {\n readonly operation: \"atomic-empty-rmdir/v1\";\n readonly namespaceUrl: string;\n readonly path: string;\n readonly outcome: \"removed\";\n}\n\nexport interface WebDavAtomicEmptyDirectoryBinding {\n readonly namespaceUrl: string;\n readonly removeEmptyDirectory: (request: WebDavAtomicEmptyDirectoryRequest) => Promise<WebDavAtomicEmptyDirectoryResult>;\n}\n\nexport interface WebDavFileSystemOptions {\n readonly baseUrl: string;\n readonly fetch: WebDavFetch;\n readonly requestStreamSupport?: \"native\" | boolean;\n readonly headers?: Readonly<Record<string, string>>;\n readonly maxResponseBytes?: number;\n readonly maxXmlBytes?: number;\n readonly maxEntries?: number;\n /** Per-request and aggregate stat/write-preflight walk timeout; defaults to 30,000 ms. */\n readonly timeoutMs?: number;\n readonly overwritePolicy?: \"lock\" | \"etag\";\n readonly atomicEmptyDirectory?: WebDavAtomicEmptyDirectoryBinding;\n readonly compareEntry?: PlatformComparisonCallback<(this: FileSystem, ...args: Parameters<NonNullable<FileSystem[\"compareEntry\"]>>)\n => ReturnType<NonNullable<FileSystem[\"compareEntry\"]>>>;\n}\n\nconst timestampNamespace = \"urn:virtual-bash:metadata\";\nconst propfindBody = '<?xml version=\"1.0\" encoding=\"utf-8\"?>'\n + '<d:propfind xmlns:d=\"DAV:\"><d:prop><d:resourcetype/><d:getcontentlength/>'\n + `<d:getlastmodified/><d:creationdate/><d:getetag/><v:timestamps xmlns:v=\"${timestampNamespace}\"/></d:prop></d:propfind>`;\n\nconst lockBody = '<d:lockinfo xmlns:d=\"DAV:\"><d:lockscope><d:exclusive/></d:lockscope>'\n + '<d:locktype><d:write/></d:locktype></d:lockinfo>';\n\nconst resourceIdBody = '<?xml version=\"1.0\" encoding=\"utf-8\"?>'\n + '<d:propfind xmlns:d=\"DAV:\"><d:prop><d:resource-id/></d:prop></d:propfind>';\n\nfunction fail(code: ErrnoCode, syscall: string, path: string, message?: string): never {\n throw new FsError(code, { syscall, path, ...(message === undefined ? {} : { message }) });\n}\n\nfunction positive(value: number, name: string, zero = false): number {\n if (!Number.isSafeInteger(value) || value < (zero ? 0 : 1)) {\n throw new FsError(\"EINVAL\", { message: `${name} must be a ${zero ? \"nonnegative\" : \"positive\"} safe integer` });\n }\n return value;\n}\n\nfunction createRequestTimeout(timeoutMs: number): AbortSignalScope {\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort(new DOMException(\"The operation was aborted due to timeout\", \"TimeoutError\"));\n }, timeoutMs);\n if (typeof timer === \"object\" && timer !== null) {\n const handle: { unref?(): unknown } = timer;\n handle.unref?.();\n }\n return {\n signal: controller.signal,\n dispose() {\n clearTimeout(timer);\n }\n };\n}\n\nfunction nativeRequestStreamsSupported(url: string): boolean {\n let body: ReadableStream<Uint8Array> | undefined;\n try {\n body = new ReadableStream<Uint8Array>({ start(destination) { destination.close(); } });\n let duplexAccessed = false;\n const init: RequestInit & { duplex: \"half\" } = {\n method: \"PUT\", body,\n get duplex(): \"half\" { duplexAccessed = true; return \"half\"; },\n };\n const request = new Request(url, init);\n return duplexAccessed && !request.headers.has(\"Content-Type\");\n } catch {\n return false;\n } finally {\n if (body && !body.locked) void body.cancel().catch(() => {});\n }\n}\n\nfunction strongEtag(value: string | null | undefined, path: string): string {\n if (!value || !/^\"[\\x21\\x23-\\x7e\\x80-\\xff]*\"$/.test(value)) {\n fail(\"ENOTSUP\", \"webdav\", path, \"operation requires a strong entity tag\");\n }\n return value;\n}\n\nfunction normalize(path: string): string {\n if (typeof path !== \"string\" || path.includes(\"\\0\") || path.includes(\"\\\\\")) {\n fail(\"EINVAL\", \"resolve\", String(path), \"invalid WebDAV path\");\n }\n try { encodeURIComponent(path); }\n catch { fail(\"EINVAL\", \"resolve\", path, \"path contains an unpaired surrogate\"); }\n const segments: string[] = [];\n for (const segment of path.split(\"/\")) {\n if (!segment || segment === \".\") continue;\n if (segment === \"..\") {\n if (!segments.length) fail(\"EACCES\", \"resolve\", path, \"path escapes WebDAV root\");\n segments.pop();\n } else segments.push(segment);\n }\n return `/${segments.join(\"/\")}`;\n}\n\nfunction validateDirectoryWalkPath(path: string, syscall = \"access\"): void {\n if (typeof path !== \"string\") fail(\"EINVAL\", \"resolve\", String(path), \"invalid WebDAV path\");\n let bytes = 0;\n let components = 0;\n let inComponent = false;\n for (let offset = 0; offset < path.length; offset++) {\n const point = path.codePointAt(offset)!;\n if (point === 47) inComponent = false;\n else if (!inComponent) {\n components++;\n inComponent = true;\n }\n bytes += point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;\n if (point > 0xffff) offset++;\n if (bytes > 65_536 || components > 256) {\n fail(\"ENAMETOOLONG\", syscall, path, \"directory access exceeds the 64KiB path or 256 component limit\");\n }\n }\n}\n\nfunction requiresCollection(path: string): boolean {\n const last = path.split(\"/\").at(-1);\n return last === \"\" || last === \".\" || last === \"..\";\n}\n\nfunction validateUrlText(text: string): void {\n if (/[\\u0000-\\u0020\\u007f\\\\?#]/.test(text)) throw new Error(\"invalid URL characters\");\n for (const segment of text.split(\"/\")) {\n const decoded = decodeURIComponent(segment);\n if (decoded === \".\" || decoded === \"..\" || /[/\\\\\\u0000]/.test(decoded)) {\n throw new Error(\"ambiguous URL segment\");\n }\n }\n}\n\nfunction urlSegments(url: URL): string[] {\n const pathname = url.pathname.endsWith(\"/\") ? url.pathname.slice(0, -1) : url.pathname;\n const segments = pathname.slice(1).split(\"/\");\n if (segments.length === 1 && segments[0] === \"\") return [];\n if (segments.some((segment) => segment === \"\")) throw new Error(\"empty URL segment\");\n return segments.map((segment) => decodeURIComponent(segment));\n}\n\nfunction statusCode(element: XmlElement): number {\n const text = scalar(element);\n if (!/^HTTP\\/\\d+\\.\\d+ [2-5]\\d\\d(?:[ \\t].*)?$/.test(text)) throw new Error(\"invalid DAV status line\");\n return Number(text.split(\" \")[1]);\n}\n\nexport class WebDavFileSystem implements FileSystem {\n async open(path: string, options: OpenFileOptions): Promise<FileDescriptor> {\n options.signal?.throwIfAborted();\n throw new FsError(\"ENOTSUP\", { syscall: \"open\", path });\n }\n\n readonly capabilities = Object.freeze({\n open: false,\n read: true, stat: true, readdir: true, realpath: true, access: true,\n write: true, append: true, exclusiveCreate: true, explicitDirectories: true, implicitDirectories: false,\n mkdir: true, recursiveMkdir: true, remove: true, recursiveRemove: true, rename: true, atomicRenameNoReplace: false, copy: true,\n exclusiveCopy: true, readlink: false, truncate: false, randomAccessWrite: false,\n removeDirectory: false as boolean, streamingAppend: false as boolean,\n symlinks: false, hardlinks: false, permissions: false, timestamps: true,\n atomicRename: false, streamingRead: true, streamingWrite: true,\n } satisfies FileSystemCapabilities);\n private readonly base: URL;\n private readonly baseSegments: string[];\n private readonly transport: WebDavFetch;\n private readonly requestStreamSupport: \"native\" | boolean;\n private readonly headers: Headers;\n private readonly maxResponseBytes: number;\n private readonly maxXmlBytes: number;\n private readonly maxEntries: number;\n private readonly timeoutMs: number;\n private readonly walkDeadlines = new WeakMap<FsOptions, { deadline?: AbortSignalScope }>();\n private readonly overwritePolicy: \"lock\" | \"etag\";\n private readonly configuredComparison: boolean;\n private readonly atomicEmptyDirectory: WebDavAtomicEmptyDirectoryBinding | undefined;\n private readonly etags = new WeakMap<FileStat, string>();\n\n constructor(options: WebDavFileSystemOptions) {\n if (typeof options.fetch !== \"function\") throw new FsError(\"EINVAL\", { message: \"an explicit fetch transport is required\" });\n if (options.requestStreamSupport !== undefined && options.requestStreamSupport !== \"native\"\n && typeof options.requestStreamSupport !== \"boolean\") {\n throw new FsError(\"EINVAL\", { message: \"requestStreamSupport must be native or a boolean\" });\n }\n if (options.compareEntry !== undefined && typeof options.compareEntry !== \"function\") {\n throw new FsError(\"EINVAL\", { message: \"compareEntry must be a function\" });\n }\n if (options.compareEntry !== undefined) assertCallbackAuthorityAllowed();\n try {\n validateUrlText(options.baseUrl);\n this.base = new URL(options.baseUrl);\n if (![\"http:\", \"https:\"].includes(this.base.protocol) || this.base.username || this.base.password\n || this.base.search || this.base.hash) throw new Error(\"invalid base URL\");\n this.baseSegments = urlSegments(this.base);\n this.base.pathname = `/${this.baseSegments.map(encodeURIComponent).join(\"/\")}${this.baseSegments.length ? \"/\" : \"\"}`;\n this.headers = new Headers(options.headers);\n for (const name of this.headers.keys()) {\n if ([\"host\", \"destination\", \"depth\", \"overwrite\", \"if\", \"if-match\", \"if-none-match\", \"range\",\n \"content-length\", \"content-type\", \"transfer-encoding\", \"connection\", \"proxy-authorization\", \"lock-token\", \"timeout\"].includes(name)) {\n throw new Error(`reserved header ${name}`);\n }\n }\n if (this.base.protocol !== \"https:\" && [...this.headers.keys()].some((name) => name === \"authorization\" || name === \"cookie\")) {\n throw new Error(\"explicit credentials require HTTPS\");\n }\n } catch (cause) {\n throw new FsError(\"EINVAL\", { message: \"invalid WebDAV base URL or headers\", cause });\n }\n const binding = options.atomicEmptyDirectory;\n if (binding !== undefined) {\n if (!binding || typeof binding !== \"object\" || binding.namespaceUrl !== this.base.href\n || typeof binding.removeEmptyDirectory !== \"function\") {\n throw new FsError(\"EINVAL\", { message: \"atomicEmptyDirectory must bind the canonical WebDAV namespace and a callback\" });\n }\n this.atomicEmptyDirectory = Object.freeze({ namespaceUrl: this.base.href, removeEmptyDirectory: binding.removeEmptyDirectory });\n }\n this.transport = options.fetch === globalThis.fetch ? options.fetch.bind(globalThis) : options.fetch;\n this.requestStreamSupport = options.requestStreamSupport ?? (options.fetch === globalThis.fetch ? \"native\" : false);\n this.capabilities = Object.freeze({ ...this.capabilities,\n removeDirectory: this.atomicEmptyDirectory !== undefined,\n streamingAppend: this.requestStreamSupport !== false,\n });\n this.maxResponseBytes = positive(options.maxResponseBytes ?? 64 * 1024 * 1024, \"maxResponseBytes\");\n this.maxXmlBytes = positive(options.maxXmlBytes ?? 2 * 1024 * 1024, \"maxXmlBytes\");\n this.maxEntries = positive(options.maxEntries ?? 10_000, \"maxEntries\");\n this.timeoutMs = positive(options.timeoutMs ?? 30_000, \"timeoutMs\");\n this.overwritePolicy = options.overwritePolicy ?? \"lock\";\n this.configuredComparison = options.compareEntry !== undefined;\n if (![\"lock\", \"etag\"].includes(this.overwritePolicy)) throw new FsError(\"EINVAL\", { message: \"invalid overwritePolicy\" });\n if (this.timeoutMs > 2_147_483_647) throw new FsError(\"EINVAL\", { message: \"timeoutMs exceeds timer range\" });\n registerResourceQuery(this, (path, settings) => this.resourceId(path, settings), originalWebDavComparison, options.compareEntry);\n registerEntryAuthority(this, compareWebDavResources);\n }\n\n compareEntry(path: string, peer: FileSystem, peerPath: string, options: FsOptions = {}): Promise<EntryComparison> {\n return compareEntries(this, path, peer, peerPath, options);\n }\n\n private async resourceId(input: string, options: FsOptions): Promise<string | undefined> {\n const path = normalize(input);\n return this.request(\"PROPFIND\", path, options, {\n headers: { Depth: \"0\", \"Content-Type\": \"application/xml; charset=utf-8\" }, body: resourceIdBody,\n }, async (response, signal) => {\n if (response.status !== 207) this.httpError(response.status, \"PROPFIND\", path);\n const responses = await this.multistatus(response, signal, \"PROPFIND\", path);\n if (responses.length !== 1) throw new Error(\"resource identity requires exactly one DAV:response\");\n const entry = responses[0]!;\n const href = davChild(entry, \"href\");\n if (!href) throw new Error(\"missing resource identity response href\");\n if (this.hrefPath(scalar(href)) !== path) fail(\"EACCES\", \"PROPFIND\", path, \"resource identity response addresses another resource\");\n const wholeStatus = davChild(entry, \"status\");\n const propstats = davChildren(entry, \"propstat\");\n if (wholeStatus) {\n if (propstats.length) throw new Error(\"conflicting response status and propstat\");\n this.httpError(statusCode(wholeStatus), \"PROPFIND\", path);\n }\n if (propstats.length === 0) throw new Error(\"missing resource identity propstat\");\n let seen = false;\n let identifier: string | undefined;\n for (const propstat of propstats) {\n const status = davChild(propstat, \"status\");\n const prop = davChild(propstat, \"prop\");\n if (!status || !prop) throw new Error(\"incomplete resource identity propstat\");\n const code = statusCode(status);\n if (code !== 200 && code !== 404) this.httpError(code, \"PROPFIND\", path);\n for (const property of davChildren(prop, \"resource-id\")) {\n if (seen) throw new Error(\"duplicate or conflicting resource identity property\");\n seen = true;\n if (code === 404) continue;\n const value = davChild(property, \"href\");\n if (!value || property.children.length !== 1 || property.text.trim()) throw new Error(\"invalid resource identity property\");\n identifier = resourceIdentifier(scalar(value));\n }\n }\n const owned = ownedResponseIdentifier(response, path);\n if (owned !== undefined && identifier !== undefined && resourceIdentifier(owned) !== identifier) {\n throw new Error(\"resource identity contradicts provider provenance\");\n }\n return identifier;\n });\n }\n\n private url(path: string, collection = false): string {\n const relative = path.slice(1).split(\"/\").map(encodeURIComponent).join(\"/\");\n return `${this.base.href}${relative}${collection && relative ? \"/\" : \"\"}`;\n }\n\n private hrefPath(href: string): string {\n try {\n validateUrlText(href);\n if (!(href.startsWith(\"/\") && !href.startsWith(\"//\")) && !/^https?:\\/\\//i.test(href)) throw new Error(\"href must be absolute\");\n const url = new URL(href, this.base);\n if (url.origin !== this.base.origin || url.username || url.password || url.search || url.hash) throw new Error(\"href is not confined\");\n const segments = urlSegments(url);\n if (segments.length < this.baseSegments.length || this.baseSegments.some((segment, index) => segments[index] !== segment)) {\n throw new Error(\"href escapes root\");\n }\n return normalize(`/${segments.slice(this.baseSegments.length).join(\"/\")}`);\n } catch (cause) {\n throw new FsError(\"EACCES\", { syscall: \"webdav\", message: \"response URL escapes or ambiguously addresses WebDAV root\", cause });\n }\n }\n\n private httpError(status: number, method: string, path: string, exclusive = false): never {\n const codes: Partial<Record<number, ErrnoCode>> = {\n 400: \"EINVAL\", 401: \"EACCES\", 403: \"EACCES\", 404: \"ENOENT\", 405: method === \"MKCOL\" ? \"EEXIST\" : \"ENOTSUP\",\n 408: \"ETIMEDOUT\", 409: method === \"PUT\" || method === \"MKCOL\" ? \"ENOENT\" : \"EINVAL\", 410: \"ENOENT\",\n 412: exclusive ? \"EEXIST\" : \"EAGAIN\", 413: \"EFBIG\", 414: \"ENAMETOOLONG\", 415: \"ENOTSUP\",\n 423: \"EBUSY\", 429: \"EAGAIN\", 501: \"ENOTSUP\", 503: \"EAGAIN\", 504: \"ETIMEDOUT\", 507: \"ENOSPC\",\n };\n fail(status >= 300 && status < 400 ? \"ENOTSUP\" : codes[status] ?? \"EIO\", method, path,\n status >= 300 && status < 400 ? \"WebDAV redirects are not followed\" : `WebDAV HTTP status ${status}`);\n }\n\n private async request<T>(method: string, path: string, options: FsOptions, init: RequestInit,\n consume: (response: Response, signal: AbortSignal) => Promise<T>, collection = false,\n received?: (response: Response, late: boolean) => void): Promise<T> {\n for await (const result of this.requestStream(method, path, options, init, async function* (response, signal) {\n yield await consume(response, signal);\n }, collection, received)) return result;\n throw new Error(\"missing WebDAV response\");\n }\n\n private async *requestStream<T>(method: string, path: string, options: FsOptions, init: RequestInit,\n consume: (response: Response, signal: AbortSignal) => AsyncIterable<T>, collection = false,\n received?: (response: Response, late: boolean) => void): AsyncGenerator<T> {\n if (options.signal?.aborted) fail(\"ECANCELED\", method, path);\n const walk = this.walkDeadlines.get(options);\n const deadline = walk?.deadline ?? createRequestTimeout(this.timeoutMs);\n if (walk) walk.deadline = deadline;\n const timeout = deadline.signal;\n try {\n const headers = new Headers(this.headers);\n for (const [name, value] of new Headers(init.headers)) headers.set(name, value);\n headers.set(\"Cache-Control\", \"no-cache\");\n const signalScope = options.signal ? composeAbortSignals([timeout, options.signal]) : undefined;\n const signal = signalScope?.signal ?? timeout;\n let response: Response | undefined;\n const receive = (value: Response, late: boolean): void => {\n if (value.redirected || value.type === \"opaqueredirect\") fail(\"ENOTSUP\", method, path, \"transport followed or hid a redirect\");\n if (value.url && this.hrefPath(value.url) !== path) fail(\"EACCES\", method, path, \"transport changed the requested resource\");\n received?.(value, late);\n };\n try {\n let url = this.url(path, collection);\n for (let attempt = 0; ; attempt++) {\n signal.throwIfAborted();\n response = await new Promise<Response>((resolve, reject) => {\n let abandoned = false;\n const abort = (): void => {\n abandoned = true;\n signal.removeEventListener(\"abort\", abort);\n reject(signal.reason);\n };\n signal.addEventListener(\"abort\", abort, { once: true });\n try {\n Promise.resolve(this.transport(url, {\n ...init, method, headers, redirect: \"manual\", credentials: \"omit\", signal,\n })).then((value) => {\n signal.removeEventListener(\"abort\", abort);\n if (!abandoned) resolve(value);\n else {\n try { receive(value, true); }\n catch (ignoredError) { void ignoredError; }\n finally {\n if (value.body && !value.body.locked) void value.body.cancel(signal.reason).catch(() => {});\n }\n }\n }, (error: unknown) => {\n signal.removeEventListener(\"abort\", abort);\n reject(error);\n }).catch(reject);\n } catch (error) {\n signal.removeEventListener(\"abort\", abort);\n reject(error);\n }\n });\n receive(response, false);\n signal.throwIfAborted();\n const location = response.headers.get(\"Location\");\n if (attempt === 0 && method === \"PROPFIND\" && !url.endsWith(\"/\")\n && [301, 302, 307, 308].includes(response.status) && location !== null\n && this.hrefPath(location) === path && new URL(location, this.base).href === `${url}/`) {\n await response.body?.cancel();\n signal.throwIfAborted();\n url += \"/\";\n continue;\n }\n yield* consume(response, signal);\n return;\n }\n } catch (cause) {\n if (options.signal?.aborted) throw new FsError(\"ECANCELED\", { syscall: method, path, cause });\n if (timeout.aborted) throw new FsError(\"ETIMEDOUT\", { syscall: method, path, cause });\n if (isFsError(cause)) throw cause;\n throw new FsError(\"EIO\", { syscall: method, path, message: \"WebDAV transport or response failure\", cause });\n } finally {\n signalScope?.dispose();\n if (response?.body && !response.body.locked) void response.body.cancel().catch(() => {});\n }\n } finally {\n if (!walk) deadline.dispose();\n }\n }\n\n private async bytes(response: Response, limit: number, signal: AbortSignal): Promise<Uint8Array> {\n const chunks: Uint8Array[] = [];\n let size = 0;\n for await (const chunk of this.bodyChunks(response, limit, signal)) {\n chunks.push(chunk);\n size += chunk.byteLength;\n }\n const data = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.byteLength; }\n return data;\n }\n\n private async *bodyChunks(response: Response, limit: number, signal: AbortSignal): AsyncGenerator<Uint8Array> {\n const length = response.headers.get(\"content-length\");\n if (length !== null && (!/^\\d+$/.test(length) || !Number.isSafeInteger(Number(length)))) {\n fail(\"EIO\", \"webdav\", \"\", \"invalid response Content-Length\");\n }\n const encoding = response.headers.get(\"content-encoding\");\n const expected = length !== null && (!encoding || encoding.toLowerCase() === \"identity\") ? Number(length) : undefined;\n if (expected !== undefined && expected > limit) fail(\"EFBIG\", \"webdav\", \"\", \"response exceeds byte limit\");\n if (!response.body) {\n if (expected !== undefined && expected !== 0) fail(\"EIO\", \"webdav\", \"\", \"response body length differs from Content-Length\");\n return;\n }\n const reader = response.body.getReader();\n let size = 0;\n const abort = (): void => { void reader.cancel(signal.reason).catch(() => {}); };\n signal.addEventListener(\"abort\", abort, { once: true });\n try {\n while (true) {\n signal.throwIfAborted();\n const result = await reader.read();\n signal.throwIfAborted();\n if (result.done) break;\n size += result.value.byteLength;\n if (size > limit) fail(\"EFBIG\", \"webdav\", \"\", \"response exceeds byte limit\");\n if (expected !== undefined && size > expected) fail(\"EIO\", \"webdav\", \"\", \"response body length differs from Content-Length\");\n yield new Uint8Array(result.value);\n }\n if (expected !== undefined && size !== expected) fail(\"EIO\", \"webdav\", \"\", \"response body length differs from Content-Length\");\n } finally {\n signal.removeEventListener(\"abort\", abort);\n void reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n }\n\n private async xml(response: Response, signal: AbortSignal, maxResponses?: number): Promise<XmlElement> {\n const data = await this.bytes(response, this.maxXmlBytes, signal);\n const encoding = (data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0x3c && data[1] === 0)\n ? \"utf-16le\" : (data[0] === 0xfe && data[1] === 0xff) || (data[0] === 0 && data[1] === 0x3c) ? \"utf-16be\" : \"utf-8\";\n return parseXml(new TextDecoder(encoding, { fatal: true }).decode(data), maxResponses === undefined ? undefined : { maxResponses });\n }\n\n private async multistatus(response: Response, signal: AbortSignal, method = \"PROPFIND\", path = \"\"): Promise<XmlElement[]> {\n const link = response.headers.get(\"link\");\n if (link && /\\brel\\s*=\\s*(?:\"[^\"]*\\bnext\\b[^\"]*\"|'[^']*\\bnext\\b[^']*'|next\\b)/i.test(link)) {\n fail(\"ENOTSUP\", method, path, \"paginated WebDAV responses are unsupported\");\n }\n let root: XmlElement;\n try { root = await this.xml(response, signal, this.maxEntries); }\n catch (error) {\n if (error instanceof XmlResponseLimitError) fail(\"EFBIG\", method, path, \"response exceeds entry limit\");\n throw error;\n }\n if (root.namespace !== \"DAV:\" || root.localName !== \"multistatus\") throw new Error(\"expected DAV:multistatus\");\n const responses = davChildren(root, \"response\");\n if (responses.length > this.maxEntries) fail(\"EFBIG\", method, path, \"response exceeds entry limit\");\n return responses;\n }\n\n private async lockFailure(response: Response, signal: AbortSignal, path: string): Promise<never> {\n try {\n const members = new Set<string>();\n let failure: { member: string; status: number } | undefined;\n for (const element of await this.multistatus(response, signal, \"LOCK\", path)) {\n const href = davChild(element, \"href\");\n const status = davChild(element, \"status\");\n if (!href || !status) throw new Error(\"invalid LOCK multistatus\");\n const member = this.hrefPath(scalar(href));\n if (member !== path && !member.startsWith(`${path}/`)) {\n fail(\"EACCES\", \"LOCK\", path, \"LOCK response member is outside requested subtree\");\n }\n if (members.has(member)) throw new Error(\"duplicate LOCK response href\");\n members.add(member);\n const code = statusCode(status);\n if (code >= 300 && (!failure || (failure.status === 424 && code !== 424))) {\n failure = { member, status: code };\n }\n }\n if (!failure) throw new Error(\"LOCK multistatus without a reported failure\");\n this.httpError(failure.status, \"LOCK\", failure.member);\n } catch (cause) {\n throw new FsError(isFsError(cause) ? cause.code : \"EIO\", {\n syscall: \"LOCK\", path, message: \"WebDAV LOCK multistatus failure\", cause,\n });\n }\n }\n\n private entryStat(element: XmlElement, path: string): FileStat {\n const wholeStatus = davChild(element, \"status\");\n if (wholeStatus) {\n const code = statusCode(wholeStatus);\n if (code < 200 || code >= 300) this.httpError(code, \"PROPFIND\", path);\n }\n const properties = new Map<string, XmlElement>();\n const failures = new Map<string, number>();\n let timestampProperty: XmlElement | undefined;\n let timestampSeen = false;\n for (const propstat of davChildren(element, \"propstat\")) {\n const status = davChild(propstat, \"status\");\n const prop = davChild(propstat, \"prop\");\n if (!status || !prop) throw new Error(\"incomplete DAV:propstat\");\n const code = statusCode(status);\n for (const property of prop.children) {\n if (property.namespace === timestampNamespace && property.localName === \"timestamps\") {\n if (timestampSeen) throw new Error(\"duplicate timestamp property\");\n timestampSeen = true;\n if (code === 200) timestampProperty = property;\n }\n if (property.namespace !== \"DAV:\") continue;\n if (properties.has(property.localName) || failures.has(property.localName)) throw new Error(\"duplicate DAV property\");\n if (code >= 200 && code < 300) properties.set(property.localName, property);\n else failures.set(property.localName, code);\n }\n }\n const required = (name: string): XmlElement => {\n const property = properties.get(name);\n if (property) return property;\n const failure = failures.get(name);\n if (failure !== undefined && failure !== 404) this.httpError(failure, \"PROPFIND\", path);\n return fail(\"ENOTSUP\", \"stat\", path, `server does not expose DAV:${name}`);\n };\n const resourceType = required(\"resourcetype\");\n const directory = !!davChild(resourceType, \"collection\");\n if (resourceType.text.trim() || resourceType.children.some((child) => child.namespace !== \"DAV:\" || child.localName !== \"collection\")) {\n fail(\"ENOTSUP\", \"stat\", path, \"unsupported DAV resource type\");\n }\n const sizeText = directory ? \"0\" : scalar(required(\"getcontentlength\"));\n if (!/^\\d+$/.test(sizeText) || !Number.isSafeInteger(Number(sizeText))) throw new Error(\"invalid content length property\");\n const date = (name: string): number | undefined => {\n const property = properties.get(name);\n if (!property) return undefined;\n const value = Date.parse(scalar(property));\n if (!Number.isFinite(value)) throw new Error(\"invalid date property\");\n return value;\n };\n const birthtimeMs = date(\"creationdate\");\n const etag = properties.get(\"getetag\");\n const validator = etag && scalar(etag);\n let mtimeMs = date(\"getlastmodified\") ?? 0;\n let atimeMs = 0;\n if (timestampProperty) {\n const timestamps: unknown = JSON.parse(scalar(timestampProperty));\n if (typeof timestamps !== \"object\" || timestamps === null\n || !(\"version\" in timestamps) || timestamps.version !== 1\n || !(\"etag\" in timestamps) || typeof timestamps.etag !== \"string\" || !/^\"[\\x21\\x23-\\x7e\\x80-\\xff]*\"$/.test(timestamps.etag)\n || !(\"type\" in timestamps) || (timestamps.type !== \"file\" && timestamps.type !== \"directory\")\n || !(\"atimeMs\" in timestamps) || typeof timestamps.atimeMs !== \"number\" || !Number.isFinite(timestamps.atimeMs)\n || Math.abs(timestamps.atimeMs) > 8.64e15\n || !(\"mtimeMs\" in timestamps) || typeof timestamps.mtimeMs !== \"number\" || !Number.isFinite(timestamps.mtimeMs)\n || Math.abs(timestamps.mtimeMs) > 8.64e15) throw new Error(\"invalid timestamp property\");\n if (timestamps.etag === validator && timestamps.type === (directory ? \"directory\" : \"file\")) {\n mtimeMs = timestamps.mtimeMs;\n atimeMs = timestamps.atimeMs;\n }\n }\n const stat: FileStat = {\n type: directory ? \"directory\" : \"file\", size: Number(sizeText), mode: directory ? 0o40777 : 0o100666,\n mtimeMs, atimeMs, ctimeMs: 0,\n ...(birthtimeMs === undefined ? {} : { birthtimeMs }),\n };\n if (validator) this.etags.set(stat, validator);\n return stat;\n }\n\n private async entries(path: string, depth: \"0\" | \"1\", options: FsOptions, collection = depth === \"1\", limit?: number): Promise<Map<string, FileStat>> {\n return this.request(\"PROPFIND\", path, options, {\n headers: { Depth: depth, \"Content-Type\": \"application/xml; charset=utf-8\" }, body: propfindBody,\n }, async (response, signal) => {\n if (response.status !== 207) this.httpError(response.status, \"PROPFIND\", path);\n const result = new Map<string, FileStat>();\n let children = 0;\n for (const element of await this.multistatus(response, signal)) {\n signal.throwIfAborted();\n const href = davChild(element, \"href\");\n if (!href) throw new Error(\"missing DAV:href\");\n const member = this.hrefPath(scalar(href));\n const prefix = path === \"/\" ? \"/\" : `${path}/`;\n if (member !== path && (depth === \"0\" || !member.startsWith(prefix) || member.slice(prefix.length).includes(\"/\"))) {\n fail(\"EACCES\", \"PROPFIND\", path, \"response member is outside requested depth\");\n }\n if (result.has(member)) throw new Error(\"duplicate response href\");\n if (member !== path) admitDirectoryEntries(++children, limit, path);\n const stat = this.entryStat(element, member);\n recordOwnedResourceStat(response, this, member, stat);\n result.set(member, stat);\n }\n if (!result.has(path)) throw new Error(\"response omitted requested resource\");\n return result;\n }, collection);\n }\n\n private async mutation(method: string, path: string, options: FsOptions, init: RequestInit = {}, collection = false): Promise<void> {\n await this.request(method, path, options, init, async (response, signal) => {\n if (response.status === 207) {\n for (const element of await this.multistatus(response, signal)) {\n const href = davChild(element, \"href\");\n const status = davChild(element, \"status\");\n if (!href || !status) throw new Error(\"invalid mutation multistatus\");\n const member = this.hrefPath(scalar(href));\n const code = statusCode(status);\n if (code < 200 || code >= 300) {\n try { this.httpError(code, method, member); }\n catch (cause) { throw new FsError(\"EIO\", { syscall: method, path, message: \"WebDAV mutation partially failed\", cause }); }\n }\n }\n fail(\"EIO\", method, path, \"unexpected mutation multistatus without a reported failure\");\n }\n const accepted = method === \"PUT\" ? [200, 201, 204] : method === \"MKCOL\" ? [201] : method === \"DELETE\" ? [204] : [201, 204];\n if (!accepted.includes(response.status)) {\n const headers = new Headers(init.headers);\n this.httpError(response.status, method, path, headers.get(\"If-None-Match\") === \"*\" || headers.get(\"Overwrite\") === \"F\");\n }\n }, collection);\n }\n\n private unsupported(operation: string, path: string): never {\n return fail(\"ENOTSUP\", operation, path, `${operation} has no safe portable WebDAV equivalent`);\n }\n\n private async maybeStat(path: string, options: FsOptions): Promise<FileStat | undefined> {\n try { return await this.stat(path, options); }\n catch (error) { if (isFsError(error, \"ENOENT\")) return undefined; throw error; }\n }\n\n private async withWalkDeadline<Options extends FsOptions, Result>(\n options: Options, walk: (options: Options) => Promise<Result>,\n ): Promise<Result> {\n if (this.walkDeadlines.has(options)) return walk(options);\n const scopedOptions = { ...options };\n const owned: { deadline?: AbortSignalScope } = {};\n this.walkDeadlines.set(scopedOptions, owned);\n try { return await walk(scopedOptions); }\n finally {\n owned.deadline?.dispose();\n this.walkDeadlines.delete(scopedOptions);\n }\n }\n\n async stat(path: string, options: FsOptions = {}): Promise<FileStat> {\n validateDirectoryWalkPath(path, \"stat\");\n return this.statWithAncestors(path, options);\n }\n\n private async statWithAncestors(path: string, options: FsOptions): Promise<FileStat> {\n const normalized = normalize(path);\n const collection = requiresCollection(path);\n return this.withWalkDeadline(options, async scopedOptions => {\n try {\n const stat = (await this.entries(normalized, \"0\", scopedOptions, collection)).get(normalized)!;\n if (collection && stat.type !== \"directory\") fail(\"ENOTDIR\", \"stat\", path);\n return stat;\n } catch (error) {\n if (!isFsError(error, \"ENOENT\")) throw error;\n let parent = \"\";\n for (const segment of normalized.slice(1).split(\"/\").slice(0, -1)) {\n parent += `/${segment}`;\n const ancestor = (await this.entries(parent, \"0\", scopedOptions)).get(parent)!;\n if (ancestor.type !== \"directory\") fail(\"ENOTDIR\", \"stat\", path);\n }\n throw error;\n }\n });\n }\n\n async lstat(path: string, options: FsOptions = {}): Promise<FileStat> {\n return this.stat(path, options);\n }\n\n async readdir(path: string, options: ReadDirectoryOptions = {}): Promise<DirectoryEntry[]> {\n let limit: number | undefined;\n if (options.maxEntries !== undefined) {\n if (options.signal?.aborted) fail(\"ECANCELED\", \"readdir\", path);\n limit = directoryEntryLimit(options, path);\n }\n const normalized = normalize(path);\n const entries = await this.entries(normalized, \"1\", options, true, limit);\n if (entries.get(normalized)!.type !== \"directory\") fail(\"ENOTDIR\", \"readdir\", path);\n return [...entries].filter(([member]) => member !== normalized)\n .map(([member, stat]) => ({ name: member.slice(member.lastIndexOf(\"/\") + 1), type: stat.type }))\n .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);\n }\n\n async readFile(path: string, options: ReadFileOptions = {}): Promise<Uint8Array> {\n const normalized = normalize(path);\n const limit = Math.min(this.maxResponseBytes, positive(options.maxBytes ?? this.maxResponseBytes, \"maxBytes\", true));\n if ((await this.stat(path, options)).type === \"directory\") fail(\"EISDIR\", \"readFile\", path);\n return this.request(\"GET\", normalized, options, { headers: { \"Accept-Encoding\": \"identity\" } }, async (response, signal) => {\n if (response.status !== 200) this.httpError(response.status, \"GET\", path);\n return this.bytes(response, limit, signal);\n });\n }\n\n async *readStream(path: string, options: ReadStreamOptions = {}): AsyncGenerator<Uint8Array> {\n const normalized = normalize(path);\n const start = positive(options.start ?? 0, \"start\", true);\n const end = options.endExclusive === undefined ? Infinity : positive(options.endExclusive, \"endExclusive\", true);\n const chunkSize = positive(options.chunkSize ?? 64 * 1024, \"chunkSize\");\n if (end < start) fail(\"EINVAL\", \"readStream\", path, \"endExclusive precedes start\");\n if ((await this.stat(path, options)).type === \"directory\") fail(\"EISDIR\", \"readStream\", path);\n yield* this.requestStream(\"GET\", normalized, options, { headers: { \"Accept-Encoding\": \"identity\" } }, async function* (this: WebDavFileSystem, response: Response, signal: AbortSignal) {\n if (response.status !== 200) this.httpError(response.status, \"GET\", path);\n let position = 0;\n for await (const chunk of this.bodyChunks(response, this.maxResponseBytes, signal)) {\n const first = Math.max(0, start - position);\n const last = Math.min(chunk.byteLength, end - position);\n for (let offset = first; offset < last; offset += chunkSize) {\n signal.throwIfAborted();\n yield chunk.slice(offset, Math.min(last, offset + chunkSize));\n }\n position += chunk.byteLength;\n if (position >= end) return;\n }\n }.bind(this));\n }\n\n private async prepareWrite(path: string, options: WriteFileOptions): Promise<{\n normalized: string; headers: Record<string, string>; prefix: Uint8Array;\n }> {\n validateDirectoryWalkPath(path, \"writeFile\");\n const normalized = normalize(path);\n if (options.mode !== undefined) this.unsupported(\"writeFile mode\", path);\n if (options.flag !== undefined && ![\"w\", \"wx\", \"a\", \"ax\"].includes(options.flag)) fail(\"EINVAL\", \"writeFile\", path);\n if (options.signal?.aborted) fail(\"ECANCELED\", \"writeFile\", path);\n if (normalized === \"/\") fail(\"EISDIR\", \"writeFile\", path);\n return this.withWalkDeadline(options, async scopedOptions => {\n if (requiresCollection(path)) {\n await this.stat(path, scopedOptions);\n fail(\"EISDIR\", \"writeFile\", path);\n }\n let parent = \"\";\n for (const segment of normalized.slice(1).split(\"/\").slice(0, -1)) {\n parent += `/${segment}`;\n await this.stat(`${parent}/`, scopedOptions);\n }\n const exclusive = options.flag === \"wx\" || options.flag === \"ax\";\n const existing = exclusive ? undefined : await this.maybeStat(normalized, scopedOptions);\n if (existing?.type === \"directory\") fail(\"EISDIR\", \"writeFile\", path);\n let prefix: Uint8Array = new Uint8Array();\n const headers: Record<string, string> = { \"Content-Type\": \"application/octet-stream\" };\n if (exclusive || (options.flag === \"a\" && !existing)) headers[\"If-None-Match\"] = \"*\";\n if (options.flag === \"a\" && existing) {\n const snapshot = await this.request(\"GET\", normalized, scopedOptions, { headers: { \"Accept-Encoding\": \"identity\" } }, async (response, signal) => {\n if (response.status !== 200) this.httpError(response.status, \"GET\", path);\n const etag = strongEtag(response.headers.get(\"ETag\"), path);\n if (response.headers.get(\"Content-Encoding\") && response.headers.get(\"Content-Encoding\")!.toLowerCase() !== \"identity\") {\n fail(\"ENOTSUP\", \"appendFile\", path, \"conditional append requires an identity representation\");\n }\n return { etag, data: await this.bytes(response, this.maxResponseBytes, signal) };\n });\n prefix = snapshot.data;\n headers[\"If-Match\"] = snapshot.etag;\n }\n return { normalized, headers, prefix };\n });\n }\n\n async writeFile(path: string, data: Uint8Array, options: WriteFileOptions = {}): Promise<void> {\n if (!(data instanceof Uint8Array)) fail(\"EINVAL\", \"writeFile\", path, \"data must be Uint8Array\");\n const { normalized, headers, prefix } = await this.prepareWrite(path, options);\n if (options.flag === \"a\" && prefix.byteLength + data.byteLength > this.maxResponseBytes) fail(\"EFBIG\", \"appendFile\", path);\n const body = new Uint8Array(prefix.byteLength + data.byteLength);\n body.set(prefix);\n body.set(data, prefix.byteLength);\n await this.mutation(\"PUT\", normalized, options, {\n headers, body,\n });\n }\n\n async writeStream(path: string, source: ByteSource, options: WriteFileOptions = {}): Promise<void> {\n if (options.signal?.aborted) fail(\"ECANCELED\", \"writeStream\", path);\n if (this.requestStreamSupport === false\n || (this.requestStreamSupport === \"native\" && !nativeRequestStreamsSupported(this.base.href))) {\n fail(\"ENOTSUP\", \"writeStream\", path, \"transport does not declare supported request streams\");\n }\n const { normalized, headers, prefix } = await this.prepareWrite(path, options);\n const deadline = createRequestTimeout(this.timeoutMs);\n const timeout = deadline.signal;\n try {\n const controller = new AbortController();\n const signalScope = composeAbortSignals([timeout, controller.signal, ...(options.signal ? [options.signal] : [])]);\n const signal = signalScope.signal;\n const limit = this.maxResponseBytes;\n const chunks = (async function* () {\n let size = prefix.byteLength;\n if (prefix.byteLength) yield prefix;\n for await (const chunk of readBytes(source, signal)) {\n size += chunk.byteLength;\n if (size > limit) fail(\"EFBIG\", \"writeStream\", path, \"upload exceeds byte limit\");\n yield new Uint8Array(chunk);\n }\n })();\n let finished = false;\n let uploadError: unknown;\n let body: ReadableStream<Uint8Array> | undefined;\n try {\n body = new ReadableStream<Uint8Array>({\n async pull(destination) {\n try {\n const result = await chunks.next();\n if (result.done) { finished = true; destination.close(); }\n else destination.enqueue(result.value);\n } catch (cause) { uploadError = cause; destination.error(cause); }\n },\n cancel(reason) { controller.abort(reason); void chunks.return(undefined).catch(() => {}); },\n }, { highWaterMark: 0 });\n try {\n const request: RequestInit & { duplex: \"half\" } = { headers, body, duplex: \"half\" };\n await this.mutation(\"PUT\", normalized, options, request);\n if (uploadError !== undefined) throw uploadError;\n if (!finished) fail(\"EIO\", \"writeStream\", path, \"server responded before consuming the upload\");\n } catch (cause) {\n if (options.signal?.aborted) throw new FsError(\"ECANCELED\", { syscall: \"writeStream\", path, cause });\n if (timeout.aborted) throw new FsError(\"ETIMEDOUT\", { syscall: \"writeStream\", path, cause });\n if (isFsError(uploadError)) throw uploadError;\n if (isFsError(cause)) throw cause;\n throw new FsError(\"EIO\", { syscall: \"writeStream\", path, cause });\n }\n } finally {\n controller.abort();\n signalScope.dispose();\n if (body && !body.locked) void body.cancel().catch(() => {});\n void chunks.return(undefined).catch(() => {});\n }\n } finally {\n deadline.dispose();\n }\n }\n\n async appendFile(path: string, data: Uint8Array, options: AppendFileOptions = {}): Promise<void> {\n await this.writeFile(path, data, { ...options, flag: \"a\" });\n }\n\n async mkdir(path: string, options: MkdirOptions = {}): Promise<void> {\n const normalized = normalize(path);\n if (options.mode !== undefined) this.unsupported(\"mkdir mode\", path);\n if (!options.recursive) {\n if (normalized === \"/\") fail(\"EEXIST\", \"mkdir\", path);\n return this.mutation(\"MKCOL\", normalized, options, {}, true);\n }\n let current = \"\";\n for (const segment of normalized.slice(1).split(\"/\").filter(Boolean)) {\n current += `/${segment}`;\n const existing = await this.maybeStat(`${current}/`, options);\n if (existing) {\n if (existing.type !== \"directory\") fail(\"ENOTDIR\", \"mkdir\", current);\n continue;\n }\n try { await this.mutation(\"MKCOL\", current, options, {}, true); }\n catch (error) {\n if (!isFsError(error, \"EEXIST\")) throw error;\n if ((await this.stat(`${current}/`, options)).type !== \"directory\") fail(\"ENOTDIR\", \"mkdir\", current);\n }\n }\n if (normalized === \"/\") await this.stat(normalized, options);\n }\n\n async rmdir(path: string, options: FsOptions = {}): Promise<void> {\n try {\n const normalized = normalize(path);\n if (options.signal?.aborted) fail(\"ECANCELED\", \"rmdir\", path);\n if (normalized === \"/\") fail(\"EBUSY\", \"rmdir\", path, \"cannot remove WebDAV root\");\n const stat = await this.stat(path, options);\n if (options.signal?.aborted) fail(\"ECANCELED\", \"rmdir\", path);\n if (stat.type !== \"directory\") fail(\"ENOTDIR\", \"rmdir\", path);\n if (this.atomicEmptyDirectory) {\n await this.atomicRmdir(normalized, path, options);\n return;\n }\n const entries = await this.readdir(path, options);\n if (options.signal?.aborted) fail(\"ECANCELED\", \"rmdir\", path);\n if (entries.length) fail(\"ENOTEMPTY\", \"rmdir\", path);\n this.unsupported(\"rmdir\", path);\n } catch (error) {\n if (isFsError(error) && (error.syscall !== \"rmdir\" || error.path !== path)) {\n throw new FsError(error.code, { syscall: \"rmdir\", path, cause: error });\n }\n throw error;\n }\n }\n\n private async atomicRmdir(normalized: string, path: string, options: FsOptions): Promise<void> {\n const deadline = createRequestTimeout(this.timeoutMs);\n const timeout = deadline.signal;\n try {\n const signalScope = options.signal ? composeAbortSignals([timeout, options.signal]) : undefined;\n const signal = signalScope?.signal ?? timeout;\n try {\n signal.throwIfAborted();\n const receipt = await new Promise<WebDavAtomicEmptyDirectoryResult>((resolve, reject) => {\n const abort = (): void => {\n signal.removeEventListener(\"abort\", abort);\n reject(signal.reason);\n };\n signal.addEventListener(\"abort\", abort, { once: true });\n try {\n Promise.resolve(this.atomicEmptyDirectory!.removeEmptyDirectory(Object.freeze({\n operation: \"atomic-empty-rmdir/v1\", namespaceUrl: this.base.href, path: normalized, signal,\n }))).then((result) => {\n signal.removeEventListener(\"abort\", abort);\n resolve(result);\n }, (error: unknown) => {\n signal.removeEventListener(\"abort\", abort);\n reject(error);\n });\n } catch (error) {\n signal.removeEventListener(\"abort\", abort);\n reject(error);\n }\n });\n signal.throwIfAborted();\n if (!receipt || receipt.operation !== \"atomic-empty-rmdir/v1\" || receipt.namespaceUrl !== this.base.href\n || receipt.path !== normalized || receipt.outcome !== \"removed\") {\n fail(\"EIO\", \"rmdir\", path, \"atomic empty-directory receipt mismatch; removal outcome is uncertain\");\n }\n } catch (cause) {\n if (options.signal?.aborted) throw new FsError(\"ECANCELED\", { syscall: \"rmdir\", path, cause });\n if (timeout.aborted) throw new FsError(\"ETIMEDOUT\", { syscall: \"rmdir\", path, cause });\n if (isFsError(cause)) throw cause;\n const code = cause && typeof cause === \"object\" && \"code\" in cause && isErrnoCode(cause.code) ? cause.code : \"EIO\";\n throw new FsError(code, { syscall: \"rmdir\", path, cause });\n } finally {\n signalScope?.dispose();\n }\n } finally {\n deadline.dispose();\n }\n }\n\n async rm(path: string, options: RemoveOptions = {}): Promise<void> {\n const normalized = normalize(path);\n if (normalized === \"/\") fail(\"EBUSY\", \"rm\", path, \"cannot remove WebDAV root\");\n try {\n const stat = await this.stat(path, options);\n if (stat.type === \"directory\" && !options.recursive) this.unsupported(\"nonrecursive directory removal\", path);\n await this.mutation(\"DELETE\", normalized, options, {}, stat.type === \"directory\");\n } catch (error) {\n if (!(options.force && isFsError(error, \"ENOENT\"))) throw error;\n }\n }\n\n private async guardTransferIdentity(source: string, destination: string, options: FsOptions): Promise<void> {\n if (!this.configuredComparison && this.compareEntry === originalWebDavComparison) return;\n const comparison = await compareEntries(this, source, this, destination, options);\n if (source === destination) {\n if (comparison === \"distinct\") fail(\"EIO\", \"compareEntry\", source, \"comparison contradicts identical WebDAV paths\");\n return;\n }\n if (comparison === \"same\") fail(\"EINVAL\", \"compareEntry\", destination, \"source and destination refer to the same entry\");\n if (comparison === \"unknown\") fail(\"ENOTSUP\", \"compareEntry\", destination, \"configured authority cannot establish distinct entries\");\n }\n\n private async transfer(method: \"MOVE\" | \"COPY\", source: string, destination: string,\n options: CopyFileOptions): Promise<void> {\n const from = normalize(source);\n const to = normalize(destination);\n if (from === \"/\" || to === \"/\") fail(\"EBUSY\", method, source, \"cannot replace or transfer WebDAV root\");\n const stat = await this.stat(source, options);\n if (method === \"COPY\" && stat.type === \"directory\") fail(\"EISDIR\", \"copyFile\", source);\n if (requiresCollection(destination) && stat.type !== \"directory\") fail(\"ENOTDIR\", method, destination);\n if (from === to) {\n await this.guardTransferIdentity(from, to, options);\n if (method === \"MOVE\") return;\n fail(options.exclusive ? \"EEXIST\" : \"EINVAL\", \"copyFile\", source, \"source and destination are identical\");\n }\n if (stat.type === \"directory\" && to.startsWith(`${from}/`)) fail(\"EINVAL\", method, destination, \"cannot move directory into itself\");\n const existing = await this.maybeStat(destination, options);\n if (existing) await this.guardTransferIdentity(from, to, options);\n if (existing && options.exclusive) fail(\"EEXIST\", method, destination);\n const checkType = (target: FileStat): void => {\n if (target.type === \"directory\" && stat.type === \"file\") fail(\"EISDIR\", method, destination);\n if (target.type !== \"directory\" && stat.type === \"directory\") fail(\"ENOTDIR\", method, destination);\n };\n if (existing) checkType(existing);\n if (stat.type === \"directory\" && from.startsWith(`${to}/`)) fail(\"EINVAL\", method, destination, \"cannot replace an ancestor of the source\");\n const destinationUrl = this.url(to, stat.type === \"directory\");\n const headers: Record<string, string> = {\n Destination: destinationUrl, Overwrite: existing ? \"T\" : \"F\",\n Depth: method === \"COPY\" ? \"0\" : \"infinity\",\n };\n const sourceEtag = this.etags.get(stat);\n if (existing && sourceEtag && /^\"[\\x21\\x23-\\x7e\\x80-\\xff]*\"$/.test(sourceEtag)) headers[\"If-Match\"] = sourceEtag;\n const mutate = (): Promise<void> => this.mutation(method, from, options, { headers }, stat.type === \"directory\");\n if (!existing) return mutate();\n if (this.overwritePolicy === \"etag\" && existing.type === \"file\") {\n headers.If = `<${destinationUrl}> ([${strongEtag(this.etags.get(existing), destination)}])`;\n return mutate();\n }\n await this.withDestinationLock(to, existing, options, async (token) => {\n const locked = await this.stat(destination, options);\n checkType(locked);\n if (locked.type === \"directory\" && (await this.readdir(destination, options)).length) fail(\"ENOTEMPTY\", method, destination);\n headers.If = `<${destinationUrl}> (${token})`;\n await mutate();\n });\n }\n\n private async withDestinationLock(path: string, stat: FileStat, options: FsOptions,\n operation: (token: string) => Promise<void>): Promise<void> {\n let token: string | undefined;\n const collection = stat.type === \"directory\";\n const validator = this.etags.get(stat);\n const unlock = async (value: string): Promise<void> => {\n await this.request(\"UNLOCK\", path, {}, { headers: { \"Lock-Token\": value } }, async (response) => {\n if (response.status !== 204) this.httpError(response.status, \"UNLOCK\", path);\n }, collection).catch(() => {});\n };\n try {\n await this.request(\"LOCK\", path, options, {\n headers: { \"Content-Type\": \"application/xml; charset=utf-8\", Depth: \"infinity\", Timeout: \"Second-60\",\n \"If-Match\": validator && /^\"[\\x21\\x23-\\x7e\\x80-\\xff]*\"$/.test(validator) ? validator : \"*\" },\n body: lockBody,\n }, async (response, signal) => {\n if (response.status === 207) return this.lockFailure(response, signal, path);\n if (response.status !== 200) this.httpError(response.status, \"LOCK\", path);\n const root = await this.xml(response, signal);\n const discovery = davChild(root, \"lockdiscovery\");\n const active = discovery && davChild(discovery, \"activelock\");\n const scope = active && davChild(active, \"lockscope\");\n const type = active && davChild(active, \"locktype\");\n const depth = active && davChild(active, \"depth\");\n const lockToken = active && davChild(active, \"locktoken\");\n const href = lockToken && davChild(lockToken, \"href\");\n const lockRoot = active && davChild(active, \"lockroot\");\n const rootHref = lockRoot && davChild(lockRoot, \"href\");\n const timeout = active && davChild(active, \"timeout\");\n if (root.namespace !== \"DAV:\" || root.localName !== \"prop\" || !scope || !davChild(scope, \"exclusive\")\n || davChild(scope, \"shared\")\n || !type || !davChild(type, \"write\") || !depth || scalar(depth) !== \"infinity\"\n || !href || `<${scalar(href)}>` !== token\n || (lockRoot !== undefined && (!rootHref || this.hrefPath(scalar(rootHref)) !== path))\n || !timeout || !/^Second-[1-9]\\d*$/i.test(scalar(timeout)) || Number(scalar(timeout).slice(7)) > 4_294_967_295) {\n fail(\"ENOTSUP\", \"LOCK\", path, \"server did not grant a finite exclusive depth-infinity write lock\");\n }\n }, collection, (response, late) => {\n if (response.status !== 200) return;\n const header = response.headers.get(\"Lock-Token\");\n if (!header || !/^<[a-z][a-z0-9+.-]*:[^<>\\s\\x00-\\x20\\x7f]+>$/i.test(header)) throw new Error(\"invalid LOCK token\");\n if (late) void unlock(header);\n else token = header;\n });\n await operation(token!);\n } finally {\n if (token) await unlock(token);\n }\n }\n\n async rename(source: string, destination: string, options: RenameOptions = {}): Promise<void> {\n if (options.noReplace) {\n options.signal?.throwIfAborted();\n fail(\"ENOTSUP\", \"rename\", source, \"atomic no-replace rename is unsupported\");\n }\n await this.transfer(\"MOVE\", source, destination, options);\n }\n\n async copyFile(source: string, destination: string, options: CopyFileOptions = {}): Promise<void> {\n await this.transfer(\"COPY\", source, destination, options);\n }\n\n async realpath(path: string, options: FsOptions = {}): Promise<string> {\n const normalized = normalize(path);\n await this.stat(path, options);\n return normalized;\n }\n\n async access(path: string, mode = 0, options: FsOptions = {}): Promise<void> {\n if (!Number.isInteger(mode) || mode < 0 || mode > 7) fail(\"EINVAL\", \"access\", path);\n if (options.signal?.aborted) fail(\"ECANCELED\", \"access\", path);\n if (mode & 2) this.unsupported(\"access write/execute permission checks\", path);\n if (mode & 1) validateDirectoryWalkPath(path);\n // Non-execute probes do not inherit stat's raw-path limits.\n const stat = await (mode & 1 ? this.stat(path, options) : this.statWithAncestors(path, options));\n if (options.signal?.aborted) fail(\"ECANCELED\", \"access\", path);\n if ((mode & 1) && stat.type !== \"directory\") this.unsupported(\"access execute permission checks\", path);\n if (mode & 4) {\n if (stat.type === \"directory\") await this.readdir(path, options);\n else await this.request(\"GET\", normalize(path), options, { headers: { \"Accept-Encoding\": \"identity\" } }, async (response) => {\n if (response.status !== 200) this.httpError(response.status, \"GET\", path);\n });\n }\n if (options.signal?.aborted) fail(\"ECANCELED\", \"access\", path);\n }\n\n async readlink(path: string, _options: FsOptions = {}): Promise<string> { return this.unsupported(\"readlink\", path); }\n async symlink(_target: string, path: string, _options: FsOptions = {}): Promise<void> { this.unsupported(\"symlink\", path); }\n async link(_source: string, path: string, _options: FsOptions = {}): Promise<void> { this.unsupported(\"link\", path); }\n async chmod(path: string, _mode: number, _options: FsOptions = {}): Promise<void> { this.unsupported(\"chmod\", path); }\n async utimes(path: string, atimeMs: number, mtimeMs: number, options: FsOptions = {}): Promise<void> {\n const normalized = normalize(path);\n if (![atimeMs, mtimeMs].every(value => Number.isFinite(value) && Math.abs(value) <= 8.64e15)) fail(\"EINVAL\", \"utimes\", path);\n const stat = await this.stat(path, options);\n const etag = strongEtag(this.etags.get(stat), path);\n const metadata = JSON.stringify({ version: 1, etag, type: stat.type, atimeMs, mtimeMs })\n .replaceAll(\"&\", \"&\").replaceAll(\"<\", \"<\").replaceAll(\">\", \">\");\n await this.request(\"PROPPATCH\", normalized, options, {\n headers: { \"Content-Type\": \"application/xml; charset=utf-8\", \"If-Match\": etag },\n body: `<d:propertyupdate xmlns:d=\"DAV:\" xmlns:v=\"${timestampNamespace}\"><d:set><d:prop>`\n + `<v:timestamps>${metadata}</v:timestamps></d:prop></d:set></d:propertyupdate>`,\n }, async (response, signal) => {\n if (response.status !== 207) this.httpError(response.status, \"PROPPATCH\", path);\n const entries = await this.multistatus(response, signal);\n if (entries.length !== 1) throw new Error(\"PROPPATCH must report the requested resource\");\n const entry = entries[0]!;\n const href = davChild(entry, \"href\");\n if (!href || this.hrefPath(scalar(href)) !== normalized) fail(\"EACCES\", \"PROPPATCH\", path, \"unexpected response resource\");\n const status = davChild(entry, \"status\");\n if (status) this.httpError(statusCode(status), \"PROPPATCH\", path);\n const propstats = davChildren(entry, \"propstat\");\n if (propstats.length !== 1) throw new Error(\"PROPPATCH must report the requested property\");\n const prop = davChild(propstats[0]!, \"prop\");\n const result = davChild(propstats[0]!, \"status\");\n const property = prop?.children[0];\n if (!result || prop?.children.length !== 1 || property?.namespace !== timestampNamespace\n || property.localName !== \"timestamps\") throw new Error(\"invalid PROPPATCH property result\");\n const code = statusCode(result);\n if (code !== 200) this.httpError(code, \"PROPPATCH\", path);\n }, stat.type === \"directory\");\n const updated = await this.stat(path, options);\n if (updated.atimeMs !== atimeMs || updated.mtimeMs !== mtimeMs) {\n fail(\"EAGAIN\", \"utimes\", path, \"server did not retain requested timestamps for the current representation\");\n }\n }\n async truncate(path: string, _length?: number, _options: FsOptions = {}): Promise<void> { this.unsupported(\"truncate\", path); }\n}\n\nconst originalWebDavComparison = WebDavFileSystem.prototype.compareEntry;\n", "import type { FsBridgeDirent, FsBridgeStats } from \"./types.js\";\nimport type { FileStat, FileType } from \"../contracts/filesystem.js\";\n\nfunction predicates(type: FileType) {\n return {\n isFile: () => type === \"file\",\n isDirectory: () => type === \"directory\",\n isSymbolicLink: () => type === \"symlink\",\n isBlockDevice: () => false,\n isCharacterDevice: () => type === \"character\",\n isFIFO: () => false,\n isSocket: () => false,\n };\n}\n\nexport function bridgeStats(stat: FileStat): FsBridgeStats {\n return {\n dev: stat.dev ?? 0,\n ino: stat.ino ?? 0,\n mode: (stat.mode & 0o7777) | (stat.type === \"directory\" ? 0o040000 : stat.type === \"symlink\" ? 0o120000 : stat.type === \"character\" ? 0o020000 : 0o100000),\n nlink: stat.nlink ?? 1,\n uid: stat.uid ?? 0,\n gid: stat.gid ?? 0,\n rdev: 0,\n size: stat.size,\n blksize: stat.ioBlockSize ?? stat.preferredIoBlockSize ?? 4096,\n blocks: Math.ceil(stat.size / 512),\n atimeMs: stat.atimeMs,\n mtimeMs: stat.mtimeMs,\n ctimeMs: stat.ctimeMs,\n birthtimeMs: stat.birthtimeMs ?? stat.ctimeMs,\n atime: new Date(stat.atimeMs),\n mtime: new Date(stat.mtimeMs),\n ctime: new Date(stat.ctimeMs),\n birthtime: new Date(stat.birthtimeMs ?? stat.ctimeMs),\n ...predicates(stat.type),\n };\n}\n\nexport function bridgeDirent<Name extends string | Uint8Array>(\n name: Name,\n parentPath: string,\n type: FileType,\n): FsBridgeDirent<Name> {\n return { name, parentPath, path: parentPath, ...predicates(type) };\n}\n", "export function record(value: unknown, name: string): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${name} must be a plain object`);\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(`${name} must be a plain object`);\n }\n const result: Record<string, unknown> = {};\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (typeof key !== \"string\" || descriptor === undefined || !(\"value\" in descriptor)) {\n throw new TypeError(`${name} must contain only string-keyed data properties`);\n }\n Object.defineProperty(result, key, {\n value: descriptor.value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return result;\n}\n\nexport function onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n for (const key of Object.keys(value)) {\n if (!allowed.includes(key)) throw new TypeError(`Unsupported option: ${key}`);\n }\n}\n\nexport function booleanValue(value: unknown, fallback = false): boolean {\n if (value === undefined) return fallback;\n if (typeof value !== \"boolean\") throw new TypeError(\"Expected a boolean option\");\n return value;\n}\n\nexport function abortError(): Error {\n return Object.assign(new Error(\"The operation was aborted\"), {\n name: \"AbortError\",\n code: \"ABORT_ERR\",\n });\n}\n\nexport function checkSignal(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortError();\n}\n\nexport async function withSignal<Value>(\n signal: AbortSignal | undefined,\n operation: () => Promise<Value>,\n): Promise<Value> {\n checkSignal(signal);\n if (signal === undefined) return operation();\n let onAbort: () => void = () => undefined;\n const cancelled = new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n try {\n return await Promise.race([Promise.resolve().then(() => {\n checkSignal(signal);\n return operation();\n }), cancelled]);\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n", "import { FsError, isFsError } from \"../contracts/errors.js\";\nimport type { FileSystem, FsOptions } from \"../contracts/filesystem.js\";\nimport { dirname } from \"../contracts/virtual-path.js\";\nimport { checkSignal } from \"./values.js\";\n\nfunction denied(path: string): never {\n throw new FsError(\"EACCES\", { syscall: \"resolve\", path, message: \"path escapes the bridge cwd\" });\n}\n\nfunction relativeComponents(root: string, path: string): string[] {\n if (typeof path !== \"string\" || !path.startsWith(\"/\") || path.includes(\"\\0\")) denied(path);\n const boundary = root.split(\"/\").filter(Boolean);\n const components = path.split(\"/\").filter(Boolean);\n let index = 0;\n for (const component of boundary) {\n while (components[index] === \".\") index++;\n if (components[index] !== component) denied(path);\n index++;\n }\n const relative = components.slice(index);\n let depth = 0;\n for (const component of relative) {\n if (component === \".\") continue;\n if (component === \"..\") {\n if (depth === 0) denied(path);\n depth--;\n } else depth++;\n }\n if (path.endsWith(\"/\")) relative.push(\".\");\n return relative;\n}\n\nexport function assertBridgePath(root: string, path: string): void {\n if (root !== \"/\") relativeComponents(root, path);\n}\n\nasync function assertCanonicalPath(\n fs: FileSystem,\n root: string,\n path: string,\n options: FsOptions\n): Promise<void> {\n checkSignal(options.signal);\n const canonical = await fs.realpath(path, options);\n checkSignal(options.signal);\n assertBridgePath(root, canonical);\n if (canonical !== path) denied(path);\n}\n\nasync function assertCanonicalOperand(\n fs: FileSystem,\n root: string,\n path: string,\n expected: string,\n options: FsOptions\n): Promise<void> {\n let operand = path;\n let target = expected;\n while (true) {\n checkSignal(options.signal);\n try {\n const canonical = await fs.realpath(operand, options);\n checkSignal(options.signal);\n assertBridgePath(root, canonical);\n if (canonical !== target) denied(path);\n return;\n } catch (error) {\n checkSignal(options.signal);\n if (!isFsError(error) || error.code !== \"ENOENT\") throw error;\n let missing = false;\n try {\n await fs.lstat(operand, options);\n } catch (inspectionError) {\n checkSignal(options.signal);\n if (!isFsError(inspectionError) || inspectionError.code !== \"ENOENT\") throw inspectionError;\n missing = true;\n }\n checkSignal(options.signal);\n if (!missing || operand === root) denied(path);\n operand = dirname(operand);\n target = dirname(target);\n assertBridgePath(root, operand);\n assertBridgePath(root, target);\n }\n }\n}\n\nexport async function checkedBridgePath(\n fs: FileSystem,\n root: string,\n path: string,\n options: FsOptions,\n followFinal: boolean\n): Promise<string> {\n if (root === \"/\") return path;\n let pending = relativeComponents(root, path);\n let current = \"\";\n for (const component of root.split(\"/\").filter(Boolean)) {\n current += `/${component}`;\n checkSignal(options.signal);\n try {\n const stat = await fs.lstat(current, options);\n checkSignal(options.signal);\n if (stat.type === \"symlink\") denied(current);\n if (stat.type !== \"directory\")\n throw new FsError(\"ENOTDIR\", { syscall: \"resolve\", path: current });\n } catch (error) {\n checkSignal(options.signal);\n if (!isFsError(error) || error.code !== \"ENOENT\") throw error;\n if (current !== root) denied(path);\n if (pending.includes(\"..\")) throw error;\n const parent = dirname(root);\n await assertCanonicalPath(fs, parent, parent, options);\n return path;\n }\n }\n await assertCanonicalPath(fs, root, root, options);\n let links = 0;\n let finalLink = false;\n let index = 0;\n while (index < pending.length) {\n const component = pending[index++]!;\n checkSignal(options.signal);\n if (component === \".\") continue;\n if (component === \"..\") {\n if (current === root) denied(path);\n current = dirname(current);\n continue;\n }\n const candidate = `${current}/${component}`;\n let stat;\n try {\n stat = await fs.lstat(candidate, options);\n } catch (error) {\n checkSignal(options.signal);\n if (!isFsError(error) || error.code !== \"ENOENT\") throw error;\n if (pending.slice(index).includes(\"..\")) throw error;\n await assertCanonicalPath(fs, root, current, options);\n const expected = [candidate, ...pending.slice(index)].join(\"/\");\n await assertCanonicalOperand(fs, root, path, expected, options);\n return path;\n }\n checkSignal(options.signal);\n if (stat.type === \"symlink\" && (followFinal || index < pending.length)) {\n if (++links > 40) throw new FsError(\"ELOOP\", { syscall: \"resolve\", path });\n if (typeof fs.readlink !== \"function\")\n throw new FsError(\"ENOTSUP\", { syscall: \"readlink\", path: candidate });\n const target = await fs.readlink(candidate, options);\n checkSignal(options.signal);\n if (typeof target !== \"string\" || target.length === 0 || target.includes(\"\\0\"))\n denied(candidate);\n const absolute = target.startsWith(\"/\") ? target : `${current}/${target}`;\n pending = [...relativeComponents(root, absolute), ...pending.slice(index)];\n index = 0;\n current = root;\n continue;\n }\n if (index < pending.length && stat.type !== \"directory\") {\n throw new FsError(\"ENOTDIR\", { syscall: \"resolve\", path: candidate });\n }\n current = candidate;\n finalLink = stat.type === \"symlink\";\n }\n await assertCanonicalPath(fs, root, finalLink ? dirname(current) : current, options);\n await assertCanonicalOperand(\n fs,\n root,\n finalLink ? dirname(path) : path,\n finalLink ? dirname(current) : current,\n options\n );\n return path;\n}\n", "import type { FileSystem, FileType, FsOptions } from \"../contracts/filesystem.js\";\nimport { composeAbortSignals } from \"../contracts/abort.js\";\nimport { bridgeDirent, bridgeStats } from \"./stats.js\";\nimport { booleanValue, checkSignal, onlyKeys, record, withSignal } from \"./values.js\";\nimport { assertBridgePath, checkedBridgePath } from \"./confinement.js\";\nimport type {\n BridgePrimitives, BufferEncodingOption, FsBridgeCodec, FsBridgeDirent, FsBridgeEncoding,\n FsBridgeFileSystem, FsBridgeStats, MakeDirectoryOptions, Mode, ObjectEncodingOptions, StatOptions\n} from \"./types.js\";\n\ntype Encoding = FsBridgeEncoding | \"buffer\";\ntype ReadOptions = ObjectEncodingOptions & { flag?: string | number | undefined; signal?: AbortSignal | undefined };\ntype DirectoryOptions = { encoding?: Encoding | null | undefined; recursive?: boolean | undefined; withFileTypes?: boolean | undefined };\n\nfunction fsError(code: string, syscall: string, path?: string): Error {\n return Object.assign(new Error(`${code}: ${syscall}${path === undefined ? \"\" : ` '${path}'`}`), {\n code,\n syscall,\n ...(path === undefined ? {} : { path }),\n });\n}\n\nfunction unsupported(operation: string): never {\n throw fsError(\"ENOTSUP\", operation);\n}\n\nfunction hasCode(error: unknown, code: string): boolean {\n return error instanceof Error && \"code\" in error && error.code === code;\n}\n\nfunction childPath(parent: string, name: string): string {\n return `${parent.replace(/\\/$/u, \"\")}/${name}`;\n}\n\nfunction optionsRecord(value: unknown, allowed: readonly string[]): Record<string, unknown> {\n const options = value == null ? {} : typeof value === \"string\" ? { encoding: value } : record(value, \"options\");\n onlyKeys(options, allowed);\n return options;\n}\n\nfunction modeValue(value: unknown, fallback: number): number {\n if (value === undefined) return fallback;\n const parsed = typeof value === \"string\" && /^[0-7]+$/u.test(value) ? Number.parseInt(value, 8) : value;\n if (typeof parsed !== \"number\" || !Number.isInteger(parsed) || parsed < 0 || parsed > 0o7777) {\n throw new TypeError(\"Invalid file mode\");\n }\n return parsed;\n}\n\nfunction timeValue(value: unknown): number {\n const number = value instanceof Date ? value.getTime() : Number(value) * 1000;\n if ((typeof value !== \"string\" && typeof value !== \"number\" && !(value instanceof Date)) || !Number.isFinite(number)) {\n throw new TypeError(\"Invalid timestamp\");\n }\n return number;\n}\n\nexport class FileSystemBridge<Binary extends Uint8Array> {\n readonly #fs: FsBridgeFileSystem;\n readonly #cwd: string;\n readonly #signal: AbortSignal | undefined;\n\n readonly #primitives: BridgePrimitives<Binary>;\n readonly #codec: FsBridgeCodec;\n\n constructor(fs: FileSystem, options: { readonly cwd?: string; readonly signal?: AbortSignal }, primitives: BridgePrimitives<Binary>) {\n if (fs === undefined) throw new TypeError(\"An explicit filesystem is required\");\n const cwd = options.cwd ?? \"/\";\n if (!primitives.paths.isAbsolute(cwd) || cwd.includes(\"\\0\")) throw new TypeError(\"cwd must be an absolute virtual path\");\n const codec = primitives.codec;\n if (codec === undefined || codec === null || typeof codec.isEncoding !== \"function\" || typeof codec.encode !== \"function\" || typeof codec.decode !== \"function\") {\n throw new TypeError(\"An explicit filesystem codec is required\");\n }\n this.#primitives = primitives;\n this.#codec = Object.freeze({\n isEncoding: codec.isEncoding.bind(codec),\n encode: codec.encode.bind(codec),\n decode: codec.decode.bind(codec)\n });\n this.#fs = fs;\n this.#cwd = primitives.paths.resolve(\"/\", cwd);\n this.#signal = options.signal;\n }\n\n #encoding(value: unknown, fallback: Encoding, names = false): string {\n const selected = value == null ? fallback : value;\n if (typeof selected !== \"string\" || (selected !== \"buffer\" && !this.#codec.isEncoding(selected)) || (names && !this.#codec.isEncoding(\"utf8\"))) {\n throw new TypeError(\"Invalid encoding\");\n }\n return selected;\n }\n\n #textBytes(value: string): Binary {\n return this.#primitives.copyBytes(this.#codec.encode(value, \"utf8\"));\n }\n\n #path(value: unknown): string {\n const path = this.#primitives.pathValue === undefined ? value : this.#primitives.pathValue(value);\n if (typeof path !== \"string\" || path.includes(\"\\0\")) throw new TypeError(\"Expected a path without NUL bytes; file handles are unsupported\");\n if (path.length === 0) throw fsError(\"ENOENT\", \"path\", path);\n checkSignal(this.#signal);\n const absolute = this.#primitives.paths.isAbsolute(path) ? path : childPath(this.#cwd, path);\n assertBridgePath(this.#cwd, absolute);\n return absolute;\n }\n\n async #call<Value>(\n paths: readonly unknown[],\n operation: (options: FsOptions, resolved: readonly string[]) => Promise<Value>,\n signal?: unknown,\n noFollow: readonly number[] = []\n ): Promise<Value> {\n if (signal !== undefined && !(signal instanceof AbortSignal)) throw new TypeError(\"Invalid AbortSignal\");\n const signalScope = signal !== undefined && this.#signal !== undefined && signal !== this.#signal\n ? composeAbortSignals([signal, this.#signal]) : undefined;\n const combined = signalScope?.signal ?? signal ?? this.#signal;\n try {\n checkSignal(combined);\n const options = combined === undefined ? {} : { signal: combined };\n return await withSignal(combined, async () => {\n const absolute = paths.map((path) => this.#path(path));\n const resolved = [...absolute];\n if (this.#cwd !== \"/\") {\n for (let index = 0; index < absolute.length; index++) {\n resolved[index] = await checkedBridgePath(this.#fs, this.#cwd, absolute[index]!, options, !noFollow.includes(index));\n }\n }\n checkSignal(combined);\n return operation(options, resolved);\n });\n } finally {\n signalScope?.dispose();\n }\n }\n\n readFile(path: unknown, options?: { encoding?: null | undefined; flag?: string | number | undefined; signal?: AbortSignal | undefined } | null): Promise<Binary>;\n readFile(path: unknown, options: FsBridgeEncoding | (ReadOptions & { encoding: FsBridgeEncoding })): Promise<string>;\n readFile(path: unknown, options?: ReadOptions | FsBridgeEncoding | null): Promise<string | Binary>;\n async readFile(path: unknown, value?: unknown): Promise<string | Binary> {\n const options = optionsRecord(value, [\"encoding\", \"flag\", \"signal\"]);\n if (options.flag !== undefined && options.flag !== \"r\") unsupported(\"readFile flag\");\n if (options.encoding === \"buffer\") throw new TypeError(\"Invalid read encoding\");\n const codec = this.#encoding(options.encoding, \"buffer\");\n const bytes = await this.#call([path], (signal, resolved) => this.#fs.readFile(resolved[0]!, signal), options.signal);\n const buffer = this.#primitives.copyBytes(bytes);\n return codec === \"buffer\" ? buffer : this.#codec.decode(buffer, codec);\n }\n\n async #write(path: unknown, data: unknown, value: unknown, fallback: \"w\" | \"a\"): Promise<void> {\n const options = optionsRecord(value, [\"encoding\", \"flag\", \"mode\", \"flush\", \"signal\"]);\n if (booleanValue(options.flush)) unsupported(\"writeFile flush\");\n const codec = this.#encoding(options.encoding, \"utf8\");\n if (codec === \"buffer\") throw new TypeError(\"Invalid write encoding\");\n const flag = options.flag ?? fallback;\n if (flag !== \"w\" && flag !== \"wx\" && flag !== \"a\" && flag !== \"ax\") unsupported(\"writeFile flag\");\n const mode = modeValue(options.mode, 0o666);\n let bytes: Uint8Array;\n if (typeof data === \"string\") bytes = this.#primitives.copyBytes(this.#codec.encode(data, codec));\n else if (ArrayBuffer.isView(data)) bytes = this.#primitives.copyBytes(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n else throw new TypeError(\"writeFile accepts a string or ArrayBuffer view; streams and file handles are unsupported\");\n await this.#call([path], (signal, resolved) => this.#fs.writeFile(resolved[0]!, bytes, { ...signal, flag, mode }), options.signal);\n }\n\n async writeFile(path: unknown, data: unknown, options?: unknown): Promise<void> {\n await this.#write(path, data, options, \"w\");\n }\n\n async appendFile(path: unknown, data: unknown, options?: unknown): Promise<void> {\n await this.#write(path, data, options, \"a\");\n }\n\n stat(path: unknown, options?: StatOptions & { bigint?: false | undefined }): Promise<FsBridgeStats>;\n stat(path: unknown, options: StatOptions & { bigint: true }): Promise<never>;\n stat(path: unknown, options?: StatOptions): Promise<FsBridgeStats>;\n async stat(path: unknown, value?: unknown): Promise<FsBridgeStats> {\n const options = optionsRecord(value, [\"bigint\"]);\n if (booleanValue(options.bigint)) unsupported(\"stat bigint\");\n return bridgeStats(await this.#call([path], (signal, resolved) => this.#fs.stat(resolved[0]!, signal)));\n }\n\n lstat(path: unknown, options?: StatOptions & { bigint?: false | undefined }): Promise<FsBridgeStats>;\n lstat(path: unknown, options: StatOptions & { bigint: true }): Promise<never>;\n lstat(path: unknown, options?: StatOptions): Promise<FsBridgeStats>;\n async lstat(path: unknown, value?: unknown): Promise<FsBridgeStats> {\n const options = optionsRecord(value, [\"bigint\"]);\n if (booleanValue(options.bigint)) unsupported(\"lstat bigint\");\n return bridgeStats(await this.#call([path], (signal, resolved) => this.#fs.lstat(resolved[0]!, signal), undefined, [0]));\n }\n\n readdir(path: unknown, options?: FsBridgeEncoding | (ObjectEncodingOptions & { withFileTypes?: false | undefined; recursive?: boolean | undefined }) | null): Promise<string[]>;\n readdir(path: unknown, options: \"buffer\" | (DirectoryOptions & { encoding: \"buffer\"; withFileTypes?: false | undefined })): Promise<Binary[]>;\n readdir(path: unknown, options: ObjectEncodingOptions & { withFileTypes: true; recursive?: boolean | undefined }): Promise<FsBridgeDirent[]>;\n readdir(path: unknown, options: DirectoryOptions & { encoding: \"buffer\"; withFileTypes: true }): Promise<FsBridgeDirent<Binary>[]>;\n async readdir(path: unknown, value?: unknown): Promise<string[] | Binary[] | FsBridgeDirent[] | FsBridgeDirent<Binary>[]> {\n const options = optionsRecord(value, [\"encoding\", \"withFileTypes\", \"recursive\"]);\n const codec = this.#encoding(options.encoding, \"utf8\", true);\n const withFileTypes = booleanValue(options.withFileTypes);\n const recursive = booleanValue(options.recursive);\n const root = this.#path(path);\n const entries: { name: string; parentPath: string; relative: string; type: FileType }[] = [];\n const pending = [root];\n while (pending.length > 0) {\n const directory = pending.shift();\n if (directory === undefined) break;\n for (const entry of await this.#call([directory], (signal, resolved) => this.#fs.readdir(resolved[0]!, signal))) {\n if (entry.name === \"\" || entry.name === \".\" || entry.name === \"..\" || entry.name.includes(\"/\") || entry.name.includes(\"\\0\")) {\n throw new TypeError(\"Invalid directory entry from filesystem\");\n }\n const fullPath = childPath(directory, entry.name);\n entries.push({ ...entry, parentPath: directory, relative: this.#primitives.paths.relative(root, fullPath) });\n if (recursive && entry.type === \"directory\") pending.push(fullPath);\n }\n }\n if (withFileTypes) {\n return codec === \"buffer\"\n ? entries.map((entry) => bridgeDirent(this.#textBytes(entry.name), entry.parentPath, entry.type))\n : entries.map((entry) => bridgeDirent(this.#codec.decode(this.#textBytes(entry.name), codec), entry.parentPath, entry.type));\n }\n return codec === \"buffer\"\n ? entries.map((entry) => this.#textBytes(entry.relative))\n : entries.map((entry) => this.#codec.decode(this.#textBytes(entry.relative), codec));\n }\n\n mkdir(path: unknown, options: MakeDirectoryOptions & { recursive: true }): Promise<string | undefined>;\n mkdir(path: unknown, options?: Mode | (MakeDirectoryOptions & { recursive?: false | undefined }) | null): Promise<void>;\n mkdir(path: unknown, options?: Mode | MakeDirectoryOptions | null): Promise<string | undefined>;\n async mkdir(path: unknown, value?: unknown): Promise<string | void> {\n const options = typeof value === \"number\" || typeof value === \"string\" ? { mode: value } : optionsRecord(value, [\"mode\", \"recursive\"]);\n const mode = modeValue(options.mode, 0o777);\n const recursive = booleanValue(options.recursive);\n const target = this.#path(path);\n let firstCreated: string | undefined;\n if (recursive) {\n let candidate = target;\n while (true) {\n try {\n await this.#call([candidate], (signal, resolved) => this.#fs.stat(resolved[0]!, signal));\n break;\n } catch (error) {\n if (!hasCode(error, \"ENOENT\")) throw error;\n firstCreated = candidate;\n if (candidate === this.#cwd) break;\n const parent = this.#primitives.paths.dirname(candidate);\n if (parent === candidate) break;\n candidate = parent;\n }\n }\n }\n await this.#call([target], (signal, resolved) => this.#fs.mkdir(resolved[0]!, { ...signal, mode, recursive }));\n return firstCreated;\n }\n\n async access(path: unknown, mode = 0): Promise<void> {\n if (!Number.isInteger(mode) || mode < 0 || mode > 7) throw new TypeError(\"Invalid access mode\");\n await this.#call([path], (signal, resolved) => this.#fs.access(resolved[0]!, mode, signal));\n }\n\n async rm(path: unknown, value?: unknown): Promise<void> {\n const options = optionsRecord(value, [\"force\", \"recursive\", \"maxRetries\", \"retryDelay\"]);\n if (options.maxRetries !== undefined && options.maxRetries !== 0) unsupported(\"rm retries\");\n if (options.retryDelay !== undefined) unsupported(\"rm retryDelay\");\n const recursive = booleanValue(options.recursive);\n const force = booleanValue(options.force);\n await this.#call([path], (signal, resolved) => this.#fs.rm(resolved[0]!, { ...signal, recursive, force }), undefined, [0]);\n }\n\n async rmdir(path: unknown, value?: unknown): Promise<void> {\n const options = optionsRecord(value, [\"recursive\", \"maxRetries\", \"retryDelay\"]);\n const stat = await this.lstat(path);\n if (!stat.isDirectory()) throw fsError(\"ENOTDIR\", \"rmdir\", this.#path(path));\n if (!booleanValue(options.recursive)) {\n if ((await this.readdir(path)).length > 0) throw fsError(\"ENOTEMPTY\", \"rmdir\", this.#path(path));\n if (options.maxRetries !== undefined && options.maxRetries !== 0) unsupported(\"rmdir retries\");\n if (options.retryDelay !== undefined) unsupported(\"rmdir retryDelay\");\n const method = this.#fs.rmdir;\n if (method === undefined) unsupported(\"atomic rmdir\");\n await this.#call([path], (signal, resolved) => method.call(this.#fs, resolved[0]!, signal), undefined, [0]);\n } else await this.rm(path, options);\n }\n\n async rename(source: unknown, destination: unknown): Promise<void> {\n await this.#call([source, destination], (signal, resolved) => this.#fs.rename(resolved[0]!, resolved[1]!, signal), undefined, [0, 1]);\n }\n\n async copyFile(source: unknown, destination: unknown, mode = 0): Promise<void> {\n if (mode !== 0 && mode !== 1) unsupported(\"copyFile mode\");\n await this.#call([source, destination], (signal, resolved) => this.#fs.copyFile(resolved[0]!, resolved[1]!, { ...signal, exclusive: mode === 1 }));\n }\n\n async cp(source: unknown, destination: unknown, value?: unknown): Promise<void> {\n const options = optionsRecord(value, [\"recursive\", \"force\", \"errorOnExist\", \"mode\", \"dereference\", \"preserveTimestamps\", \"verbatimSymlinks\"]);\n if (booleanValue(options.dereference) || booleanValue(options.preserveTimestamps) || booleanValue(options.verbatimSymlinks)) unsupported(\"cp options\");\n const recursive = booleanValue(options.recursive);\n const force = booleanValue(options.force, true);\n const errorOnExist = booleanValue(options.errorOnExist);\n if (options.mode !== undefined && options.mode !== 0 && options.mode !== 1) unsupported(\"cp mode\");\n const from = this.#path(source);\n const to = this.#path(destination);\n const canonicalFrom = await this.realpath(from);\n let ancestor = to === this.#cwd ? to : this.#primitives.paths.dirname(to);\n let canonicalAncestor: string;\n while (true) {\n try {\n canonicalAncestor = await this.realpath(ancestor);\n break;\n } catch (error) {\n if (!hasCode(error, \"ENOENT\")) throw error;\n const parent = this.#primitives.paths.dirname(ancestor);\n if (parent === ancestor) throw error;\n ancestor = parent;\n }\n }\n const canonicalTo = this.#primitives.paths.resolve(canonicalAncestor, this.#primitives.paths.relative(ancestor, to));\n if (canonicalFrom === \"/\" || canonicalTo === canonicalFrom || canonicalTo.startsWith(`${canonicalFrom}/`)) throw fsError(\"EINVAL\", \"cp\", to);\n const copy = async (current: string, target: string): Promise<void> => {\n const sourceStat = await this.lstat(current);\n if (sourceStat.isSymbolicLink()) unsupported(\"cp symlink\");\n let destinationStat: FsBridgeStats | undefined;\n try {\n destinationStat = await this.lstat(target);\n } catch (error) {\n if (!hasCode(error, \"ENOENT\")) throw error;\n }\n if (destinationStat?.isSymbolicLink()) unsupported(\"cp destination symlink\");\n if (sourceStat.isDirectory()) {\n if (!recursive) throw fsError(\"EISDIR\", \"cp\", current);\n if (destinationStat !== undefined && !destinationStat.isDirectory()) throw fsError(\"ENOTDIR\", \"cp\", target);\n await this.mkdir(target, { recursive: true, mode: sourceStat.mode & 0o7777 });\n for (const entry of await this.readdir(current)) await copy(childPath(current, entry), childPath(target, entry));\n } else {\n if (destinationStat?.isDirectory()) throw fsError(\"EISDIR\", \"cp\", target);\n if (destinationStat !== undefined && !force) {\n if (errorOnExist) throw fsError(\"EEXIST\", \"cp\", target);\n return;\n }\n await this.mkdir(this.#primitives.paths.dirname(target), { recursive: true });\n await this.copyFile(current, target, options.mode === 1 || !force ? 1 : 0);\n }\n };\n await copy(from, to);\n }\n\n readlink(path: unknown, options?: ObjectEncodingOptions | FsBridgeEncoding | null): Promise<string>;\n readlink(path: unknown, options: BufferEncodingOption): Promise<Binary>;\n readlink(path: unknown, options?: ObjectEncodingOptions | BufferEncodingOption | string | null): Promise<string | Binary>;\n async readlink(path: unknown, value?: unknown): Promise<string | Binary> {\n const codec = this.#encoding(optionsRecord(value, [\"encoding\"]).encoding, \"utf8\", true);\n const method = this.#fs.readlink;\n if (method === undefined) unsupported(\"readlink\");\n const target = await this.#call([path], (signal, resolved) => method.call(this.#fs, resolved[0]!, signal), undefined, [0]);\n return codec === \"buffer\" ? this.#textBytes(target) : this.#codec.decode(this.#textBytes(target), codec);\n }\n\n realpath(path: unknown, options?: ObjectEncodingOptions | FsBridgeEncoding | null): Promise<string>;\n realpath(path: unknown, options: BufferEncodingOption): Promise<Binary>;\n realpath(path: unknown, options?: ObjectEncodingOptions | BufferEncodingOption | string | null): Promise<string | Binary>;\n async realpath(path: unknown, value?: unknown): Promise<string | Binary> {\n const codec = this.#encoding(optionsRecord(value, [\"encoding\"]).encoding, \"utf8\", true);\n const target = await this.#call([path], (signal, resolved) => this.#fs.realpath(resolved[0]!, signal));\n assertBridgePath(this.#cwd, target);\n return codec === \"buffer\" ? this.#textBytes(target) : this.#codec.decode(this.#textBytes(target), codec);\n }\n\n mkdtemp(prefix: string, options?: ObjectEncodingOptions | FsBridgeEncoding | null): Promise<string>;\n mkdtemp(prefix: string, options: BufferEncodingOption): Promise<Binary>;\n mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncodingOption | string | null): Promise<string | Binary>;\n async mkdtemp(prefix: string, value?: unknown): Promise<string | Binary> {\n if (typeof prefix !== \"string\" || prefix.includes(\"\\0\")) throw new TypeError(\"Invalid mkdtemp prefix\");\n const codec = this.#encoding(optionsRecord(value, [\"encoding\"]).encoding, \"utf8\", true);\n for (let attempt = 0; attempt < 10; attempt += 1) {\n const path = prefix + this.#primitives.randomSuffix();\n try {\n await this.mkdir(path, { mode: 0o700 });\n return codec === \"buffer\" ? this.#textBytes(path) : this.#codec.decode(this.#textBytes(path), codec);\n } catch (error) {\n if (!hasCode(error, \"EEXIST\")) throw error;\n }\n }\n throw fsError(\"EEXIST\", \"mkdtemp\", prefix);\n }\n\n async symlink(target: unknown, path: unknown, type?: unknown): Promise<void> {\n if (type !== undefined && type !== null && type !== \"file\" && type !== \"dir\") unsupported(\"symlink type\");\n const linkTarget = this.#primitives.pathValue === undefined ? target : this.#primitives.pathValue(target);\n if (typeof linkTarget !== \"string\" || linkTarget.includes(\"\\0\")) throw new TypeError(\"Invalid symlink target\");\n const destination = this.#path(path);\n const absoluteTarget = this.#path(this.#primitives.paths.isAbsolute(linkTarget)\n ? linkTarget : childPath(this.#primitives.paths.dirname(destination), linkTarget));\n if (this.#cwd !== \"/\" && this.#primitives.paths.isAbsolute(linkTarget)) {\n throw fsError(\"ENOTSUP\", \"symlink\", destination);\n }\n const method = this.#fs.symlink;\n if (method === undefined) unsupported(\"symlink\");\n await this.#call([destination, absoluteTarget], (signal, resolved) => method.call(this.#fs, linkTarget, resolved[0]!, signal), undefined, [0]);\n }\n\n async link(existing: unknown, path: unknown): Promise<void> {\n const method = this.#fs.link;\n if (method === undefined) unsupported(\"link\");\n await this.#call([existing, path], (signal, resolved) => method.call(this.#fs, resolved[0]!, resolved[1]!, signal), undefined, [1]);\n }\n\n async chmod(path: unknown, value: unknown): Promise<void> {\n const mode = modeValue(value, 0);\n const method = this.#fs.chmod;\n if (method === undefined) unsupported(\"chmod\");\n await this.#call([path], (signal, resolved) => method.call(this.#fs, resolved[0]!, mode, signal));\n }\n\n async utimes(path: unknown, atime: unknown, mtime: unknown): Promise<void> {\n const accessTime = timeValue(atime);\n const modificationTime = timeValue(mtime);\n const method = this.#fs.utimes;\n if (method === undefined) unsupported(\"utimes\");\n await this.#call([path], (signal, resolved) => method.call(this.#fs, resolved[0]!, accessTime, modificationTime, signal));\n }\n\n async truncate(path: unknown, length = 0): Promise<void> {\n if (!Number.isInteger(length)) throw new TypeError(\"Invalid truncate length\");\n const method = this.#fs.truncate;\n if (method === undefined) unsupported(\"truncate\");\n await this.#call([path], (signal, resolved) => method.call(this.#fs, resolved[0]!, Math.max(0, length), signal));\n }\n}\n", "import { platform } from \"#safe-fs-platform\";\nimport type { FileSystem } from \"../contracts/filesystem.js\";\nimport { dirname, relativePath, resolvePath } from \"../contracts/virtual-path.js\";\nimport { FileSystemBridge } from \"./filesystem.js\";\nimport type { FsBridgeOptions } from \"./types.js\";\n\nexport type {\n FsBridgeCodec, FsBridgeDirent, FsBridgeEncoding, FsBridgeFileSystem, FsBridgeOptions, FsBridgeStats\n} from \"./types.js\";\nexport type FsBridge = FileSystemBridge<Uint8Array<ArrayBuffer>>;\n\nexport function createFsBridge(fs: FileSystem, options: FsBridgeOptions): FsBridge {\n if (options === undefined || options === null) throw new TypeError(\"An explicit filesystem codec is required\");\n return new FileSystemBridge(fs, options, {\n codec: options.codec,\n copyBytes(bytes) { return new Uint8Array(bytes); },\n randomSuffix() { return platform.randomUUID().slice(0, 6); },\n paths: {\n isAbsolute(path) { return typeof path === \"string\" && path.startsWith(\"/\"); },\n dirname,\n relative: relativePath,\n resolve: resolvePath\n }\n });\n}\n", "import { FsError } from \"../contracts/errors.js\";\nimport type { PythonFsRequest } from \"./filesystem.js\";\n\nconst argumentKinds = {\n open: [\"string\", \"object\"], read: [\"number\", \"number\", \"position\"], write: [\"number\", \"bytes\", \"position\"],\n descriptorCapabilities: [\"number\"], fstat: [\"number\"], close: [\"number\"], position: [\"number\"], ftruncate: [\"number\", \"number\"], sync: [\"number\", \"boolean\"],\n stat: [\"string\"], lstat: [\"string\"], readdir: [\"string\"], realpath: [\"string\"], readlink: [\"string\"], rm: [\"string\"], rmdir: [\"string\"], rmtree: [\"string\"], rmtreeSupported: [\"string\"],\n rename: [\"string\", \"string\"], symlink: [\"string\", \"string\"], link: [\"string\", \"string\"], mkdir: [\"string\", \"optionalObject\"],\n chmod: [\"string\", \"number\"], truncate: [\"string\", \"number\"], access: [\"string\", \"number\"], utimes: [\"string\", \"number\", \"number\"],\n} as const;\n\nexport function parsePythonFsRequest(value: unknown, maxTransferBytes: number): PythonFsRequest {\n if (!value || typeof value !== \"object\" || Reflect.ownKeys(value).some(key => key !== \"op\" && key !== \"args\")) throw new FsError(\"EINVAL\");\n const op = Object.getOwnPropertyDescriptor(value, \"op\")?.value as unknown;\n const args = Object.getOwnPropertyDescriptor(value, \"args\")?.value as unknown;\n if (typeof op !== \"string\" || !Object.hasOwn(argumentKinds, op)) throw new FsError(\"ENOTSUP\");\n const kinds = argumentKinds[op as keyof typeof argumentKinds] as readonly string[];\n if (!Array.isArray(args) || args.length > kinds.length || args.length < kinds.length - (kinds.at(-1) === \"optionalObject\" ? 1 : 0)) throw new FsError(\"EINVAL\", { syscall: op });\n const selected: unknown[] = [];\n for (let index = 0; index < kinds.length; index++) {\n const kind = kinds[index];\n const descriptor = Object.getOwnPropertyDescriptor(args, String(index));\n if (descriptor && !Object.hasOwn(descriptor, \"value\")) throw new FsError(\"EINVAL\", { syscall: op });\n const argument: unknown = descriptor?.value;\n if (kind === \"bytes\") {\n if (!(argument instanceof Uint8Array) && !Array.isArray(argument)) throw new FsError(\"EINVAL\", { syscall: op });\n if (argument.length > maxTransferBytes) throw new FsError(\"EFBIG\", { syscall: op });\n const owned = new Uint8Array(argument.length);\n for (let byteIndex = 0; byteIndex < argument.length; byteIndex++) {\n const entry = Object.getOwnPropertyDescriptor(argument, String(byteIndex));\n const byte: unknown = entry?.value;\n if (!entry || !Object.hasOwn(entry, \"value\") || typeof byte !== \"number\" || !Number.isInteger(byte) || byte < 0 || byte > 255) throw new FsError(\"EINVAL\", { syscall: op });\n owned[byteIndex] = byte;\n }\n selected.push(owned);\n continue;\n }\n if (kind === \"position\" ? argument !== null && typeof argument !== \"number\"\n : kind === \"optionalObject\" ? argument !== undefined && (typeof argument !== \"object\" || argument === null || Array.isArray(argument))\n : kind === \"object\" ? typeof argument !== \"object\" || argument === null || Array.isArray(argument)\n : typeof argument !== kind) throw new FsError(\"EINVAL\", { syscall: op });\n if (argument !== null && typeof argument === \"object\") {\n const snapshot: Record<string, unknown> = {};\n for (const key of Reflect.ownKeys(argument)) {\n const field = Object.getOwnPropertyDescriptor(argument, key);\n if (typeof key !== \"string\" || !field || !Object.hasOwn(field, \"value\")) throw new FsError(\"EINVAL\", { syscall: op });\n Object.defineProperty(snapshot, key, { value: field.value, enumerable: true });\n }\n selected.push(snapshot);\n } else selected.push(argument);\n }\n return { op, args: selected } as unknown as PythonFsRequest;\n}\n", "import { parsePythonFsRequest } from \"./request.js\";\nimport { composeAbortSignals } from \"../contracts/abort.js\";\nimport { FsError } from \"../contracts/errors.js\";\nimport type { FileDescriptor, FileSystem, OpenFileOptions, MkdirOptions } from \"../contracts/filesystem.js\";\nimport { dirname, validatePath } from \"../contracts/virtual-path.js\";\n\nexport type PythonFsRequest =\n | { readonly op: \"open\"; readonly args: readonly [string, OpenFileOptions] }\n | { readonly op: \"read\"; readonly args: readonly [number, number, number | null] }\n | { readonly op: \"write\"; readonly args: readonly [number, Uint8Array, number | null] }\n | { readonly op: \"fstat\" | \"close\" | \"position\" | \"descriptorCapabilities\"; readonly args: readonly [number] }\n | { readonly op: \"ftruncate\"; readonly args: readonly [number, number] }\n | { readonly op: \"sync\"; readonly args: readonly [number, boolean] }\n | { readonly op: \"stat\" | \"lstat\" | \"readdir\" | \"realpath\" | \"readlink\" | \"rm\" | \"rmdir\" | \"rmtree\" | \"rmtreeSupported\"; readonly args: readonly [string] }\n | { readonly op: \"rename\" | \"symlink\" | \"link\"; readonly args: readonly [string, string] }\n | { readonly op: \"mkdir\"; readonly args: readonly [string, MkdirOptions?] }\n | { readonly op: \"chmod\" | \"truncate\" | \"access\"; readonly args: readonly [string, number] }\n | { readonly op: \"utimes\"; readonly args: readonly [string, number, number] };\n\nexport interface PythonFileSystemOptions {\n readonly cwd: string;\n readonly signal?: AbortSignal;\n readonly maxTransferBytes?: number;\n readonly maxOpenFiles?: number;\n readonly maxDirectoryEntries?: number;\n /** Caller-owned acquisition wrapper, e.g. shell descriptor quota enrollment. */\n readonly open?: (path: string, options: OpenFileOptions) => Promise<FileDescriptor>;\n}\n\n/** Async half of a worker RPC filesystem. Never run this on an Atomics.wait-blocked interpreter thread. */\nexport class PythonFileSystem {\n readonly #fs: FileSystem;\n readonly #cwd: string;\n readonly #transfer: number;\n readonly #limit: number;\n readonly #directoryLimit: number;\n readonly #open: PythonFileSystemOptions[\"open\"];\n readonly #abort = new AbortController();\n readonly #scope: ReturnType<typeof composeAbortSignals>;\n readonly #handles = new Map<number, FileDescriptor>();\n readonly #pending = new Set<Promise<unknown>>();\n #acquiring = 0;\n #next = 1;\n #closing: Promise<void> | undefined;\n\n constructor(fs: FileSystem, options: PythonFileSystemOptions) {\n this.#fs = fs;\n validatePath(options.cwd);\n if (!options.cwd.startsWith(\"/\")) throw new FsError(\"EINVAL\", { syscall: \"python filesystem\", path: options.cwd, message: \"cwd must be absolute\" });\n this.#cwd = options.cwd;\n this.#transfer = options.maxTransferBytes ?? 65536;\n this.#limit = options.maxOpenFiles ?? 256;\n this.#directoryLimit = options.maxDirectoryEntries ?? 65536;\n for (const limit of [this.#transfer, this.#limit, this.#directoryLimit]) if (!Number.isSafeInteger(limit) || limit < 1) throw new FsError(\"EINVAL\", { syscall: \"python filesystem\" });\n this.#open = options.open;\n this.#scope = composeAbortSignals([...(options.signal === undefined ? [] : [options.signal]), this.#abort.signal]);\n }\n\n dispatch(value: unknown): Promise<unknown> {\n if (this.#closing) return Promise.reject(new FsError(\"EBADF\"));\n let request: PythonFsRequest;\n try {\n this.#scope.signal.throwIfAborted();\n request = parsePythonFsRequest(value, this.#transfer);\n } catch (error) { return Promise.reject(error); }\n const operation = this.#execute(request);\n this.#pending.add(operation);\n void operation.then(() => this.#pending.delete(operation), () => this.#pending.delete(operation));\n return operation;\n }\n\n #path(path: string): string {\n validatePath(path);\n if (path.length === 0) throw new FsError(\"ENOENT\", { syscall: \"resolve\", path });\n return path.startsWith(\"/\") ? path : `${this.#cwd === \"/\" ? \"\" : this.#cwd}/${path}`;\n }\n\n #handle(id: number): FileDescriptor {\n const handle = this.#handles.get(id);\n if (!handle) throw new FsError(\"EBADF\");\n return handle;\n }\n\n #size(size: number): void {\n if (!Number.isSafeInteger(size) || size < 0) throw new FsError(\"EINVAL\");\n if (size > this.#transfer) throw new FsError(\"EFBIG\", { message: \"Python filesystem transfer exceeds configured limit\" });\n }\n\n async #execute(request: PythonFsRequest): Promise<unknown> {\n const signal = this.#scope.signal;\n signal.throwIfAborted();\n const options = { signal };\n const fs = this.#fs;\n switch (request.op) {\n case \"open\": {\n const [path, supplied] = request.args;\n if (this.#handles.size + this.#acquiring >= this.#limit || !Number.isSafeInteger(this.#next)) throw new FsError(\"EMFILE\", { syscall: \"open\" });\n if (!this.#open && !fs.open) throw new FsError(\"ENOTSUP\", { syscall: \"open\", path });\n this.#acquiring++;\n let handle: FileDescriptor | undefined;\n try {\n // A following capability query cannot preflight exclusive final-entry acquisition.\n // The canonical open remains authoritative for selected-path policy and atomic refusal.\n const capabilities = supplied.creation !== \"exclusive\" && fs.capabilitiesFor ? await fs.capabilitiesFor(this.#path(path), { signal, ...(supplied.creation === \"ifMissing\" ? { create: true } : {}) }) : fs.capabilities;\n if (capabilities.readOnly === true && (supplied.access === \"write\" || supplied.access === \"readwrite\" || supplied.creation === \"ifMissing\" || supplied.creation === \"exclusive\" || supplied.truncate === true || supplied.append === true)) throw new FsError(\"EROFS\", { syscall: \"open\", path });\n if (capabilities.open === false) throw new FsError(\"ENOTSUP\", { syscall: \"open\", path });\n signal.throwIfAborted();\n const open = this.#open ?? fs.open!.bind(fs);\n handle = await open(this.#path(path), { ...supplied, signal });\n signal.throwIfAborted();\n const id = this.#next++;\n this.#handles.set(id, handle);\n return id;\n } catch (error) {\n if (handle) try { await handle.close(); } catch { /* Preserve the acquisition failure. */ }\n signal.throwIfAborted();\n throw error;\n } finally { this.#acquiring--; }\n }\n case \"close\": {\n const [id] = request.args;\n const handle = this.#handle(id);\n this.#handles.delete(id);\n await handle.close();\n return;\n }\n case \"descriptorCapabilities\": return { ...this.#handle(request.args[0]).capabilities };\n case \"fstat\": return this.#handle(request.args[0]).stat(options);\n case \"position\": {\n const handle = this.#handle(request.args[0]);\n if (handle.capabilities.position !== true || !handle.getPosition) throw new FsError(\"ENOTSUP\");\n return handle.getPosition(options);\n }\n case \"read\": {\n const [id, length, position] = request.args;\n this.#size(length);\n const buffer = new Uint8Array(length);\n const count = await this.#handle(id).read(buffer, position, options);\n if (!Number.isSafeInteger(count) || count < 0 || count > length) throw new FsError(\"EIO\");\n return buffer.slice(0, count);\n }\n case \"write\": {\n const [id, data, position] = request.args;\n if (!(data instanceof Uint8Array)) throw new FsError(\"EINVAL\");\n this.#size(data.byteLength);\n // The request may outlive its transport's shared reply/request slot.\n const owned = data.slice();\n const count = await this.#handle(id).write(owned, position, options);\n if (!Number.isSafeInteger(count) || count < 0 || count > owned.byteLength) throw new FsError(\"EIO\");\n return count;\n }\n case \"ftruncate\": return this.#handle(request.args[0]).truncate(request.args[1], options);\n case \"sync\": return this.#handle(request.args[0]).sync(request.args[1], options);\n case \"stat\": return fs.stat(this.#path(request.args[0]), options);\n case \"lstat\": return fs.lstat(this.#path(request.args[0]), options);\n case \"realpath\": return fs.realpath(this.#path(request.args[0]), options);\n case \"readdir\": {\n const path = this.#path(request.args[0]);\n const entries = await fs.readdir(path, { ...options, maxEntries: this.#directoryLimit });\n signal.throwIfAborted();\n if (entries.length > this.#directoryLimit) throw new FsError(\"EFBIG\", { syscall: \"readdir\", path, message: \"Python directory listing exceeds configured limit\" });\n return entries;\n }\n case \"access\": return fs.access(this.#path(request.args[0]), request.args[1], options);\n case \"mkdir\": return fs.mkdir(this.#path(request.args[0]), { ...request.args[1], ...options });\n case \"rm\": {\n const path = this.#path(request.args[0]);\n if (!fs.unlink) throw new FsError(\"ENOTSUP\", { syscall: \"unlink\", path });\n return fs.unlink(path, options);\n }\n case \"rmdir\": {\n const path = this.#path(request.args[0]);\n const capabilities = fs.capabilitiesFor ? await fs.capabilitiesFor(path, options) : fs.capabilities;\n signal.throwIfAborted();\n if (capabilities.readOnly === true) throw new FsError(\"EROFS\", { syscall: \"rmdir\", path });\n if (!fs.rmdir || capabilities.removeDirectory === false || capabilities.snapshotRmdir === true) throw new FsError(\"ENOTSUP\", { syscall: \"rmdir\", path });\n return fs.rmdir(path, options);\n }\n case \"rmtreeSupported\":\n case \"rmtree\": {\n const path = this.#path(request.args[0]);\n const capabilities = fs.capabilitiesFor ? await fs.capabilitiesFor(path, options) : fs.capabilities;\n signal.throwIfAborted();\n if (request.op === \"rmtreeSupported\") return capabilities.readOnly === true || capabilities.atomicTreeRemoval === true && typeof fs.removeTreeConditional === \"function\";\n if (capabilities.readOnly === true) throw new FsError(\"EROFS\", { syscall: \"rmtree\", path });\n if (capabilities.atomicTreeRemoval !== true || !fs.removeTreeConditional) throw new FsError(\"ENOTSUP\", { syscall: \"rmtree\", path });\n const expected = await fs.lstat(path, options);\n signal.throwIfAborted();\n if (expected.type !== \"directory\") throw new FsError(\"ENOTDIR\", { syscall: \"rmtree\", path });\n const parent = await fs.stat(dirname(path), options);\n signal.throwIfAborted();\n return fs.removeTreeConditional(path, { ...options, parent, expected });\n }\n case \"rename\": return fs.rename(this.#path(request.args[0]), this.#path(request.args[1]), options);\n case \"readlink\": if (fs.readlink) return fs.readlink(this.#path(request.args[0]), options); break;\n case \"symlink\": if (fs.symlink) return fs.symlink(request.args[0], this.#path(request.args[1]), options); break;\n case \"link\": if (fs.link) return fs.link(this.#path(request.args[0]), this.#path(request.args[1]), options); break;\n case \"chmod\": if (fs.chmod) return fs.chmod(this.#path(request.args[0]), request.args[1], options); break;\n case \"truncate\": if (fs.truncate) return fs.truncate(this.#path(request.args[0]), request.args[1], options); break;\n case \"utimes\": if (fs.utimes) return fs.utimes(this.#path(request.args[0]), request.args[1], request.args[2], options); break;\n }\n throw new FsError(\"ENOTSUP\", { syscall: request.op });\n }\n\n close(): Promise<void> {\n if (!this.#closing) {\n this.#closing = Promise.resolve().then(async () => {\n await Promise.allSettled([...this.#pending]);\n const handles = [...this.#handles.values()];\n this.#handles.clear();\n const results = await Promise.allSettled(handles.map(handle => handle.close()));\n this.#scope.dispose();\n const failed = results.find(result => result.status === \"rejected\");\n if (failed?.status === \"rejected\") throw failed.reason;\n });\n this.#abort.abort(new FsError(\"ECANCELED\", { syscall: \"python filesystem close\" }));\n }\n return this.#closing;\n }\n}\n", "import { FsError } from \"../contracts/errors.js\";\nimport type { OpenFileOptions } from \"../contracts/filesystem.js\";\n\n/** Emscripten's pinned musl flag ABI, not the host operating system's flags. */\nexport function translatePythonOpenFlags(flags: number, mode = 0o666): OpenFileOptions {\n if (!Number.isSafeInteger(flags) || flags < 0 || flags > 0x7fffffff || (flags & 3) === 3) throw new FsError(\"EINVAL\", { syscall: \"open\" });\n const exclusive = (flags & (64 | 128)) === (64 | 128);\n // CLOEXEC and LARGEFILE do not alter the lifetime or numeric range of a virtual descriptor.\n const supported = 3 | 64 | 128 | 512 | 1024 | 32768 | 524288 | (exclusive ? 131072 : 0);\n if ((flags & ~supported) !== 0) throw new FsError(\"ENOTSUP\", { syscall: \"open\" });\n return { access: (flags & 3) === 0 ? \"read\" : (flags & 3) === 1 ? \"write\" : \"readwrite\",\n creation: (flags & 64) !== 0 ? exclusive ? \"exclusive\" : \"ifMissing\" : \"never\",\n truncate: (flags & 512) !== 0, append: (flags & 1024) !== 0, mode };\n}\n", "import { translatePythonOpenFlags } from './flags.js';\n\n// Emscripten's FS is a runtime-owned ABI, rather than a canonical FileSystem.\n// Structural values here deliberately follow that external, dynamically installed ABI.\nexport interface PythonMountOptions {\n request: (operation: string, ...args: any[]) => any;\n cwd: string;\n runtimeMount: string;\n maxTransferBytes: number;\n errno: Record<string, number>;\n synchronizationFlags: number;\n runtimeModule: any;\n}\nexport function mountPythonFileSystem(FS: any, options: PythonMountOptions): void {\nconst {request: rpc, cwd, runtimeMount, maxTransferBytes, errno, synchronizationFlags} = options;\nconst canonicalStat = Symbol('canonical Python stat');\nconst runtimeDevices = createPythonRuntimeStatMapper();\nconst mapRuntimeStat = (stat: any) => {\n try { return runtimeDevices(stat); }\n catch { throw new FS.ErrnoError(errno.EOVERFLOW); }\n};\nconst originalWriteStat = options.runtimeModule.SYSCALLS.writeStat;\noptions.runtimeModule.SYSCALLS.writeStat = (pointer: number, stat: any) => {\n if (!stat[canonicalStat]) {\n try { return originalWriteStat(pointer, mapRuntimeStat(stat)); }\n catch { throw new FS.ErrnoError(errno.EOVERFLOW); }\n }\n try { return writePythonStat(options.runtimeModule.HEAPU8, pointer, stat); }\n catch { throw new FS.ErrnoError(errno.EOVERFLOW); }\n};\nfunction path(node: any): string { return node.parent === node ? \"/\" : `${path(node.parent) === '/' ? '' : path(node.parent)}/${node.name}`; }\nfunction attr(stat: any) {\n return { [canonicalStat]: true, dev: stat.dev, ino: stat.ino, mode: stat.mode | (stat.type === 'directory' ? 16384 : stat.type === 'symlink' ? 40960 : stat.type === 'character' ? 8192 : 32768), nlink: stat.nlink, uid: stat.uid, gid: stat.gid, rdev: stat.type === 'character' ? undefined : 0, size: stat.size, atime: new Date(stat.atimeMs), mtime: new Date(stat.mtimeMs), ctime: new Date(stat.ctimeMs), atimeMs: stat.atimeMs, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, blksize: stat.ioBlockSize ?? stat.preferredIoBlockSize, blocks: stat.allocatedBytes === undefined ? undefined : Math.ceil(stat.allocatedBytes / 512) };\n}\nfunction node(parent: any, name: string, stat: any) {\n const value = FS.createNode(parent, name, attr(stat).mode, 0);\n value.node_ops = nodeOps; value.stream_ops = streamOps;\n return value;\n}\nlet bootstrapMountNode: any;\nconst nodeOps = {\n getattr: (n: any) => attr(n === bootstrapMountNode ? { type: 'directory', mode: 365, size: 0, atimeMs: 0, mtimeMs: 0, ctimeMs: 0 } : rpc('lstat', path(n))),\n setattr(n: any, attributes: any) {\n if (attributes.size !== undefined) rpc('truncate', path(n), attributes.size);\n if (attributes.mode !== undefined) rpc('chmod', path(n), attributes.mode & 4095);\n if (attributes.atime !== undefined || attributes.mtime !== undefined) {\n const previous = attributes.atime === undefined || attributes.mtime === undefined ? rpc('stat', path(n)) : undefined;\n rpc('utimes', path(n), attributes.atime ?? previous.atimeMs, attributes.mtime ?? previous.mtimeMs);\n }\n },\n lookup(parent: any, name: string) {\n if (parent.parent === parent && name === runtimeMount.slice(1)) return bootstrapMountNode ??= node(parent, name, { type: 'directory', mode: 365, size: 0, atimeMs: 0, mtimeMs: 0, ctimeMs: 0 });\n return node(parent, name, rpc('lstat', `${path(parent)}/${name}`));\n },\n mknod(parent: any, name: string, mode: number) {\n const target = `${path(parent)}/${name}`;\n if (FS.isDir(mode)) rpc('mkdir', target, { mode: mode & 4095 });\n else { const handle = rpc('open', target, { access: 'write', creation: 'exclusive', mode: mode & 4095 }); rpc('close', handle); }\n return node(parent, name, rpc('lstat', target));\n },\n rename(n: any, parent: any, name: string) { rpc('rename', path(n), `${path(parent)}/${name}`); n.name = name; n.parent = parent; },\n unlink: (parent: any, name: string) => rpc('rm', `${path(parent)}/${name}`),\n rmdir: (parent: any, name: string) => rpc('rmdir', `${path(parent)}/${name}`),\n readdir: (n: any) => ['.', '..', ...rpc('readdir', path(n)).map((entry: any) => entry.name)],\n readlink: (n: any) => rpc('readlink', path(n)),\n symlink(parent: any, name: string, target: string) { rpc('symlink', target, `${path(parent)}/${name}`); return node(parent, name, rpc('lstat', `${path(parent)}/${name}`)); },\n};\nconst streamOps = {\n getattr: (stream: any) => attr(stream.handle ? rpc('fstat', stream.handle) : rpc('stat', path(stream.node))),\n setattr(stream: any, attributes: any) {\n if (Object.keys(attributes).some(key => key !== 'size' && key !== 'ctime' && !(key === 'timestamp' && attributes.size !== undefined))) throw new FS.ErrnoError(errno.ENOTSUP);\n if (attributes.size !== undefined) rpc('ftruncate', stream.handle, attributes.size);\n },\n open(stream: any) {\n if (FS.isDir(stream.node.mode)) return;\n stream.retained = { references: 1 };\n stream.handle = rpc('open', path(stream.node), { access: (stream.flags & 3) === 0 ? 'read' : (stream.flags & 3) === 1 ? 'write' : 'readwrite', creation: 'never', append: Boolean(stream.flags & 1024) });\n },\n dup: (stream: any) => { if (stream.retained) stream.retained.references++; },\n close: (stream: any) => { if (stream.handle && --stream.retained.references === 0) rpc('close', stream.handle); },\n fsync: (stream: any) => { rpc('sync', stream.handle, false); return 0; },\n read(stream: any, buffer: Uint8Array, offset: number, length: number, position: number) { const data = rpc('read', stream.handle, Math.min(length, maxTransferBytes), stream.seekable ? position : null); buffer.set(data, offset); return data.length; },\n write: (stream: any, buffer: Uint8Array, offset: number, length: number, position: number) => rpc('write', stream.handle, Uint8Array.from(buffer.subarray(offset, offset + Math.min(length, maxTransferBytes))), stream.pythonExplicitPosition ?? (stream.flags & 1024 || !stream.seekable ? null : position)),\n llseek(stream: any, offset: number, whence: number) { if (![0,1,2].includes(whence) || !Number.isSafeInteger(offset)) throw new FS.ErrnoError(errno.EINVAL); const position = whence === 0 ? offset : whence === 1 ? stream.position + offset : rpc('fstat', stream.handle).size + offset; if (!Number.isSafeInteger(position) || position < 0) throw new FS.ErrnoError(28); return position; },\n};\nconst originalLookupNode = FS.lookupNode.bind(FS);\nFS.lookupNode = (parent: any, name: string) => {\n const cached = originalLookupNode(parent, name);\n return parent.node_ops === nodeOps && !cached.mounted ? nodeOps.lookup(parent, name) : cached;\n};\nconst bootstrapRoot = FS.root;\nFS.root = null;\nFS.mount({ mount: () => node(null, '/', rpc('stat', '/')) }, {}, '/');\nFS.mount({ mount: () => bootstrapRoot }, {}, runtimeMount);\nFS.chdir(rpc('realpath', cwd));\n// Intercept before Emscripten decomposes atomic exclusive/truncating open.\nconst originalOpen = FS.open.bind(FS);\nFS.open = function (inputPath: string, flags: number | string, mode = 438) {\n if (typeof flags === 'string') {\n const modes: Record<string, number> = {r:0, 'r+':2, w:577, 'w+':578, a:1089, 'a+':1090};\n const numeric = modes[flags];\n if (numeric === undefined) throw new FS.ErrnoError(errno.EINVAL);\n flags = numeric;\n }\n if (typeof inputPath !== 'string') { if ((flags & 3) !== 0 || (flags & (64 | 512))) throw new FS.ErrnoError(errno.EROFS); return originalOpen(inputPath, flags, mode); }\n if (inputPath.length === 0) throw new FS.ErrnoError(errno.ENOENT);\n const absolute = inputPath.startsWith('/') ? inputPath : `${FS.cwd()}/${inputPath}`;\n if (absolute === runtimeMount || absolute.startsWith(runtimeMount + '/')) {\n if (absolute.split('/').includes('..')) throw new FS.ErrnoError(errno.ENOTSUP);\n if (typeof flags !== 'number' || (flags & 3) !== 0 || (flags & (64 | 512))) throw new FS.ErrnoError(errno.EROFS);\n return originalOpen(inputPath, flags, mode);\n }\n if (typeof flags !== 'number') return originalOpen(inputPath, flags, mode);\n if (flags & synchronizationFlags) throw new FS.ErrnoError(errno.ENOTSUP);\n // Atomic exclusive creation already refuses symlinks and all existing entries.\n const exclusive = (flags & 192) === 192;\n if ((flags & 131072) && !exclusive) throw new FS.ErrnoError(138);\n if (flags & 65536) throw new FS.ErrnoError(54);\n let openOptions;\n try { openOptions = translatePythonOpenFlags(flags, mode); }\n catch (error) { throw new FS.ErrnoError(errno[(error as {code: string}).code] ?? errno.EIO); }\n const handle = rpc('open', absolute, openOptions);\n try {\n // Bind the stream to the acquired identity, without re-opening its pathname.\n // A concurrent rename or unlink after acquisition must not invalidate open().\n const capabilities = rpc('descriptorCapabilities', handle);\n if ((flags & 1024) && !capabilities.position) throw new FS.ErrnoError(errno.ENOTSUP);\n const seekable = ((flags & 3) === 1 || capabilities.positionedRead) && ((flags & 3) === 0 || ((flags & 1024) ? capabilities.position : capabilities.positionedWrite));\n const retainedStat = rpc('fstat', handle);\n if (retainedStat.type === 'directory') throw new FS.ErrnoError(errno.ENOTSUP);\n const retainedNode = node(FS.root, absolute.slice(1), retainedStat);\n return FS.createStream({ node: retainedNode, path: absolute, flags: flags & ~(128 | 512), seekable, position: 0, stream_ops: streamOps, ungotten: [], error: false, handle, pythonCapabilities: capabilities, retained: { references: 1 } });\n } catch (error) { rpc('close', handle); throw error; }\n};\n\n// Pass application operands intact to the authoritative resolver. Emscripten's\n// lexical dot-segment normalization must not run before canonical symlink traversal.\nconst absolutePath = (target: string): string => target.length === 0 || target.startsWith('/') ? target : `${FS.cwd()}/${target}`;\nconst bootstrapPath = (target: string): boolean => {\n const absolute = absolutePath(target);\n const bootstrap = absolute === runtimeMount || absolute.startsWith(runtimeMount + '/');\n if (bootstrap && absolute.split('/').includes('..')) throw new FS.ErrnoError(errno.ENOTSUP);\n return bootstrap;\n};\nfor (const operation of ['stat','lstat']) {\n const original = FS[operation].bind(FS);\n FS[operation] = (target: string, ...args: any[]) => bootstrapPath(target)\n ? mapRuntimeStat(original(target, ...args)) : attr(rpc(operation, absolutePath(target)));\n}\nconst originalFstat = FS.fstat.bind(FS);\nFS.fstat = (fd: number) => {\n const value = originalFstat(fd);\n return value[canonicalStat] ? value : mapRuntimeStat(value);\n};\nfor (const [operation, canonical] of [['unlink','rm'],['rmdir','rmdir'],['chmod','chmod'],['truncate','truncate'],['utime','utimes']] as const) {\n const original = FS[operation].bind(FS);\n FS[operation] = (target: string, ...args: any[]) => bootstrapPath(target)\n ? original(target, ...args) : rpc(canonical, absolutePath(target), ...args);\n}\nconst originalMkdir = FS.mkdir.bind(FS);\nFS.mkdir = (target: string, mode = 0o777) => {\n if (bootstrapPath(target)) return originalMkdir(target, mode);\n const absolute = absolutePath(target);\n rpc('mkdir', absolute, {mode});\n return node(FS.root, absolute.slice(1), rpc('lstat', absolute));\n};\nconst originalRename = FS.rename.bind(FS);\nFS.rename = (source: string, destination: string) => bootstrapPath(source) || bootstrapPath(destination)\n ? originalRename(source, destination) : rpc('rename', absolutePath(source), absolutePath(destination));\nconst originalChdir = FS.chdir.bind(FS);\nFS.chdir = (target: string) => bootstrapPath(target) ? originalChdir(target) : originalChdir(rpc('realpath', absolutePath(target)));\n\nconst runtimeNode = (node: any): boolean => {\n const seen = new Set();\n while (node && !seen.has(node)) {\n if (node === bootstrapRoot || node.mount?.mountpoint === runtimeMount) return true;\n seen.add(node); node = node.parent;\n }\n return false;\n};\nconst assertWritablePath = (target: string): void => {\n if (bootstrapPath(target)) throw new FS.ErrnoError(errno.EROFS);\n};\nconst originalSymlink = FS.symlink.bind(FS);\nFS.symlink = (source: string, destination: string) => bootstrapPath(destination)\n ? originalSymlink(source, destination) : rpc('symlink', source, absolutePath(destination));\nconst originalReaddir = FS.readdir.bind(FS);\nFS.readdir = (target: string) => bootstrapPath(target) ? originalReaddir(target)\n : ['.','..', ...rpc('readdir', absolutePath(target)).map((entry: any) => entry.name)];\nconst originalReadlink = FS.readlink.bind(FS);\nFS.readlink = (target: string) => bootstrapPath(target) ? originalReadlink(target) : rpc('readlink', absolutePath(target));\nfor (const operation of ['chown','lchown','lchmod']) {\n FS[operation] = (target: string) => {assertWritablePath(target); throw new FS.ErrnoError(errno.ENOTSUP);};\n}\nconst originalMknod = FS.mknod.bind(FS);\nFS.mknod = (target: string, mode: number, device: number) => {\n if (bootstrapPath(target)) return originalMknod(target, mode, device);\n if (!FS.isFile(mode)) throw new FS.ErrnoError(errno.ENOTSUP);\n const handle = rpc('open', absolutePath(target), {access:'write',creation:'exclusive',mode:mode & 4095});\n rpc('close', handle);\n return node(FS.root, absolutePath(target).slice(1), rpc('lstat', absolutePath(target)));\n};\nfor (const operation of ['mkdir','mknod','unlink','rmdir','chmod','lchmod','chown','lchown','truncate','utime']) {\n if (typeof FS[operation] !== 'function') continue;\n const original = FS[operation].bind(FS);\n FS[operation] = (target: string, ...args: any[]) => {assertWritablePath(target); return original(target, ...args);};\n}\nfor (const operation of ['rename','symlink']) {\n const original = FS[operation].bind(FS);\n FS[operation] = (source: string, destination: string, ...args: any[]) => {\n if (operation === 'rename') assertWritablePath(source);\n assertWritablePath(destination); return original(source, destination, ...args);\n };\n}\nfor (const operation of ['fchmod','fchown','ftruncate']) {\n if (typeof FS[operation] !== 'function') continue;\n const original = FS[operation].bind(FS);\n FS[operation] = (fd: number, ...args: any[]) => {\n if (runtimeNode(FS.getStreamChecked(fd).node)) throw new FS.ErrnoError(errno.EROFS);\n return original(fd, ...args);\n };\n}\nconst originalWrite = FS.write.bind(FS);\nFS.write = (stream: any, ...args: any[]) => {\n if (stream.fd > 2 && runtimeNode(stream.node)) throw new FS.ErrnoError(errno.EROFS);\n const explicit = typeof args[3] === 'number';\n if (stream.handle && (stream.flags & 1024) && explicit && !stream.pythonCapabilities.positionedAppendWrite) throw new FS.ErrnoError(errno.EINVAL);\n const previousPosition = stream.position;\n stream.pythonExplicitPosition = explicit ? args[3] : undefined;\n let written;\n try { written = originalWrite(stream, ...args); }\n finally { stream.pythonExplicitPosition = undefined; if (explicit) stream.position = previousPosition; }\n if (stream.handle && (stream.flags & 1024) && args[3] === undefined) stream.position = rpc('position', stream.handle);\n return written;\n};\n\n}\n\n/** Encode the pinned wasm32 musl stat layout without truncating canonical values. */\nexport function writePythonStat(heap: Uint8Array, pointer: number, stat: Record<string, any>): number {\n const view = new DataView(heap.buffer, heap.byteOffset, heap.byteLength);\n const integer = (key: string, max: number): number => {\n const value = stat[key];\n if (!Number.isSafeInteger(value) || value < 0 || value > max) throw new Error('EOVERFLOW');\n return value;\n };\n const values = {\n dev: integer('dev', 0xffffffff), mode: integer('mode', 0xffffffff),\n nlink: integer('nlink', 0xffffffff), uid: integer('uid', 0xffffffff),\n gid: integer('gid', 0xffffffff), rdev: integer('rdev', 0xffffffff),\n size: integer('size', Number.MAX_SAFE_INTEGER), ino: integer('ino', Number.MAX_SAFE_INTEGER),\n blksize: integer('blksize', 0x7fffffff), blocks: integer('blocks', 0x7fffffff),\n };\n const times = ['atime', 'mtime', 'ctime'].map(key => {\n const time = stat[key + 'Ms'] ?? stat[key]?.getTime();\n if (!Number.isFinite(time)) throw new Error('EOVERFLOW');\n let seconds = Math.floor(time / 1000);\n let nanoseconds = Math.round((time - seconds * 1000) * 1000000);\n if (nanoseconds === 1000000000) { seconds++; nanoseconds = 0; }\n if (!Number.isSafeInteger(seconds) || nanoseconds < 0 || nanoseconds >= 1000000000) throw new Error('EOVERFLOW');\n return {seconds, nanoseconds};\n });\n if (!Number.isSafeInteger(pointer) || pointer < 0 || pointer + 96 > heap.byteLength) throw new Error('EOVERFLOW');\n for (const [index,key] of ['dev','mode','nlink','uid','gid','rdev'].entries()) view.setUint32(pointer + index * 4, values[key as keyof typeof values], true);\n view.setBigInt64(pointer+24,BigInt(values.size),true);\n view.setInt32(pointer+32,values.blksize,true);\n view.setInt32(pointer+36,values.blocks,true);\n times.forEach((time,index)=>{view.setBigInt64(pointer+40+index*16,BigInt(time.seconds),true);view.setUint32(pointer+48+index*16,time.nanoseconds,true);});\n view.setBigInt64(pointer+88,BigInt(values.ino),true);\n return 0;\n}\n\n/** Runtime storage and application storage occupy disjoint guest device ranges. */\nexport function createPythonRuntimeStatMapper(maxDevices = 1024): (stat: Record<string | symbol, any>) => Record<string | symbol, any> {\n if (!Number.isSafeInteger(maxDevices) || maxDevices < 1 || maxDevices > 1024) throw new RangeError('Invalid runtime device limit');\n const mapped = Symbol('mapped Python runtime device');\n const devices = new Map<number, number>();\n return stat => {\n if (stat[mapped]) return stat;\n if (!Number.isSafeInteger(stat.dev) || stat.dev < 0 || stat.dev > 0xffffffff) throw new Error('EOVERFLOW');\n let device = devices.get(stat.dev);\n if (device === undefined) {\n if (devices.size >= maxDevices) throw new Error('EOVERFLOW');\n device = 0x80000000 + devices.size;\n devices.set(stat.dev, device);\n }\n return {...stat, dev:device, [mapped]:true};\n };\n}\n", "import { FsError } from \"../contracts/errors.js\";\nimport type { FileStat } from \"../contracts/filesystem.js\";\n\nexport type PythonWireStat = Omit<FileStat, \"identityScope\">;\n\n/** Invocation-local device numbers qualify canonical scope/dev without serializing opaque authority. */\nexport class PythonStatTranslator {\n readonly #devices = new Map<object | symbol, Map<number, number>>();\n readonly #maxDevices: number;\n #next = 1;\n constructor(maxDevices = 1024) {\n if (!Number.isSafeInteger(maxDevices) || maxDevices < 1) throw new FsError(\"EINVAL\");\n this.#maxDevices = maxDevices;\n }\n translate(stat: FileStat): PythonWireStat {\n const { identityScope, dev, ino, ...rest } = stat;\n if (!(typeof identityScope === \"symbol\" || typeof identityScope === \"object\" && identityScope !== null)\n || !Number.isSafeInteger(dev) || dev! < 0 || !Number.isSafeInteger(ino) || ino! < 0) return rest;\n let devices = this.#devices.get(identityScope);\n let guestDevice = devices?.get(dev!);\n if (guestDevice === undefined) {\n if (this.#next > this.#maxDevices) throw new FsError(\"EFBIG\", { syscall: \"stat\", message: \"Python device identity limit exceeded\" });\n if (!devices) { devices = new Map(); this.#devices.set(identityScope, devices); }\n guestDevice = this.#next++;\n devices.set(dev!, guestDevice);\n }\n return { ...rest, dev: guestDevice, ino: ino! };\n }\n}\n", "import type { FileSystem } from \"../../contracts/filesystem.js\";\nimport { onlyKeys, record, stringValue, withSignal } from \"./values.js\";\n\nexport interface ShellGuestOptions {\n readonly cwd?: string;\n readonly env?: Readonly<Record<string, string>>;\n readonly stdin?: string;\n}\n\nexport interface ShellExecutionOptions extends ShellGuestOptions {\n readonly fs: FileSystem;\n readonly signal: AbortSignal;\n}\n\nexport interface ShellExecutionResult {\n readonly stdout: string;\n readonly stderr: string;\n readonly exitCode: number;\n}\n\nexport type ShellExecute = (\n source: string,\n options: ShellExecutionOptions,\n) => ShellExecutionResult | Promise<ShellExecutionResult>;\n\nexport interface ShellExecutor {\n exec: ShellExecute;\n}\n\nexport type ShellHostOperation = (\n source: string,\n options?: ShellGuestOptions,\n) => Promise<ShellExecutionResult>;\n\nexport type DeclareShellHostOperation = (\n operation: ShellHostOperation,\n policy: \"read-side-effect\",\n) => ShellHostOperation;\n\nexport interface SafeJsShellOptions {\n readonly fs: FileSystem;\n readonly signal: AbortSignal;\n readonly replayPolicy: \"read-side-effect\";\n readonly declareHostOperation: DeclareShellHostOperation;\n}\n\nfunction guestOptions(value: unknown): ShellGuestOptions {\n if (value === undefined) return {};\n const options = record(value, \"shell options\");\n onlyKeys(options, [\"cwd\", \"env\", \"stdin\"]);\n const env = options.env === undefined ? undefined : record(options.env, \"env\");\n const entries = env === undefined ? undefined : Object.entries(env).map(([key, entry]): [string, string] => {\n if (key.includes(\"\\0\") || key.includes(\"=\")) throw new TypeError(\"Invalid environment key\");\n const text = stringValue(entry, `env.${key}`);\n if (text.includes(\"\\0\")) throw new TypeError(\"Invalid environment value\");\n return [key, text];\n });\n return {\n ...(options.cwd === undefined ? {} : { cwd: stringValue(options.cwd, \"cwd\") }),\n ...(options.stdin === undefined ? {} : { stdin: stringValue(options.stdin, \"stdin\") }),\n ...(entries === undefined ? {} : { env: Object.fromEntries(entries) }),\n };\n}\n\nexport function makeSafeJsShellModule(\n executor: ShellExecute | ShellExecutor,\n options: SafeJsShellOptions,\n): { exec: ShellHostOperation } {\n if (options.fs === undefined) throw new TypeError(\"An explicit filesystem is required\");\n if (!(options.signal instanceof AbortSignal)) throw new TypeError(\"An explicit signal is required\");\n if (options.replayPolicy !== \"read-side-effect\") {\n throw new TypeError(\"Shell operations require the read-side-effect replay policy\");\n }\n if (typeof options.declareHostOperation !== \"function\") {\n throw new TypeError(\"SafeJS declareHostOperation must be injected\");\n }\n const execute = typeof executor === \"function\" ? executor : executor.exec.bind(executor);\n if (typeof execute !== \"function\") throw new TypeError(\"A shell executor is required\");\n async function exec(source: string, input?: ShellGuestOptions): Promise<ShellExecutionResult> {\n const text = stringValue(source, \"source\");\n const request = guestOptions(input);\n return withSignal(options.signal, async () => {\n const result = await execute(text, { ...request, fs: options.fs, signal: options.signal });\n if (!Number.isInteger(result.exitCode) || result.exitCode < 0 || result.exitCode > 255) {\n throw new TypeError(\"Shell exitCode must be an integer between 0 and 255\");\n }\n return {\n stdout: stringValue(result.stdout, \"stdout\"),\n stderr: stringValue(result.stderr, \"stderr\"),\n exitCode: result.exitCode,\n };\n });\n }\n return { exec: options.declareHostOperation(exec, options.replayPolicy) };\n}\n", "import { yieldTurn } from \"../../contracts/yield.js\";\nimport { readBytes, writeBytes, type ByteSink, type ByteSource } from \"../../contracts/index.js\";\nimport { SafeJsCommandLimitError } from \"./types.js\";\nimport { renderOutput } from \"./render.js\";\n\nconst chunkSize = 64 * 1024;\n\nexport class GuestInput {\n private readonly iterator: AsyncGenerator<Uint8Array>;\n private pending: Uint8Array = new Uint8Array();\n private consumed = 0;\n private pulls = 0;\n private queue = Promise.resolve();\n constructor(source: ByteSource, private readonly limit: number, private readonly signal: AbortSignal,\n private readonly fail: (error: unknown) => void, private readonly resource: \"maxSourceBytes\" | \"maxInputBytes\" = \"maxInputBytes\") {\n this.iterator = readBytes(source, signal);\n }\n private async take(size: number): Promise<Uint8Array | undefined> {\n this.signal.throwIfAborted();\n while (!this.pending.length) {\n if (++this.pulls % 64 === 0) await yieldTurn(this.signal);\n const next = await this.iterator.next();\n if (next.done) return undefined;\n this.pending = next.value;\n }\n const length = Math.min(size, this.pending.length);\n if (length > this.limit - this.consumed) {\n const error = new SafeJsCommandLimitError(this.resource); this.fail(error); throw error;\n }\n const bytes = this.pending.slice(0, length);\n this.pending = this.pending.subarray(length);\n this.consumed += length;\n return bytes;\n }\n private serialize<Result>(operation: () => Promise<Result>): Promise<Result> {\n const result = this.queue.then(operation);\n this.queue = result.then(() => {}, () => {});\n return result;\n }\n readBytes(size: unknown = chunkSize): Promise<number[] | null> {\n if (typeof size !== \"number\" || !Number.isSafeInteger(size) || size < 1 || size > chunkSize) throw new TypeError(\"readBytes size must be an integer from 1 through 65536\");\n return this.serialize(async () => { const bytes = await this.take(size); return bytes === undefined ? null : Array.from(bytes); });\n }\n readText(): Promise<string> {\n return this.serialize(async () => {\n const pieces: Uint8Array[] = [];\n for (;;) { const chunk = await this.take(chunkSize); if (!chunk) break; pieces.push(chunk); }\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(Buffer.concat(pieces));\n });\n }\n async close(): Promise<void> { await this.iterator.return(undefined); }\n}\n\nexport class GuestOutput {\n private queue = Promise.resolve();\n private produced = 0;\n stderrFailed = false;\n constructor(private readonly stdout: ByteSink, private readonly stderr: ByteSink, private readonly limit: number,\n private readonly signal: AbortSignal, private readonly fail: (error: unknown) => void) {}\n private enqueue(bytes: Uint8Array, target: ByteSink): Promise<void> {\n this.signal.throwIfAborted();\n if (bytes.length > this.limit - this.produced) {\n const error = new SafeJsCommandLimitError(\"maxOutputBytes\"); this.fail(error); throw error;\n }\n this.produced += bytes.length;\n const queued = this.queue.then(async () => {\n for (let offset = 0; offset < bytes.length; offset += chunkSize) await writeBytes(target, bytes.subarray(offset, offset + chunkSize), this.signal);\n }).catch(error => { if (target === this.stderr) this.stderrFailed = true; this.fail(error); throw error; });\n this.queue = queued;\n void queued.catch(() => {});\n return queued;\n }\n text(value: unknown, stderr = false): Promise<void> {\n if (typeof value !== \"string\") throw new TypeError(\"stdio text output requires a string\");\n if (Buffer.byteLength(value) > this.limit - this.produced) {\n const error = new SafeJsCommandLimitError(\"maxOutputBytes\"); this.fail(error); throw error;\n }\n return this.enqueue(Buffer.from(value), stderr ? this.stderr : this.stdout);\n }\n bytes(value: unknown, stderr = false): Promise<void> {\n if (!Array.isArray(value) || value.length > chunkSize) throw new TypeError(\"stdio byte output requires an array of at most 65536 bytes\");\n for (const byte of value) if (!Number.isInteger(byte) || byte < 0 || byte > 255) throw new TypeError(\"stdio byte values must be integers from 0 through 255\");\n return this.enqueue(Uint8Array.from(value as number[]), stderr ? this.stderr : this.stdout);\n }\n console(args: readonly unknown[], stderr: boolean): void {\n void this.text(renderOutput(args, this.limit - this.produced, this.fail), stderr);\n }\n result(value: unknown): Promise<void> {\n return this.text(renderOutput([value], this.limit - this.produced, this.fail));\n }\n async drain(): Promise<void> { await this.queue; }\n}\n", "import type { FileSystem, FsBridgeOptions } from \"poe-code/safe-fs/core\";\n\nexport type SafeJsHostFunction = { call(...args: readonly unknown[]): unknown }[\"call\"];\nexport type SafeJsHostValue = string | number | boolean | null | undefined | SafeJsHostFunction\n | readonly SafeJsHostValue[] | { readonly [key: string]: SafeJsHostValue };\nexport type SafeJsModule = Record<string, SafeJsHostValue>;\n\nexport interface SafeJsBudgetOptions {\n readonly maxSteps: number;\n readonly deadline: number;\n readonly maxCallDepth: number;\n readonly stringLength: number;\n readonly arrayLength: number;\n readonly dataSize: number;\n}\n\nexport interface SafeJsRunOptions<Budget> {\n readonly bindings?: SafeJsModule;\n readonly budget: Budget;\n readonly filename: string;\n readonly modules: Record<string, SafeJsModule>;\n readonly signal: AbortSignal;\n readonly sink: { log(...args: unknown[]): void; error(...args: unknown[]): void };\n}\n\nexport type SafeJsRunResult = { readonly ok: true; readonly returnValue?: unknown }\n | { readonly ok: false; readonly error: unknown };\n\nexport interface SafeJsRuntime<Budget> {\n readonly run: (source: string, options: SafeJsRunOptions<Budget>) => Promise<SafeJsRunResult>;\n readonly createBudget: (options: SafeJsBudgetOptions) => Budget;\n readonly makeFsModule: (options: { adapter: FileSystem } & Pick<FsBridgeOptions, \"cwd\" | \"signal\">) => SafeJsModule;\n readonly declareHostOperation: <Operation extends SafeJsHostFunction>(operation: Operation, policy: \"read-side-effect\") => Operation;\n}\n\nexport interface SafeJsCommandLimits {\n readonly maxSourceBytes: number;\n readonly maxInputBytes: number;\n readonly maxOutputBytes: number;\n readonly timeoutMs: number;\n readonly maxSteps: number;\n readonly maxCallDepth: number;\n readonly stringLength: number;\n readonly arrayLength: number;\n readonly dataSize: number;\n}\n\nexport interface SafeJsCommandsOptions<Budget = unknown> {\n readonly runtime?: SafeJsRuntime<Budget>;\n readonly limits?: Partial<SafeJsCommandLimits>;\n readonly replace?: boolean;\n}\n\nexport class SafeJsCommandLimitError extends Error {\n readonly code = \"SAFEJS_LIMIT\";\n constructor(readonly resource: keyof SafeJsCommandLimits) {\n super(`SafeJS command limit exceeded: ${resource}`);\n this.name = \"SafeJsCommandLimitError\";\n }\n}\n", "import { record } from \"../../integrations/safejs/values.js\";\nimport { SafeJsCommandLimitError } from \"./types.js\";\n\nclass Text {\n private readonly parts: string[] = [];\n private size = 0;\n private readonly active = new Set<object>();\n constructor(private readonly limit: number, private readonly fail: (error: unknown) => void) {}\n append(value: string): void {\n if (Buffer.byteLength(value) > this.limit - this.size) {\n const error = new SafeJsCommandLimitError(\"maxOutputBytes\"); this.fail(error); throw error;\n }\n this.size += Buffer.byteLength(value);\n this.parts.push(value);\n }\n private quoted(value: string): void {\n if (Buffer.byteLength(value) + 2 > this.limit - this.size) {\n const error = new SafeJsCommandLimitError(\"maxOutputBytes\"); this.fail(error); throw error;\n }\n this.append(JSON.stringify(value));\n }\n json(value: unknown, depth = 0): void {\n if (depth > 64) throw new TypeError(\"output JSON exceeds depth 64\");\n if (value === null || value === undefined) { this.append(\"null\"); return; }\n if (typeof value === \"string\") { this.quoted(value); return; }\n if (typeof value === \"boolean\" || typeof value === \"number\") { this.append(JSON.stringify(value)); return; }\n if (typeof value !== \"object\" || this.active.has(value)) throw new TypeError(\"output requires acyclic JSON data\");\n this.active.add(value);\n try {\n if (Array.isArray(value)) {\n this.append(\"[\");\n for (let index = 0; index < value.length; index++) {\n if (index) this.append(\",\");\n const property = Object.getOwnPropertyDescriptor(value, String(index));\n if (property && !(\"value\" in property)) throw new TypeError(\"output arrays must contain data properties\");\n this.json(property?.value, depth + 1);\n }\n this.append(\"]\");\n } else {\n const entries = record(value, \"output value\");\n this.append(\"{\");\n let first = true;\n for (const [key, item] of Object.entries(entries)) {\n if (item === undefined) continue;\n if (!first) this.append(\",\"); first = false;\n this.quoted(key); this.append(\":\"); this.json(item, depth + 1);\n }\n this.append(\"}\");\n }\n } finally { this.active.delete(value); }\n }\n finish(): string { return this.parts.join(\"\"); }\n}\n\nexport function renderOutput(values: readonly unknown[], limit: number, fail: (error: unknown) => void): string {\n const text = new Text(limit, fail);\n for (let index = 0; index < values.length; index++) {\n if (index) text.append(\" \");\n const value = values[index];\n if (typeof value === \"string\") text.append(value);\n else if (value === undefined) text.append(\"undefined\");\n else text.json(value);\n }\n text.append(\"\\n\");\n return text.finish();\n}\n", "import { UsageError } from \"../internal.js\";\nimport type { SafeJsCommandLimits } from \"./types.js\";\n\nexport const defaultSafeJsLimits: Readonly<SafeJsCommandLimits> = Object.freeze({\n maxSourceBytes: 1024 * 1024, maxInputBytes: 8 * 1024 * 1024, maxOutputBytes: 8 * 1024 * 1024,\n timeoutMs: 5000, maxSteps: 100_000, maxCallDepth: 128, stringLength: 1024 * 1024,\n arrayLength: 100_000, dataSize: 16 * 1024 * 1024,\n});\n\nexport function commandLimits(options: Partial<SafeJsCommandLimits> = {}): SafeJsCommandLimits {\n const result = { ...defaultSafeJsLimits, ...options };\n for (const [name, value] of Object.entries(result)) {\n if (!Object.hasOwn(defaultSafeJsLimits, name)) throw new TypeError(`Unknown SafeJS limit: ${name}`);\n if (!Number.isSafeInteger(value) || value < (name === \"timeoutMs\" ? 1 : 0)) throw new RangeError(`Invalid SafeJS limit: ${name}`);\n }\n if (result.timeoutMs > 2_147_483_647) throw new RangeError(\"SafeJS timeoutMs exceeds timer range\");\n return Object.freeze(result);\n}\n\nexport interface Invocation { readonly source?: string; readonly file: string; readonly args: readonly string[]; readonly print: boolean; readonly help: boolean }\n\nexport function invocation(args: readonly string[]): Invocation {\n let print = false;\n for (let index = 0; index < args.length; index++) {\n const argument = args[index]!;\n if (argument === \"-h\" || argument === \"--help\") return { file: \"-\", args: [], print, help: true };\n if (argument === \"-p\" || argument === \"--print\") { print = true; continue; }\n if (argument === \"-e\" || argument === \"--eval\" || argument.startsWith(\"--eval=\") || argument.startsWith(\"-e\")) {\n const source = argument.startsWith(\"--eval=\") ? argument.slice(7) : argument.length > 2 && argument !== \"--eval\" ? argument.slice(2) : args[++index];\n if (source === undefined) throw new UsageError(`${argument} requires SafeJS source`);\n const rest = args.slice(index + 1);\n return { source, file: \"<safejs -e>\", args: rest[0] === \"--\" ? rest.slice(1) : rest, print, help: false };\n }\n if (argument === \"--\") {\n const file = args[index + 1] ?? \"-\";\n return { file, args: args.slice(index + 2), print, help: false };\n }\n if (argument !== \"-\" && argument.startsWith(\"-\")) throw new UsageError(`unrecognized option '${argument}'`);\n return { file: argument, args: args.slice(index + 1), print, help: false };\n }\n return { file: \"-\", args: [], print, help: false };\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAAA;;;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,MAAM;AAAA,MAC/B;AACA,cAAQ,KAAK,EAAE,GAAG,IAAI,SAAS,GAAG;AAClC,YAAM,kBAAkB,oBAAI,IAAI,CAAC,CAAC,eAAe,EAAE,GAAG,CAAC,oBAAoB,EAAE,CAAC,CAAC;AAC/E,aAAO;AAAA,QACL,SAAS,SAAS,QAAQ;AAAA,EAAkB,MAAM;AAAA,OAAU,UAAU;AAAA,QACtE,UAAU;AAAA,UACR,SAAS;AAAA,UAAe,uBAAuB,QAAQ;AAAA,UACvD,SAAS,QAAQ,QAAQ,qBAAqB,CAAC,SAAkB;AAC/D,kBAAM,SAAS,OAAO,SAAS,WAAW,gBAAgB,IAAI,IAAI,IAAI;AACtE,gBAAI,CAAC,OAAQ,OAAM,IAAI,UAAU,8DAA8D;AAC/F,mBAAO;AAAA,UACT,GAAG,kBAAkB;AAAA,QACvB;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACD,SAAO,OAAO,OAAO,YAAY,CAAC,CAAE;AACtC;",
|
|
6
|
-
"names": ["readBytes", "mode", "dirname", "components", "posixPath", "readOnly", "options", "fail", "names", "record", "mode", "entry", "integer", "unsupported", "signal", "chunkSize", "start", "prefix", "localName", "invalid", "parseXml", "responses", "fail", "components", "entries", "chunkSize", "readBytes", "mode", "entries", "entries"]
|
|
7
|
-
}
|