@pgxsinkit/pgwasm 0.6.1 → 0.6.3

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.
Files changed (74) hide show
  1. package/README.md +8 -0
  2. package/dist/{chunk-jnmd6w7f.js → chunk-4eb2pcfr.js} +18 -3
  3. package/dist/chunk-4eb2pcfr.js.map +10 -0
  4. package/dist/{chunk-garmxqte.js → chunk-82r7js5b.js} +101 -21
  5. package/dist/chunk-82r7js5b.js.map +16 -0
  6. package/dist/{chunk-c06zjbcj.js → chunk-cgt5pdan.js} +2 -290
  7. package/dist/chunk-cgt5pdan.js.map +13 -0
  8. package/dist/{chunk-cpsnmzrf.js → chunk-jwz46twh.js} +14 -2
  9. package/dist/chunk-jwz46twh.js.map +10 -0
  10. package/dist/{chunk-d2kpv98r.js → chunk-rqykg4gj.js} +1 -1
  11. package/dist/{chunk-d2kpv98r.js.map → chunk-rqykg4gj.js.map} +1 -1
  12. package/dist/{chunk-10ebj4re.js → chunk-rsenqaz0.js} +2 -2
  13. package/dist/{chunk-10ebj4re.js.map → chunk-rsenqaz0.js.map} +1 -1
  14. package/dist/chunk-ryjxx1c8.js +303 -0
  15. package/dist/chunk-ryjxx1c8.js.map +10 -0
  16. package/dist/core/parse.d.ts.map +1 -1
  17. package/dist/core/pgwasm.d.ts.map +1 -1
  18. package/dist/drizzle/codecs.d.ts.map +1 -1
  19. package/dist/drizzle/driver.d.ts.map +1 -1
  20. package/dist/drizzle/index.js +2 -2
  21. package/dist/drizzle/index.js.map +3 -3
  22. package/dist/drizzle/session.d.ts.map +1 -1
  23. package/dist/errors.d.ts +5 -1
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/index.d.ts +1 -1
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +7 -5
  28. package/dist/index.js.map +1 -1
  29. package/dist/interface.d.ts +4 -1
  30. package/dist/interface.d.ts.map +1 -1
  31. package/dist/live/format-query.d.ts.map +1 -1
  32. package/dist/live/index.js +5 -5
  33. package/dist/live/index.js.map +3 -3
  34. package/dist/opfs/core/mounted-vfs.d.ts +1 -1
  35. package/dist/opfs/core/mounted-vfs.d.ts.map +1 -1
  36. package/dist/opfs/index.js +3 -3
  37. package/dist/opfs/index.js.map +8 -8
  38. package/dist/protocol/index.d.ts.map +1 -1
  39. package/dist/protocol/index.js +6 -4
  40. package/dist/protocol/index.js.map +3 -3
  41. package/dist/protocol/wire/parser.d.ts.map +1 -1
  42. package/dist/templating.d.ts.map +1 -1
  43. package/dist/types.d.ts +2 -1
  44. package/dist/types.d.ts.map +1 -1
  45. package/package.json +1 -1
  46. package/skills/opfs/SKILL.md +1 -1
  47. package/src/core/data-dir-archive.ts +1 -1
  48. package/src/core/parse.ts +2 -2
  49. package/src/core/pgwasm.ts +104 -17
  50. package/src/drizzle/codecs.ts +2 -2
  51. package/src/drizzle/driver.ts +1 -1
  52. package/src/drizzle/session.ts +2 -2
  53. package/src/errors.ts +10 -1
  54. package/src/index.ts +1 -0
  55. package/src/interface.ts +4 -1
  56. package/src/live/format-query.ts +2 -1
  57. package/src/opfs/broker/client.ts +4 -4
  58. package/src/opfs/broker/server.ts +3 -3
  59. package/src/opfs/core/codec.ts +2 -2
  60. package/src/opfs/core/metadata-store.ts +6 -6
  61. package/src/opfs/core/mounted-vfs.ts +1 -1
  62. package/src/opfs/core/port.ts +1 -1
  63. package/src/opfs/core/repacked-vfs.ts +6 -6
  64. package/src/opfs/core/state-machine.ts +3 -3
  65. package/src/protocol/index.ts +1 -1
  66. package/src/protocol/wire/parser.ts +4 -4
  67. package/src/templating.ts +3 -1
  68. package/src/types.ts +15 -1
  69. package/dist/chunk-c06zjbcj.js.map +0 -14
  70. package/dist/chunk-cpsnmzrf.js.map +0 -10
  71. package/dist/chunk-garmxqte.js.map +0 -16
  72. package/dist/chunk-jnmd6w7f.js.map +0 -10
  73. package/dist/chunk-kb3rsr7n.js +0 -19
  74. package/dist/chunk-kb3rsr7n.js.map +0 -9
@@ -7,19 +7,19 @@
7
7
  "const CRC32_TABLE = new Uint32Array(256);\n\nfor (let value = 0; value < CRC32_TABLE.length; value += 1) {\n let remainder = value;\n for (let bit = 0; bit < 8; bit += 1) {\n remainder = (remainder & 1) === 1 ? 0xedb88320 ^ (remainder >>> 1) : remainder >>> 1;\n }\n CRC32_TABLE[value] = remainder >>> 0;\n}\n\nconst CRC32_SLICES: Uint32Array[] = [CRC32_TABLE];\nfor (let slice = 1; slice < 8; slice += 1) {\n const previous = CRC32_SLICES[slice - 1]!;\n const current = new Uint32Array(256);\n for (let value = 0; value < current.length; value += 1) {\n const remainder = previous[value]!;\n current[value] = (CRC32_TABLE[remainder & 0xff]! ^ (remainder >>> 8)) >>> 0;\n }\n CRC32_SLICES.push(current);\n}\n\nconst CRC32_SLICE_1 = CRC32_SLICES[1]!;\nconst CRC32_SLICE_2 = CRC32_SLICES[2]!;\nconst CRC32_SLICE_3 = CRC32_SLICES[3]!;\nconst CRC32_SLICE_4 = CRC32_SLICES[4]!;\nconst CRC32_SLICE_5 = CRC32_SLICES[5]!;\nconst CRC32_SLICE_6 = CRC32_SLICES[6]!;\nconst CRC32_SLICE_7 = CRC32_SLICES[7]!;\n\nfunction updateCrc32(remainder: number, bytes: Uint8Array, start: number, end: number): number {\n let index = start;\n while (index + 8 <= end) {\n const word =\n remainder ^ (bytes[index]! | (bytes[index + 1]! << 8) | (bytes[index + 2]! << 16) | (bytes[index + 3]! << 24));\n remainder =\n CRC32_SLICE_7[word & 0xff]! ^\n CRC32_SLICE_6[(word >>> 8) & 0xff]! ^\n CRC32_SLICE_5[(word >>> 16) & 0xff]! ^\n CRC32_SLICE_4[word >>> 24]! ^\n CRC32_SLICE_3[bytes[index + 4]!]! ^\n CRC32_SLICE_2[bytes[index + 5]!]! ^\n CRC32_SLICE_1[bytes[index + 6]!]! ^\n CRC32_TABLE[bytes[index + 7]!]!;\n index += 8;\n }\n for (; index < end; index += 1) {\n remainder = CRC32_TABLE[(remainder ^ bytes[index]!) & 0xff]! ^ (remainder >>> 8);\n }\n return remainder;\n}\n\nfunction updateCrc32WithZeros(remainder: number, length: number): number {\n while (length >= 8) {\n remainder =\n CRC32_SLICE_7[remainder & 0xff]! ^\n CRC32_SLICE_6[(remainder >>> 8) & 0xff]! ^\n CRC32_SLICE_5[(remainder >>> 16) & 0xff]! ^\n CRC32_SLICE_4[remainder >>> 24]!;\n length -= 8;\n }\n while (length > 0) {\n remainder = CRC32_TABLE[remainder & 0xff]! ^ (remainder >>> 8);\n length -= 1;\n }\n return remainder;\n}\n\nexport function crc32(bytes: Uint8Array): number {\n const remainder = updateCrc32(0xffff_ffff, bytes, 0, bytes.byteLength);\n return (remainder ^ 0xffff_ffff) >>> 0;\n}\n\nexport function crc32WithZeroedRange(bytes: Uint8Array, offset: number, length: number): number {\n if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0) {\n throw new TypeError(\"checksum range must use non-negative safe integers\");\n }\n if (offset + length > bytes.byteLength) {\n throw new RangeError(\"checksum range exceeds the input\");\n }\n const zeroEnd = offset + length;\n let remainder = updateCrc32(0xffff_ffff, bytes, 0, offset);\n remainder = updateCrc32WithZeros(remainder, length);\n remainder = updateCrc32(remainder, bytes, zeroEnd, bytes.byteLength);\n return (remainder ^ 0xffff_ffff) >>> 0;\n}\n",
8
8
  "import { StoreLimitError } from \"./errors\";\n\n/**\n * The on-disk format identity. Bumped to 2 by the symlink entry kind: a format-1 reader meets an\n * inode kind and a transaction record it cannot decode, and the recreate-only version policy\n * (ADR-0048 §3) is the store's ONLY evolution mechanism — one build reads and writes exactly one\n * version, and a store identifying another one is rejected with `StoreRecreationRequiredError`\n * before any content mutation. There is no migration and never will be.\n */\nexport const FORMAT_VERSION = 2;\nexport const LIMITS_PROFILE_VERSION = 1;\nexport const ARENA_HEADER_BYTES = 8192;\nexport const MIN_EXTENT_BYTES = 8192;\nexport const MAX_EXTENT_BYTES = 16 * 1024 * 1024;\nexport const DEFAULT_EXTENT_BYTES = 64 * 1024;\nexport const MAX_COMPONENT_BYTES = 255;\nexport const MAX_PATH_BYTES = 1024;\nexport const MAX_PATH_DEPTH = 32;\n/** How many symbolic links one path resolution may traverse before it reports `ELOOP`. */\nexport const MAX_SYMLINK_HOPS = 32;\nexport const MAX_INODES = 65_536;\nexport const MAX_EXTENTS_PER_INODE = 2 ** 20;\nexport const MAX_TOTAL_EXTENTS = 2 ** 22;\nexport const MAX_METADATA_BASE_READER_BYTES = 64 * 1024 * 1024;\nexport const MAX_METADATA_BASE_WRITER_BYTES = 32 * 1024 * 1024;\nexport const MAX_FRAME_PAYLOAD_BYTES = 1024 * 1024;\nexport const MAX_ACTIVE_LOG_BYTES = 16 * 1024 * 1024;\nexport const SOFT_ACTIVE_LOG_BYTES = 8 * 1024 * 1024;\nexport const MAX_ACTIVE_LOG_FRAMES = 32_768;\nexport const SOFT_ACTIVE_LOG_FRAMES = 16_384;\nexport const MAX_U64 = (1n << 64n) - 1n;\n\nexport function validateExtentSize(value: number): number {\n if (\n !Number.isSafeInteger(value) ||\n value < MIN_EXTENT_BYTES ||\n value > MAX_EXTENT_BYTES ||\n value % ARENA_HEADER_BYTES !== 0\n ) {\n throw new TypeError(\n `extentSize must be an ${ARENA_HEADER_BYTES}-byte multiple between ${MIN_EXTENT_BYTES} and ${MAX_EXTENT_BYTES}`,\n );\n }\n return value;\n}\n\nexport function checkedU64(value: bigint, label: string): bigint {\n if (value < 0n || value > MAX_U64) {\n throw new StoreLimitError(`${label} is outside the unsigned 64-bit range`);\n }\n return value;\n}\n\nexport function checkedSafeNumber(value: bigint, label: string): number {\n checkedU64(value, label);\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new StoreLimitError(`${label} exceeds JavaScript's safe integer range`);\n }\n return Number(value);\n}\n\nexport function checkedAdd(left: bigint, right: bigint, label: string): bigint {\n return checkedU64(left + right, label);\n}\n\nexport function checkedMultiply(left: bigint, right: bigint, label: string): bigint {\n return checkedU64(left * right, label);\n}\n",
9
9
  "import { FsError } from \"./errors\";\nimport { MAX_COMPONENT_BYTES, MAX_PATH_BYTES, MAX_PATH_DEPTH } from \"./limits\";\n\nfunction utf8Length(value: string, label: string): number {\n let bytes = 0;\n for (let index = 0; index < value.length; index += 1) {\n const codeUnit = value.charCodeAt(index);\n if (codeUnit <= 0x7f) {\n bytes += 1;\n } else if (codeUnit <= 0x7ff) {\n bytes += 2;\n } else if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (index + 1 >= value.length || next < 0xdc00 || next > 0xdfff) {\n throw new FsError(\"EINVAL\", `${label} is not canonically representable as UTF-8`);\n }\n bytes += 4;\n index += 1;\n } else if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {\n throw new FsError(\"EINVAL\", `${label} is not canonically representable as UTF-8`);\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n\nexport function encodedUtf8Length(value: string): number {\n return utf8Length(value, \"string\");\n}\n\nexport function validatePathComponent(component: string): number {\n if (component.length === 0 || component === \".\" || component === \"..\") {\n throw new FsError(\"EINVAL\", \"path contains an empty or reserved component\");\n }\n if (component.includes(\"/\") || component.includes(\"\\0\")) {\n throw new FsError(\"EINVAL\", \"path component contains a forbidden character\");\n }\n const bytes = utf8Length(component, \"path component\");\n if (bytes > MAX_COMPONENT_BYTES) {\n throw new FsError(\"EINVAL\", `path component exceeds ${MAX_COMPONENT_BYTES} UTF-8 bytes`);\n }\n return bytes;\n}\n\n/**\n * Validate a symbolic link's target and report its UTF-8 byte length.\n *\n * Targets are ABSOLUTE ONLY, and deliberately so: an absolute target resolves by restarting the\n * walk at the store root, which needs no notion of \"the directory the link lives in\" and therefore\n * survives a rename of the link. It is also all a Postgres datadir ever writes — `CREATE TABLESPACE`\n * links `pg_tblspc/<oid>` at the absolute `LOCATION`. A relative target is `EINVAL`, not silently\n * reinterpreted.\n */\nexport function validateSymlinkTarget(target: string): number {\n const bytes = utf8Length(target, \"symlink target\");\n if (bytes === 0 || bytes > MAX_PATH_BYTES) {\n throw new FsError(\"EINVAL\", `symlink target must be 1 to ${MAX_PATH_BYTES} UTF-8 bytes`);\n }\n parsePath(target);\n return bytes;\n}\n\nexport function parsePath(path: string): string[] {\n if (path === \"/\") {\n return [];\n }\n if (!path.startsWith(\"/\") || path.endsWith(\"/\") || path.includes(\"//\")) {\n throw new FsError(\"EINVAL\", \"path must be absolute and canonical\", { path });\n }\n if (utf8Length(path, \"path\") > MAX_PATH_BYTES) {\n throw new FsError(\"EINVAL\", `path exceeds ${MAX_PATH_BYTES} UTF-8 bytes`, { path });\n }\n const components = path.slice(1).split(\"/\");\n if (components.length > MAX_PATH_DEPTH) {\n throw new FsError(\"EINVAL\", `path exceeds ${MAX_PATH_DEPTH} components`, { path });\n }\n for (const component of components) {\n validatePathComponent(component);\n }\n return components;\n}\n",
10
- "import { FsError, StoreLimitError } from \"./errors\";\nimport {\n MAX_EXTENTS_PER_INODE,\n MAX_INODES,\n MAX_FRAME_PAYLOAD_BYTES,\n MAX_METADATA_BASE_WRITER_BYTES,\n MAX_PATH_BYTES,\n MAX_PATH_DEPTH,\n MAX_SYMLINK_HOPS,\n MAX_TOTAL_EXTENTS,\n MAX_U64,\n checkedAdd,\n checkedU64,\n validateExtentSize,\n} from \"./limits\";\nimport { encodedUtf8Length, parsePath, validatePathComponent, validateSymlinkTarget } from \"./path\";\n\nexport type InodeId = bigint;\nexport type ExtentId = bigint;\nexport type MetadataFile = \"a\" | \"b\";\n\nexport function otherMetadataFile(file: MetadataFile): MetadataFile {\n return file === \"a\" ? \"b\" : \"a\";\n}\n\ninterface BaseInode {\n id: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n}\n\nexport interface DirectoryInode extends BaseInode {\n kind: \"directory\";\n children: Map<string, InodeId>;\n}\n\nexport interface FileInode extends BaseInode {\n kind: \"file\";\n size: bigint;\n extents: ExtentId[];\n}\n\n/**\n * A symbolic link. It owns no extents and no children — the whole entry IS its absolute `target`,\n * which path resolution restarts the walk at. See {@link validateSymlinkTarget} for why relative\n * targets are refused.\n */\nexport interface SymlinkInode extends BaseInode {\n kind: \"symlink\";\n target: string;\n}\n\nexport type Inode = DirectoryInode | FileInode | SymlinkInode;\n\nexport interface OrphanRecord {\n inodeId: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n size: bigint;\n extents: ExtentId[];\n}\n\nexport function makeOrphanRecord(inode: FileInode): OrphanRecord {\n return {\n inodeId: inode.id,\n mode: inode.mode,\n atimeMs: inode.atimeMs,\n mtimeMs: inode.mtimeMs,\n ctimeMs: inode.ctimeMs,\n size: inode.size,\n extents: [...inode.extents],\n };\n}\n\nexport class IndexedExtentSet {\n readonly #items: ExtentId[] = [];\n readonly #indexes = new Map<ExtentId, number>();\n\n get size(): number {\n return this.#items.length;\n }\n\n has(extentId: ExtentId): boolean {\n return this.#indexes.has(extentId);\n }\n\n add(extentId: ExtentId): void {\n if (this.#indexes.has(extentId)) {\n return;\n }\n this.#indexes.set(extentId, this.#items.length);\n this.#items.push(extentId);\n }\n\n delete(extentId: ExtentId): boolean {\n const index = this.#indexes.get(extentId);\n if (index === undefined) {\n return false;\n }\n const last = this.#items.pop();\n this.#indexes.delete(extentId);\n if (last !== undefined && index < this.#items.length) {\n this.#items[index] = last;\n this.#indexes.set(last, index);\n }\n return true;\n }\n\n values(): readonly ExtentId[] {\n return this.#items;\n }\n\n peekLast(count: number): ExtentId[] {\n if (!Number.isSafeInteger(count) || count < 0 || count > this.#items.length) {\n throw new StoreLimitError(\"invalid available-extent selection count\");\n }\n return this.#items.slice(this.#items.length - count).reverse();\n }\n\n clone(): IndexedExtentSet {\n const copy = new IndexedExtentSet();\n for (const extentId of this.#items) {\n copy.add(extentId);\n }\n return copy;\n }\n}\n\nexport interface AllocatorState {\n totalExtents: bigint;\n ownedBy: Map<ExtentId, InodeId>;\n available: IndexedExtentSet;\n quarantine: Map<ExtentId, bigint | null>;\n}\n\nexport interface VfsState {\n generation: bigint;\n nextInodeId: bigint;\n rootInodeId: bigint;\n extentSize: number;\n activeMetadataFile: MetadataFile;\n retainedGenerations: Record<MetadataFile, bigint | null>;\n basePayloadBytes: number;\n inodes: Map<InodeId, Inode>;\n parentByInode: Map<InodeId, { parentId: InodeId; name: string }>;\n allocator: AllocatorState;\n}\n\nexport interface CreateDirectoryChoice {\n parentId: InodeId;\n name: string;\n inodeId: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n}\n\nexport interface ExtentRun {\n start: ExtentId;\n count: number;\n}\n\nexport type TxnRecord =\n | {\n kind: \"createDirectories\";\n entries: readonly CreateDirectoryChoice[];\n }\n | {\n kind: \"createFile\";\n parentId: InodeId;\n name: string;\n inodeId: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n size: bigint;\n extents: readonly ExtentRun[];\n }\n | {\n kind: \"removeFile\";\n parentId: InodeId;\n name: string;\n parentMtimeMs: bigint;\n parentCtimeMs: bigint;\n }\n | {\n kind: \"changeMode\";\n inodeId: InodeId;\n mode: number;\n ctimeMs: bigint;\n }\n | {\n kind: \"changeTimes\";\n inodeId: InodeId;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n }\n | {\n kind: \"resizeFile\";\n operation: \"truncate\" | \"write\";\n inodeId: InodeId;\n size: bigint;\n allocated: readonly ExtentRun[];\n mtimeMs: bigint;\n ctimeMs: bigint;\n }\n | {\n kind: \"removeDirectory\";\n parentId: InodeId;\n name: string;\n parentMtimeMs: bigint;\n parentCtimeMs: bigint;\n }\n | {\n kind: \"rename\";\n sourceParentId: InodeId;\n sourceName: string;\n destinationParentId: InodeId;\n destinationName: string;\n timestampMs: bigint;\n }\n | {\n kind: \"createSymlink\";\n parentId: InodeId;\n name: string;\n inodeId: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n target: string;\n }\n | {\n kind: \"reserveQuarantine\";\n extents: readonly ExtentRun[];\n };\n\nexport interface TxnPlan<RecordType extends TxnRecord = TxnRecord> {\n record: RecordType;\n}\n\nexport interface PreflightLimits {\n maxFramePayloadBytes: number;\n maxBasePayloadBytes: number;\n}\n\nconst BASE_STATE_FIXED_BYTES = 20;\nconst DIRECTORY_INODE_FIXED_BYTES = 41;\nconst FILE_INODE_FIXED_BYTES = 49;\n/** The common inode header plus the target's `u16` length prefix; the target bytes are added on. */\nconst SYMLINK_INODE_FIXED_BYTES = 39;\nconst CHILD_FIXED_BYTES = 10;\n/** The mode a symbolic link carries: `S_IFLNK | 0777`, the only mode POSIX gives a link. */\nexport const SYMLINK_MODE = 0o120777;\n\nfunction childBaseBytes(name: string): number {\n return CHILD_FIXED_BYTES + encodedUtf8Length(name);\n}\n\nfunction inodeBaseBytes(inode: Inode): number {\n if (inode.kind === \"file\") {\n return FILE_INODE_FIXED_BYTES + inode.extents.length * 8;\n }\n if (inode.kind === \"symlink\") {\n return SYMLINK_INODE_FIXED_BYTES + encodedUtf8Length(inode.target);\n }\n let bytes = DIRECTORY_INODE_FIXED_BYTES;\n for (const name of inode.children.keys()) {\n bytes += childBaseBytes(name);\n }\n return bytes;\n}\n\nexport function estimateMetadataBasePayloadBytes(state: VfsState): number {\n let bytes = BASE_STATE_FIXED_BYTES;\n for (const inode of state.inodes.values()) {\n bytes += inodeBaseBytes(inode);\n }\n bytes += state.allocator.available.size * 8;\n bytes += state.allocator.quarantine.size * 16;\n return bytes;\n}\n\nfunction extentRunsPayloadBytes(runs: readonly ExtentRun[]): number {\n return 4 + runs.length * 12;\n}\n\nexport function estimateTxnPayloadBytes(record: TxnRecord): number {\n switch (record.kind) {\n case \"createDirectories\":\n return 5 + record.entries.reduce((bytes, entry) => bytes + 8 + 2 + encodedUtf8Length(entry.name) + 8 + 4 + 24, 0);\n case \"createFile\":\n return 1 + 8 + 2 + encodedUtf8Length(record.name) + 8 + 4 + 24 + 8 + extentRunsPayloadBytes(record.extents);\n case \"removeFile\":\n case \"removeDirectory\":\n return 1 + 8 + 2 + encodedUtf8Length(record.name) + 16;\n case \"changeMode\":\n return 1 + 8 + 4 + 8;\n case \"changeTimes\":\n return 1 + 8 + 24;\n case \"resizeFile\":\n return 1 + 1 + 8 + 8 + extentRunsPayloadBytes(record.allocated) + 16;\n case \"rename\":\n return 1 + 8 + 2 + encodedUtf8Length(record.sourceName) + 8 + 2 + encodedUtf8Length(record.destinationName) + 8;\n case \"createSymlink\":\n return 1 + 8 + 2 + encodedUtf8Length(record.name) + 8 + 4 + 24 + 2 + encodedUtf8Length(record.target);\n case \"reserveQuarantine\":\n return 1 + extentRunsPayloadBytes(record.extents);\n }\n}\n\nfunction selectedExtentsAlreadyAvailable(state: VfsState, runs: readonly ExtentRun[]): number {\n let count = 0;\n for (const extentId of expandExtentRuns(runs, MAX_EXTENTS_PER_INODE)) {\n if (extentId < state.allocator.totalExtents) {\n count += 1;\n }\n }\n return count;\n}\n\nfunction projectedBaseDelta(state: VfsState, record: TxnRecord): number {\n switch (record.kind) {\n case \"createDirectories\":\n return record.entries.reduce(\n (bytes, entry) => bytes + DIRECTORY_INODE_FIXED_BYTES + childBaseBytes(entry.name),\n 0,\n );\n case \"createFile\": {\n const extentCount = expandExtentRuns(record.extents, MAX_EXTENTS_PER_INODE).length;\n const reused = selectedExtentsAlreadyAvailable(state, record.extents);\n return FILE_INODE_FIXED_BYTES + extentCount * 8 + childBaseBytes(record.name) - reused * 8;\n }\n case \"removeFile\": {\n const parent = directoryById(state, record.parentId);\n const inodeId = parent.children.get(record.name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined || inode.kind === \"directory\") {\n throw new FsError(\"ENOENT\", \"file does not exist\");\n }\n const quarantined = inode.kind === \"file\" ? inode.extents.length * 16 : 0;\n return -inodeBaseBytes(inode) - childBaseBytes(record.name) + quarantined;\n }\n case \"changeMode\":\n case \"changeTimes\":\n return 0;\n case \"resizeFile\": {\n const inode = fileById(state, record.inodeId);\n const required = extentCountForSize(record.size, state.extentSize);\n const allocatedCount = Math.max(0, required - inode.extents.length);\n const releasedCount = Math.max(0, inode.extents.length - required);\n const reused = selectedExtentsAlreadyAvailable(state, record.allocated);\n return (allocatedCount - releasedCount) * 8 - reused * 8 + releasedCount * 16;\n }\n case \"removeDirectory\": {\n const parent = directoryById(state, record.parentId);\n const inodeId = parent.children.get(record.name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode?.kind !== \"directory\") {\n throw new FsError(\"ENOENT\", \"directory does not exist\");\n }\n return -inodeBaseBytes(inode) - childBaseBytes(record.name);\n }\n case \"rename\": {\n const sourceParent = directoryById(state, record.sourceParentId);\n const destinationParent = directoryById(state, record.destinationParentId);\n const destinationId = destinationParent.children.get(record.destinationName);\n const destination = destinationId === undefined ? undefined : state.inodes.get(destinationId);\n let delta = -childBaseBytes(record.sourceName);\n if (destination === undefined) {\n delta += childBaseBytes(record.destinationName);\n } else {\n delta -= inodeBaseBytes(destination);\n if (destination.kind === \"file\") {\n delta += destination.extents.length * 16;\n }\n }\n const sourceId = sourceParent.children.get(record.sourceName);\n if (sourceId === undefined) {\n throw new FsError(\"ENOENT\", \"rename source does not exist\");\n }\n return delta;\n }\n case \"createSymlink\":\n return SYMLINK_INODE_FIXED_BYTES + encodedUtf8Length(record.target) + childBaseBytes(record.name);\n case \"reserveQuarantine\": {\n const count = expandExtentRuns(record.extents, MAX_EXTENTS_PER_INODE).length;\n const reused = selectedExtentsAlreadyAvailable(state, record.extents);\n return count * 16 - reused * 8;\n }\n }\n}\n\nexport function preflightTxn(\n state: VfsState,\n record: TxnRecord,\n limits: PreflightLimits = {\n maxFramePayloadBytes: MAX_FRAME_PAYLOAD_BYTES,\n maxBasePayloadBytes: MAX_METADATA_BASE_WRITER_BYTES,\n },\n): number {\n const payloadBytes = estimateTxnPayloadBytes(record);\n if (payloadBytes > limits.maxFramePayloadBytes) {\n throw new StoreLimitError(`transaction payload would exceed ${limits.maxFramePayloadBytes} bytes`);\n }\n const projected = state.basePayloadBytes + projectedBaseDelta(state, record);\n if (!Number.isSafeInteger(projected) || projected < 0 || projected > limits.maxBasePayloadBytes) {\n throw new StoreLimitError(`metadata base would exceed ${limits.maxBasePayloadBytes} bytes`);\n }\n return projected;\n}\n\nconst PREPARED_TXN_PROJECTION = Symbol(\"prepared transaction projection\");\n\nexport interface PreparedTxnProjection {\n readonly projectedBasePayloadBytes: number;\n readonly state: VfsState;\n readonly record: TxnRecord;\n readonly [PREPARED_TXN_PROJECTION]: true;\n}\n\n/** @internal Bind one projected size to the exact live state and record it preflighted. */\nexport function prepareTxnProjection(state: VfsState, record: TxnRecord): PreparedTxnProjection {\n return {\n projectedBasePayloadBytes: preflightTxn(state, record),\n state,\n record,\n [PREPARED_TXN_PROJECTION]: true,\n };\n}\n\nfunction checkedPlan<RecordType extends TxnRecord>(state: VfsState, record: RecordType): TxnPlan<RecordType> {\n preflightTxn(state, record);\n return { record };\n}\n\nexport function createInitialState(extentSize: number): VfsState {\n validateExtentSize(extentSize);\n const root: DirectoryInode = {\n id: 1n,\n kind: \"directory\",\n mode: 0o40777,\n atimeMs: 0n,\n mtimeMs: 0n,\n ctimeMs: 0n,\n children: new Map(),\n };\n return {\n generation: 1n,\n nextInodeId: 2n,\n rootInodeId: root.id,\n extentSize,\n activeMetadataFile: \"a\",\n retainedGenerations: { a: 1n, b: null },\n basePayloadBytes: BASE_STATE_FIXED_BYTES + DIRECTORY_INODE_FIXED_BYTES,\n inodes: new Map([[root.id, root]]),\n parentByInode: new Map(),\n allocator: {\n totalExtents: 0n,\n ownedBy: new Map(),\n available: new IndexedExtentSet(),\n quarantine: new Map(),\n },\n };\n}\n\nfunction validateMode(mode: number): number {\n if (!Number.isSafeInteger(mode) || mode < 0 || mode > 0xffff_ffff) {\n throw new FsError(\"EINVAL\", \"mode must be an unsigned 32-bit integer\");\n }\n return mode;\n}\n\nfunction validateTimestamp(timestamp: bigint): bigint {\n return checkedU64(timestamp, \"timestamp\");\n}\n\nfunction advanceNextInodeId(inodeId: InodeId): InodeId {\n if (inodeId === MAX_U64) {\n throw new StoreLimitError(\"next inode ID is exhausted; the store must be recreated\");\n }\n return checkedAdd(inodeId, 1n, \"next inode ID\");\n}\n\nfunction directoryById(state: VfsState, inodeId: InodeId): DirectoryInode {\n const inode = state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"directory does not exist\");\n }\n if (inode.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path component is not a directory\");\n }\n return inode;\n}\n\nfunction inodeById(state: VfsState, inodeId: InodeId): Inode {\n const inode = state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"inode does not exist\");\n }\n return inode;\n}\n\nfunction fileById(state: VfsState, inodeId: InodeId): FileInode {\n const inode = inodeById(state, inodeId);\n if (inode.kind !== \"file\") {\n throw new FsError(\"EISDIR\", \"inode is not a file\");\n }\n return inode;\n}\n\nfunction joinPath(base: string, rest: readonly string[]): string {\n if (rest.length === 0) return base;\n return base === \"/\" ? `/${rest.join(\"/\")}` : `${base}/${rest.join(\"/\")}`;\n}\n\nfunction parentAndName(state: VfsState, path: string): { parent: DirectoryInode; name: string } {\n const components = parsePath(path);\n const name = components.pop();\n if (name === undefined) {\n throw new FsError(\"EINVAL\", \"operation is not permitted on root\", { path });\n }\n let parent = directoryById(state, state.rootInodeId);\n for (const component of components) {\n const childId = parent.children.get(component);\n if (childId === undefined) {\n throw new FsError(\"ENOENT\", \"parent directory does not exist\", { path });\n }\n parent = directoryById(state, childId);\n }\n return { parent, name };\n}\n\nfunction extentCountForSize(size: bigint, extentSize: number): number {\n checkedU64(size, \"file size\");\n if (size === 0n) {\n return 0;\n }\n const count = (size + BigInt(extentSize) - 1n) / BigInt(extentSize);\n if (count > BigInt(MAX_EXTENTS_PER_INODE)) {\n throw new StoreLimitError(`file would exceed ${MAX_EXTENTS_PER_INODE} extents`);\n }\n return Number(count);\n}\n\nexport function toExtentRuns(extents: readonly ExtentId[]): ExtentRun[] {\n const runs: ExtentRun[] = [];\n for (const extentId of extents) {\n checkedU64(extentId, \"extent ID\");\n const last = runs.at(-1);\n if (last !== undefined && last.start + BigInt(last.count) === extentId && last.count < 0xffff_ffff) {\n last.count += 1;\n } else {\n runs.push({ start: extentId, count: 1 });\n }\n }\n return runs;\n}\n\nexport function expandExtentRuns(runs: readonly ExtentRun[], maximum: number): ExtentId[] {\n const extents: ExtentId[] = [];\n for (const run of runs) {\n checkedU64(run.start, \"extent run start\");\n if (!Number.isSafeInteger(run.count) || run.count <= 0) {\n throw new FsError(\"EINVAL\", \"extent run count must be a positive safe integer\");\n }\n if (extents.length + run.count > maximum) {\n throw new StoreLimitError(`extent list exceeds ${maximum} entries`);\n }\n for (let offset = 0; offset < run.count; offset += 1) {\n extents.push(checkedAdd(run.start, BigInt(offset), \"extent ID\"));\n }\n }\n return extents;\n}\n\nfunction chooseExtents(state: VfsState, count: number): ExtentId[] {\n if (count > MAX_EXTENTS_PER_INODE) {\n throw new StoreLimitError(`allocation exceeds ${MAX_EXTENTS_PER_INODE} extents`);\n }\n const availableCount = Math.min(count, state.allocator.available.size);\n const chosen = state.allocator.available.peekLast(availableCount);\n const freshCount = count - availableCount;\n if (state.allocator.totalExtents + BigInt(freshCount) > BigInt(MAX_TOTAL_EXTENTS)) {\n throw new StoreLimitError(`total extent count would exceed ${MAX_TOTAL_EXTENTS}`);\n }\n for (let offset = 0; offset < freshCount; offset += 1) {\n chosen.push(state.allocator.totalExtents + BigInt(offset));\n }\n return chosen;\n}\n\nexport function getInodeAtPath(state: VfsState, path: string): Inode {\n const components = parsePath(path);\n let inode = state.inodes.get(state.rootInodeId);\n if (inode === undefined) {\n throw new StoreLimitError(\"root inode is missing\");\n }\n for (const component of components) {\n if (inode.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path component is not a directory\", { path });\n }\n const childId = inode.children.get(component);\n if (childId === undefined) {\n throw new FsError(\"ENOENT\", \"path does not exist\", { path });\n }\n const child = state.inodes.get(childId);\n if (child === undefined) {\n throw new StoreLimitError(\"directory entry references a missing inode\");\n }\n inode = child;\n }\n return inode;\n}\n\n/**\n * Resolve every symbolic link on `path` and report the link-free absolute path it names.\n *\n * `follow` governs the FINAL component only — the POSIX `stat`/`lstat` split. Every INTERMEDIATE\n * link is always followed, because a path can only continue through the thing a link points at.\n *\n * A component that does not exist, or one whose parent turned out not to be a directory, stops the\n * walk and the remainder is carried through verbatim: resolution answers \"which path does this\n * name\", not \"does it exist\". The operation that follows reports `ENOENT`/`ENOTDIR` itself, or\n * creates the tail — which is exactly what an `open(O_CREAT)` through a symlinked directory needs.\n *\n * Targets are absolute, so a hop restarts the walk at the root. `MAX_SYMLINK_HOPS` hops is `ELOOP`,\n * and each expansion is re-validated by `parsePath`, so a chain that outgrows the store's depth or\n * byte limits is rejected here rather than in a planner.\n */\nexport function resolveLinks(state: VfsState, path: string, follow: boolean): string {\n const root = state.inodes.get(state.rootInodeId);\n if (root === undefined) {\n throw new StoreLimitError(\"root inode is missing\");\n }\n let pending = parsePath(path);\n let index = 0;\n let current: Inode = root;\n const resolved: string[] = [];\n let hops = 0;\n while (index < pending.length) {\n const name = pending[index]!;\n if (current.kind !== \"directory\") break;\n const childId = current.children.get(name);\n if (childId === undefined) break;\n const child = state.inodes.get(childId);\n if (child === undefined) {\n throw new StoreLimitError(\"directory entry references a missing inode\");\n }\n if (child.kind === \"symlink\" && (follow || index < pending.length - 1)) {\n hops += 1;\n if (hops > MAX_SYMLINK_HOPS) {\n throw new FsError(\"ELOOP\", `path traverses more than ${MAX_SYMLINK_HOPS} symbolic links`, { path });\n }\n pending = parsePath(joinPath(child.target, pending.slice(index + 1)));\n index = 0;\n current = root;\n resolved.length = 0;\n continue;\n }\n resolved.push(name);\n current = child;\n index += 1;\n }\n return joinPath(`/${resolved.join(\"/\")}`, pending.slice(index));\n}\n\nexport function planMkdir(\n state: VfsState,\n path: string,\n options: { recursive?: boolean; mode?: number; nowMs: bigint },\n): TxnPlan<Extract<TxnRecord, { kind: \"createDirectories\" }>> {\n const components = parsePath(path);\n if (components.length === 0) {\n throw new FsError(\"EEXIST\", \"root directory already exists\", { operation: \"mkdir\", path });\n }\n const mode = validateMode(options.mode ?? 0o40777);\n const nowMs = validateTimestamp(options.nowMs);\n const entries: CreateDirectoryChoice[] = [];\n let parent = directoryById(state, state.rootInodeId);\n let nextInodeId = state.nextInodeId;\n\n for (let index = 0; index < components.length; index += 1) {\n const name = components[index]!;\n const existingId = parent.children.get(name);\n if (existingId !== undefined) {\n const existing = state.inodes.get(existingId);\n if (existing?.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path component is not a directory\", { operation: \"mkdir\", path });\n }\n if (index === components.length - 1) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"mkdir\", path });\n }\n parent = existing;\n continue;\n }\n if (!options.recursive && index !== components.length - 1) {\n throw new FsError(\"ENOENT\", \"parent directory does not exist\", { operation: \"mkdir\", path });\n }\n if (state.inodes.size + entries.length >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n checkedU64(nextInodeId, \"next inode ID\");\n const followingInodeId = advanceNextInodeId(nextInodeId);\n const entry: CreateDirectoryChoice = {\n parentId: parent.id,\n name,\n inodeId: nextInodeId,\n mode,\n atimeMs: nowMs,\n mtimeMs: nowMs,\n ctimeMs: nowMs,\n };\n entries.push(entry);\n parent = { ...entry, kind: \"directory\", id: entry.inodeId, children: new Map() };\n nextInodeId = followingInodeId;\n }\n\n if (entries.length === 0) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"mkdir\", path });\n }\n return checkedPlan(state, { kind: \"createDirectories\", entries });\n}\n\nexport function planCreateFile(\n state: VfsState,\n path: string,\n options: { mode?: number; nowMs: bigint; size?: bigint },\n): TxnPlan<Extract<TxnRecord, { kind: \"createFile\" }>> {\n const { parent, name } = parentAndName(state, path);\n if (parent.children.has(name)) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"writeFile\", path });\n }\n if (state.inodes.size >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n const inodeId = checkedU64(state.nextInodeId, \"next inode ID\");\n advanceNextInodeId(inodeId);\n const mode = validateMode(options.mode ?? 0o100666);\n const nowMs = validateTimestamp(options.nowMs);\n const size = checkedU64(options.size ?? 0n, \"file size\");\n const extents = toExtentRuns(chooseExtents(state, extentCountForSize(size, state.extentSize)));\n return checkedPlan(state, {\n kind: \"createFile\",\n parentId: parent.id,\n name,\n inodeId,\n mode,\n atimeMs: nowMs,\n mtimeMs: nowMs,\n ctimeMs: nowMs,\n size,\n extents,\n });\n}\n\n/** A symbolic link. Nothing about the TARGET is consulted — the link entry is the whole record. */\nexport function planSymlink(\n state: VfsState,\n path: string,\n target: string,\n options: { mode?: number; nowMs: bigint },\n): TxnPlan<Extract<TxnRecord, { kind: \"createSymlink\" }>> {\n const { parent, name } = parentAndName(state, path);\n if (parent.children.has(name)) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"symlink\", path });\n }\n if (state.inodes.size >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n validateSymlinkTarget(target);\n const inodeId = checkedU64(state.nextInodeId, \"next inode ID\");\n advanceNextInodeId(inodeId);\n const nowMs = validateTimestamp(options.nowMs);\n return checkedPlan(state, {\n kind: \"createSymlink\",\n parentId: parent.id,\n name,\n inodeId,\n mode: validateMode(options.mode ?? SYMLINK_MODE),\n atimeMs: nowMs,\n mtimeMs: nowMs,\n ctimeMs: nowMs,\n target,\n });\n}\n\n/** Removes a FILE or a SYMBOLIC LINK. A link is unlinked as itself; its target is never touched. */\nexport function planUnlink(\n state: VfsState,\n path: string,\n nowMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"removeFile\" }>> {\n const { parent, name } = parentAndName(state, path);\n const inodeId = parent.children.get(name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"path does not exist\", { operation: \"unlink\", path });\n }\n if (inode.kind === \"directory\") {\n throw new FsError(\"EISDIR\", \"path is a directory\", { operation: \"unlink\", path });\n }\n const timestamp = validateTimestamp(nowMs);\n return checkedPlan(state, {\n kind: \"removeFile\",\n parentId: parent.id,\n name,\n parentMtimeMs: timestamp,\n parentCtimeMs: timestamp,\n });\n}\n\nexport function planChmod(\n state: VfsState,\n path: string,\n mode: number,\n nowMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"changeMode\" }>> {\n const inode = getInodeAtPath(state, path);\n return checkedPlan(state, {\n kind: \"changeMode\",\n inodeId: inode.id,\n mode: validateMode(mode),\n ctimeMs: validateTimestamp(nowMs),\n });\n}\n\nexport function planUtimes(\n state: VfsState,\n path: string,\n atimeMs: bigint,\n mtimeMs: bigint,\n ctimeMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"changeTimes\" }>> {\n const inode = getInodeAtPath(state, path);\n return checkedPlan(state, {\n kind: \"changeTimes\",\n inodeId: inode.id,\n atimeMs: validateTimestamp(atimeMs),\n mtimeMs: validateTimestamp(mtimeMs),\n ctimeMs: validateTimestamp(ctimeMs),\n });\n}\n\nexport function planResizeFile(\n state: VfsState,\n path: string,\n size: bigint,\n nowMs: bigint,\n operation: \"truncate\" | \"write\",\n): TxnPlan<Extract<TxnRecord, { kind: \"resizeFile\" }>> {\n const inode = getInodeAtPath(state, path);\n if (inode.kind !== \"file\") {\n throw new FsError(\"EISDIR\", \"path is a directory\", { operation, path });\n }\n return planResizeFileForInode(state, inode, size, nowMs, operation);\n}\n\n/** @internal Inode-first planner for descriptor operations that already resolved the file. */\nexport function planResizeFileForInode(\n state: VfsState,\n inode: FileInode,\n size: bigint,\n nowMs: bigint,\n operation: \"truncate\" | \"write\",\n): TxnPlan<Extract<TxnRecord, { kind: \"resizeFile\" }>> {\n if (state.inodes.get(inode.id) !== inode) {\n throw new StoreLimitError(\"resize planner requires the current file inode\");\n }\n const checkedSize = checkedU64(size, \"file size\");\n const required = extentCountForSize(checkedSize, state.extentSize);\n const additional = Math.max(0, required - inode.extents.length);\n const timestamp = validateTimestamp(nowMs);\n return checkedPlan(state, {\n kind: \"resizeFile\",\n operation,\n inodeId: inode.id,\n size: checkedSize,\n allocated: toExtentRuns(chooseExtents(state, additional)),\n mtimeMs: timestamp,\n ctimeMs: timestamp,\n });\n}\n\nexport function planRmdir(\n state: VfsState,\n path: string,\n nowMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"removeDirectory\" }>> {\n const { parent, name } = parentAndName(state, path);\n const inodeId = parent.children.get(name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"directory does not exist\", { operation: \"rmdir\", path });\n }\n if (inode.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path is not a directory\", { operation: \"rmdir\", path });\n }\n if (inode.children.size !== 0) {\n throw new FsError(\"ENOTEMPTY\", \"directory is not empty\", { operation: \"rmdir\", path });\n }\n const timestamp = validateTimestamp(nowMs);\n return checkedPlan(state, {\n kind: \"removeDirectory\",\n parentId: parent.id,\n name,\n parentMtimeMs: timestamp,\n parentCtimeMs: timestamp,\n });\n}\n\nfunction directoryContains(state: VfsState, directory: DirectoryInode, candidateId: InodeId): boolean {\n if (directory.id === candidateId) {\n return true;\n }\n for (const childId of directory.children.values()) {\n const child = inodeById(state, childId);\n if (child.kind === \"directory\" && directoryContains(state, child, candidateId)) {\n return true;\n }\n }\n return false;\n}\n\ninterface PathMetrics {\n depth: number;\n bytes: number;\n}\n\nfunction childPathMetrics(parent: PathMetrics, name: string): PathMetrics {\n return {\n depth: parent.depth + 1,\n bytes: parent.bytes + (parent.depth === 0 ? 0 : 1) + encodedUtf8Length(name),\n };\n}\n\nfunction findPathMetrics(state: VfsState, targetId: InodeId): PathMetrics {\n let currentId = targetId;\n let depth = 0;\n let componentBytes = 0;\n const visited = new Set<InodeId>();\n while (currentId !== state.rootInodeId) {\n if (visited.has(currentId)) {\n throw new StoreLimitError(\"inode parent index contains a cycle\");\n }\n visited.add(currentId);\n const entry = state.parentByInode.get(currentId);\n if (entry === undefined) {\n throw new StoreLimitError(\"inode parent index does not reach root\");\n }\n depth += 1;\n componentBytes += encodedUtf8Length(entry.name);\n currentId = entry.parentId;\n }\n return { depth, bytes: 1 + componentBytes + Math.max(0, depth - 1) };\n}\n\nfunction validateRenamedSubtreeBounds(\n state: VfsState,\n source: Inode,\n destinationParent: DirectoryInode,\n destinationName: string,\n): void {\n const visit = (inode: Inode, metrics: PathMetrics): void => {\n if (metrics.depth > MAX_PATH_DEPTH) {\n throw new FsError(\"EINVAL\", `rename would exceed ${MAX_PATH_DEPTH} path components`);\n }\n if (metrics.bytes > MAX_PATH_BYTES) {\n throw new FsError(\"EINVAL\", `rename would exceed ${MAX_PATH_BYTES} UTF-8 path bytes`);\n }\n if (inode.kind === \"directory\") {\n for (const [name, childId] of inode.children) {\n visit(inodeById(state, childId), childPathMetrics(metrics, name));\n }\n }\n };\n const destinationMetrics = findPathMetrics(state, destinationParent.id);\n visit(source, childPathMetrics(destinationMetrics, destinationName));\n}\n\nfunction validateRenameTypes(source: Inode, destination: Inode | undefined): void {\n if (destination === undefined) {\n return;\n }\n if (source.kind !== \"directory\" && destination.kind === \"directory\") {\n throw new FsError(\"EISDIR\", \"cannot replace a directory with a file\");\n }\n if (source.kind === \"directory\" && destination.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"cannot replace a file with a directory\");\n }\n if (destination.kind === \"directory\" && destination.children.size !== 0) {\n throw new FsError(\"ENOTEMPTY\", \"destination directory is not empty\");\n }\n}\n\nexport function planRename(\n state: VfsState,\n oldPath: string,\n newPath: string,\n nowMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"rename\" }>> {\n if (oldPath === newPath) {\n throw new FsError(\"EINVAL\", \"source and destination are identical\", { operation: \"rename\", path: oldPath });\n }\n const sourceLocation = parentAndName(state, oldPath);\n const destinationLocation = parentAndName(state, newPath);\n const sourceId = sourceLocation.parent.children.get(sourceLocation.name);\n if (sourceId === undefined) {\n throw new FsError(\"ENOENT\", \"rename source does not exist\", { operation: \"rename\", path: oldPath });\n }\n const source = inodeById(state, sourceId);\n const destinationId = destinationLocation.parent.children.get(destinationLocation.name);\n const destination = destinationId === undefined ? undefined : inodeById(state, destinationId);\n validateRenameTypes(source, destination);\n if (source.kind === \"directory\" && directoryContains(state, source, destinationLocation.parent.id)) {\n throw new FsError(\"EINVAL\", \"cannot move a directory into itself\", { operation: \"rename\", path: newPath });\n }\n validateRenamedSubtreeBounds(state, source, destinationLocation.parent, destinationLocation.name);\n return checkedPlan(state, {\n kind: \"rename\",\n sourceParentId: sourceLocation.parent.id,\n sourceName: sourceLocation.name,\n destinationParentId: destinationLocation.parent.id,\n destinationName: destinationLocation.name,\n timestampMs: validateTimestamp(nowMs),\n });\n}\n\nexport function planReserveQuarantine(\n state: VfsState,\n count: number,\n): TxnPlan<Extract<TxnRecord, { kind: \"reserveQuarantine\" }>> {\n if (!Number.isSafeInteger(count) || count <= 0 || count > MAX_EXTENTS_PER_INODE) {\n throw new StoreLimitError(`orphan reservation must contain 1 to ${MAX_EXTENTS_PER_INODE} extents`);\n }\n return checkedPlan(state, {\n kind: \"reserveQuarantine\",\n extents: toExtentRuns(chooseExtents(state, count)),\n });\n}\n\nfunction validateCreateDirectories(state: VfsState, entries: readonly CreateDirectoryChoice[]): void {\n if (entries.length === 0) {\n throw new FsError(\"EINVAL\", \"createDirectories record is empty\");\n }\n const staged = new Map<InodeId, DirectoryInode>();\n const stagedDirectory = (inodeId: InodeId): DirectoryInode => {\n const alreadyStaged = staged.get(inodeId);\n if (alreadyStaged !== undefined) {\n return alreadyStaged;\n }\n const existing = directoryById(state, inodeId);\n const copy = { ...existing, children: new Map(existing.children) };\n staged.set(inodeId, copy);\n return copy;\n };\n let expectedInodeId = state.nextInodeId;\n for (const entry of entries) {\n validatePathComponent(entry.name);\n validateMode(entry.mode);\n validateTimestamp(entry.atimeMs);\n validateTimestamp(entry.mtimeMs);\n validateTimestamp(entry.ctimeMs);\n if (entry.inodeId !== expectedInodeId || entry.inodeId > MAX_U64) {\n throw new FsError(\"EINVAL\", \"createDirectories record has a non-canonical inode sequence\");\n }\n const parent = stagedDirectory(entry.parentId);\n if (parent.children.has(entry.name)) {\n throw new FsError(\"EEXIST\", \"directory entry already exists\");\n }\n const created: DirectoryInode = {\n id: entry.inodeId,\n kind: \"directory\",\n mode: entry.mode,\n atimeMs: entry.atimeMs,\n mtimeMs: entry.mtimeMs,\n ctimeMs: entry.ctimeMs,\n children: new Map(),\n };\n parent.children.set(entry.name, entry.inodeId);\n staged.set(entry.inodeId, created);\n expectedInodeId = advanceNextInodeId(expectedInodeId);\n }\n if (state.inodes.size + entries.length > MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n}\n\nfunction validateExtentAssignment(state: VfsState, runs: readonly ExtentRun[], expectedCount: number): ExtentId[] {\n const extents = expandExtentRuns(runs, MAX_EXTENTS_PER_INODE);\n if (extents.length !== expectedCount) {\n throw new FsError(\"EINVAL\", \"extent choices do not cover the file size exactly\");\n }\n const unique = new Set(extents);\n if (unique.size !== extents.length) {\n throw new FsError(\"EINVAL\", \"extent choices contain a duplicate\");\n }\n let nextFresh = state.allocator.totalExtents;\n for (const extentId of extents) {\n if (extentId < state.allocator.totalExtents) {\n if (!state.allocator.available.has(extentId)) {\n throw new FsError(\"EINVAL\", \"extent choice is not safely available\");\n }\n continue;\n }\n if (extentId !== nextFresh) {\n throw new FsError(\"EINVAL\", \"fresh extent choices must grow the arena contiguously\");\n }\n nextFresh += 1n;\n }\n if (nextFresh > BigInt(MAX_TOTAL_EXTENTS)) {\n throw new StoreLimitError(`total extent count would exceed ${MAX_TOTAL_EXTENTS}`);\n }\n return extents;\n}\n\nfunction applyCreateFile(state: VfsState, record: Extract<TxnRecord, { kind: \"createFile\" }>): void {\n validatePathComponent(record.name);\n const parent = directoryById(state, record.parentId);\n if (parent.children.has(record.name)) {\n throw new FsError(\"EEXIST\", \"directory entry already exists\");\n }\n if (record.inodeId !== state.nextInodeId || state.inodes.has(record.inodeId)) {\n throw new FsError(\"EINVAL\", \"createFile record has a non-canonical inode ID\");\n }\n const nextInodeId = advanceNextInodeId(record.inodeId);\n validateMode(record.mode);\n validateTimestamp(record.atimeMs);\n validateTimestamp(record.mtimeMs);\n validateTimestamp(record.ctimeMs);\n const size = checkedU64(record.size, \"file size\");\n const extents = validateExtentAssignment(state, record.extents, extentCountForSize(size, state.extentSize));\n if (state.inodes.size >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n\n const inode: FileInode = {\n id: record.inodeId,\n kind: \"file\",\n mode: record.mode,\n atimeMs: record.atimeMs,\n mtimeMs: record.mtimeMs,\n ctimeMs: record.ctimeMs,\n size,\n extents,\n };\n for (const extentId of extents) {\n if (extentId < state.allocator.totalExtents) {\n state.allocator.available.delete(extentId);\n } else {\n state.allocator.totalExtents += 1n;\n }\n state.allocator.ownedBy.set(extentId, inode.id);\n }\n parent.children.set(record.name, inode.id);\n state.inodes.set(inode.id, inode);\n state.parentByInode.set(inode.id, { parentId: parent.id, name: record.name });\n state.nextInodeId = nextInodeId;\n}\n\nfunction applyRemoveFile(state: VfsState, record: Extract<TxnRecord, { kind: \"removeFile\" }>): void {\n validatePathComponent(record.name);\n validateTimestamp(record.parentMtimeMs);\n validateTimestamp(record.parentCtimeMs);\n const parent = directoryById(state, record.parentId);\n const inodeId = parent.children.get(record.name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"file does not exist\");\n }\n if (inode.kind === \"directory\") {\n throw new FsError(\"EISDIR\", \"path is a directory\");\n }\n const extents = inode.kind === \"file\" ? inode.extents : [];\n for (const extentId of extents) {\n if (state.allocator.ownedBy.get(extentId) !== inode.id || state.allocator.quarantine.has(extentId)) {\n throw new StoreLimitError(\"file extent ownership is inconsistent\");\n }\n }\n\n parent.children.delete(record.name);\n parent.mtimeMs = record.parentMtimeMs;\n parent.ctimeMs = record.parentCtimeMs;\n state.inodes.delete(inode.id);\n state.parentByInode.delete(inode.id);\n for (const extentId of extents) {\n state.allocator.ownedBy.delete(extentId);\n state.allocator.quarantine.set(extentId, null);\n }\n}\n\nfunction applyCreateSymlink(state: VfsState, record: Extract<TxnRecord, { kind: \"createSymlink\" }>): void {\n validatePathComponent(record.name);\n const parent = directoryById(state, record.parentId);\n if (parent.children.has(record.name)) {\n throw new FsError(\"EEXIST\", \"directory entry already exists\");\n }\n if (record.inodeId !== state.nextInodeId || state.inodes.has(record.inodeId)) {\n throw new FsError(\"EINVAL\", \"createSymlink record has a non-canonical inode ID\");\n }\n const nextInodeId = advanceNextInodeId(record.inodeId);\n validateMode(record.mode);\n validateTimestamp(record.atimeMs);\n validateTimestamp(record.mtimeMs);\n validateTimestamp(record.ctimeMs);\n validateSymlinkTarget(record.target);\n if (state.inodes.size >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n const inode: SymlinkInode = {\n id: record.inodeId,\n kind: \"symlink\",\n mode: record.mode,\n atimeMs: record.atimeMs,\n mtimeMs: record.mtimeMs,\n ctimeMs: record.ctimeMs,\n target: record.target,\n };\n parent.children.set(record.name, inode.id);\n state.inodes.set(inode.id, inode);\n state.parentByInode.set(inode.id, { parentId: parent.id, name: record.name });\n state.nextInodeId = nextInodeId;\n}\n\nfunction applyChangeMode(state: VfsState, record: Extract<TxnRecord, { kind: \"changeMode\" }>): void {\n const inode = inodeById(state, record.inodeId);\n const mode = validateMode(record.mode);\n const ctimeMs = validateTimestamp(record.ctimeMs);\n inode.mode = mode;\n inode.ctimeMs = ctimeMs;\n}\n\nfunction applyChangeTimes(state: VfsState, record: Extract<TxnRecord, { kind: \"changeTimes\" }>): void {\n const inode = inodeById(state, record.inodeId);\n const atimeMs = validateTimestamp(record.atimeMs);\n const mtimeMs = validateTimestamp(record.mtimeMs);\n const ctimeMs = validateTimestamp(record.ctimeMs);\n inode.atimeMs = atimeMs;\n inode.mtimeMs = mtimeMs;\n inode.ctimeMs = ctimeMs;\n}\n\nfunction applyResizeFile(state: VfsState, record: Extract<TxnRecord, { kind: \"resizeFile\" }>): void {\n const inode = fileById(state, record.inodeId);\n const size = checkedU64(record.size, \"file size\");\n const required = extentCountForSize(size, state.extentSize);\n const additionalCount = Math.max(0, required - inode.extents.length);\n const allocated = validateExtentAssignment(state, record.allocated, additionalCount);\n const retained = required >= inode.extents.length ? inode.extents : inode.extents.slice(0, required);\n const released = inode.extents.slice(required);\n for (const extentId of released) {\n if (state.allocator.ownedBy.get(extentId) !== inode.id || state.allocator.quarantine.has(extentId)) {\n throw new StoreLimitError(\"file extent ownership is inconsistent\");\n }\n }\n const mtimeMs = validateTimestamp(record.mtimeMs);\n const ctimeMs = validateTimestamp(record.ctimeMs);\n\n for (const extentId of allocated) {\n if (extentId < state.allocator.totalExtents) {\n state.allocator.available.delete(extentId);\n } else {\n state.allocator.totalExtents += 1n;\n }\n state.allocator.ownedBy.set(extentId, inode.id);\n retained.push(extentId);\n }\n for (const extentId of released) {\n state.allocator.ownedBy.delete(extentId);\n state.allocator.quarantine.set(extentId, null);\n }\n inode.size = size;\n inode.extents = retained;\n inode.mtimeMs = mtimeMs;\n inode.ctimeMs = ctimeMs;\n}\n\nfunction applyRemoveDirectory(state: VfsState, record: Extract<TxnRecord, { kind: \"removeDirectory\" }>): void {\n validatePathComponent(record.name);\n const parent = directoryById(state, record.parentId);\n const inodeId = parent.children.get(record.name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"directory does not exist\");\n }\n if (inode.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path is not a directory\");\n }\n if (inode.children.size !== 0) {\n throw new FsError(\"ENOTEMPTY\", \"directory is not empty\");\n }\n const mtimeMs = validateTimestamp(record.parentMtimeMs);\n const ctimeMs = validateTimestamp(record.parentCtimeMs);\n parent.children.delete(record.name);\n parent.mtimeMs = mtimeMs;\n parent.ctimeMs = ctimeMs;\n state.inodes.delete(inode.id);\n state.parentByInode.delete(inode.id);\n}\n\nfunction applyRename(state: VfsState, record: Extract<TxnRecord, { kind: \"rename\" }>): void {\n validatePathComponent(record.sourceName);\n validatePathComponent(record.destinationName);\n if (record.sourceParentId === record.destinationParentId && record.sourceName === record.destinationName) {\n throw new FsError(\"EINVAL\", \"rename source and destination are identical\");\n }\n const timestampMs = validateTimestamp(record.timestampMs);\n const sourceParent = directoryById(state, record.sourceParentId);\n const destinationParent = directoryById(state, record.destinationParentId);\n const sourceId = sourceParent.children.get(record.sourceName);\n if (sourceId === undefined) {\n throw new FsError(\"ENOENT\", \"rename source does not exist\");\n }\n const source = inodeById(state, sourceId);\n const destinationId = destinationParent.children.get(record.destinationName);\n const destination = destinationId === undefined ? undefined : inodeById(state, destinationId);\n validateRenameTypes(source, destination);\n if (source.kind === \"directory\" && directoryContains(state, source, destinationParent.id)) {\n throw new FsError(\"EINVAL\", \"cannot move a directory into itself\");\n }\n validateRenamedSubtreeBounds(state, source, destinationParent, record.destinationName);\n if (destination?.kind === \"file\") {\n for (const extentId of destination.extents) {\n if (state.allocator.ownedBy.get(extentId) !== destination.id || state.allocator.quarantine.has(extentId)) {\n throw new StoreLimitError(\"replacement extent ownership is inconsistent\");\n }\n }\n }\n\n sourceParent.children.delete(record.sourceName);\n if (destination !== undefined) {\n destinationParent.children.delete(record.destinationName);\n state.inodes.delete(destination.id);\n state.parentByInode.delete(destination.id);\n if (destination.kind === \"file\") {\n for (const extentId of destination.extents) {\n state.allocator.ownedBy.delete(extentId);\n state.allocator.quarantine.set(extentId, null);\n }\n }\n }\n destinationParent.children.set(record.destinationName, source.id);\n state.parentByInode.set(source.id, {\n parentId: destinationParent.id,\n name: record.destinationName,\n });\n source.ctimeMs = timestampMs;\n sourceParent.mtimeMs = timestampMs;\n sourceParent.ctimeMs = timestampMs;\n destinationParent.mtimeMs = timestampMs;\n destinationParent.ctimeMs = timestampMs;\n}\n\nfunction applyReserveQuarantine(state: VfsState, record: Extract<TxnRecord, { kind: \"reserveQuarantine\" }>): void {\n const declaredCount = record.extents.reduce((sum, run) => sum + run.count, 0);\n if (declaredCount <= 0 || declaredCount > MAX_EXTENTS_PER_INODE) {\n throw new StoreLimitError(\"orphan reservation extent count is outside limits\");\n }\n const extents = validateExtentAssignment(state, record.extents, declaredCount);\n for (const extentId of extents) {\n if (extentId < state.allocator.totalExtents) {\n state.allocator.available.delete(extentId);\n } else {\n state.allocator.totalExtents += 1n;\n }\n state.allocator.quarantine.set(extentId, null);\n }\n}\n\nexport function applyTxn(state: VfsState, record: TxnRecord, prepared?: PreparedTxnProjection): void {\n if (\n prepared !== undefined &&\n (prepared[PREPARED_TXN_PROJECTION] !== true || prepared.state !== state || prepared.record !== record)\n ) {\n throw new StoreLimitError(\"prepared transaction projection does not match the live transition\");\n }\n const projectedBasePayloadBytes = prepared?.projectedBasePayloadBytes ?? preflightTxn(state, record);\n switch (record.kind) {\n case \"createDirectories\":\n validateCreateDirectories(state, record.entries);\n for (const entry of record.entries) {\n const parent = directoryById(state, entry.parentId);\n const created: DirectoryInode = {\n id: entry.inodeId,\n kind: \"directory\",\n mode: entry.mode,\n atimeMs: entry.atimeMs,\n mtimeMs: entry.mtimeMs,\n ctimeMs: entry.ctimeMs,\n children: new Map(),\n };\n parent.children.set(entry.name, created.id);\n state.inodes.set(created.id, created);\n state.parentByInode.set(created.id, { parentId: parent.id, name: entry.name });\n state.nextInodeId = advanceNextInodeId(created.id);\n }\n break;\n case \"createFile\":\n applyCreateFile(state, record);\n break;\n case \"removeFile\":\n applyRemoveFile(state, record);\n break;\n case \"changeMode\":\n applyChangeMode(state, record);\n break;\n case \"changeTimes\":\n applyChangeTimes(state, record);\n break;\n case \"resizeFile\":\n applyResizeFile(state, record);\n break;\n case \"removeDirectory\":\n applyRemoveDirectory(state, record);\n break;\n case \"rename\":\n applyRename(state, record);\n break;\n case \"createSymlink\":\n applyCreateSymlink(state, record);\n break;\n case \"reserveQuarantine\":\n applyReserveQuarantine(state, record);\n break;\n }\n state.basePayloadBytes = projectedBasePayloadBytes;\n}\n\nfunction cloneState(state: VfsState): VfsState {\n return {\n ...state,\n retainedGenerations: { ...state.retainedGenerations },\n inodes: new Map(\n [...state.inodes].map(([inodeId, inode]) => [\n inodeId,\n inode.kind === \"directory\"\n ? { ...inode, children: new Map(inode.children) }\n : inode.kind === \"file\"\n ? { ...inode, extents: [...inode.extents] }\n : { ...inode },\n ]),\n ),\n parentByInode: new Map([...state.parentByInode].map(([inodeId, entry]) => [inodeId, { ...entry }])),\n allocator: {\n totalExtents: state.allocator.totalExtents,\n ownedBy: new Map(state.allocator.ownedBy),\n available: state.allocator.available.clone(),\n quarantine: new Map(state.allocator.quarantine),\n },\n };\n}\n\nfunction projectRepackFromCopy(\n state: VfsState,\n projected: VfsState,\n pinnedQuarantine: ReadonlySet<ExtentId>,\n): VfsState {\n // Activated/recovered state and every live reducer transition are already validated.\n // The projected result is validated below before its canonical base can be activated.\n if (state.generation === MAX_U64) {\n throw new StoreLimitError(\"generation is exhausted; the store must be recreated\");\n }\n let projectedBasePayloadBytes = state.basePayloadBytes;\n const nextGeneration = state.generation + 1n;\n const target = otherMetadataFile(state.activeMetadataFile);\n const targetPreviousGeneration = state.retainedGenerations[target];\n for (const [extentId, firstExcludedGeneration] of projected.allocator.quarantine) {\n if (pinnedQuarantine.has(extentId)) {\n projected.allocator.quarantine.set(extentId, null);\n } else if (firstExcludedGeneration === null) {\n projected.allocator.quarantine.set(extentId, nextGeneration);\n } else if (targetPreviousGeneration === null || targetPreviousGeneration < firstExcludedGeneration) {\n projected.allocator.quarantine.delete(extentId);\n projected.allocator.available.add(extentId);\n projectedBasePayloadBytes -= 8;\n }\n }\n while (projected.allocator.totalExtents > 0n) {\n const tail = projected.allocator.totalExtents - 1n;\n if (!projected.allocator.available.delete(tail)) break;\n projected.allocator.totalExtents = tail;\n projectedBasePayloadBytes -= 8;\n }\n projected.generation = nextGeneration;\n projected.activeMetadataFile = target;\n projected.retainedGenerations[target] = nextGeneration;\n projected.basePayloadBytes = projectedBasePayloadBytes;\n validateState(projected);\n return projected;\n}\n\nexport function projectRepack(state: VfsState, pinnedQuarantine: ReadonlySet<ExtentId> = new Set()): VfsState {\n return projectRepackFromCopy(state, cloneState(state), pinnedQuarantine);\n}\n\n/**\n * @internal Activation-only projection. Structures repack never mutates are shared read-only until\n * durable activation; allocator and generation structures remain isolated from the live state.\n */\nexport function projectRepackForActivation(\n state: VfsState,\n pinnedQuarantine: ReadonlySet<ExtentId> = new Set(),\n): VfsState {\n const projected: VfsState = {\n ...state,\n retainedGenerations: { ...state.retainedGenerations },\n inodes: state.inodes,\n parentByInode: state.parentByInode,\n allocator: {\n totalExtents: state.allocator.totalExtents,\n ownedBy: state.allocator.ownedBy,\n available: state.allocator.available.clone(),\n quarantine: new Map(state.allocator.quarantine),\n },\n };\n return projectRepackFromCopy(state, projected, pinnedQuarantine);\n}\n\nexport function validateState(state: VfsState): void {\n validateExtentSize(state.extentSize);\n checkedU64(state.generation, \"generation\");\n if (state.generation === 0n) {\n throw new StoreLimitError(\"generation must be positive\");\n }\n checkedU64(state.nextInodeId, \"next inode ID\");\n const root = state.inodes.get(state.rootInodeId);\n if (root?.kind !== \"directory\") {\n throw new StoreLimitError(\"root inode is missing or is not a directory\");\n }\n if (state.parentByInode.has(state.rootInodeId)) {\n throw new StoreLimitError(\"root inode must not have a parent entry\");\n }\n if (state.inodes.size > MAX_INODES) {\n throw new StoreLimitError(`inode count exceeds ${MAX_INODES}`);\n }\n checkedU64(state.allocator.totalExtents, \"total extent count\");\n if (state.allocator.totalExtents > BigInt(MAX_TOTAL_EXTENTS)) {\n throw new StoreLimitError(`total extent count exceeds ${MAX_TOTAL_EXTENTS}`);\n }\n const classified = new Uint8Array(Number(state.allocator.totalExtents));\n let classifiedCount = 0;\n const classify = (extentId: ExtentId, label: string): void => {\n if (extentId < 0n || extentId >= state.allocator.totalExtents) {\n throw new StoreLimitError(`${label} extent is out of range or multiply classified`);\n }\n const index = Number(extentId);\n if (classified[index] !== 0) {\n throw new StoreLimitError(`${label} extent is out of range or multiply classified`);\n }\n classified[index] = 1;\n classifiedCount += 1;\n };\n const reached = new Set<InodeId>();\n let calculatedBasePayloadBytes = BASE_STATE_FIXED_BYTES;\n const visit = (inodeKey: InodeId, inode: Inode, metrics: PathMetrics): void => {\n checkedU64(inodeKey, \"inode map key\");\n checkedU64(inode.id, \"inode ID\");\n if (inodeKey !== inode.id) {\n throw new StoreLimitError(\"inode map key does not match the inode ID\");\n }\n if (inode.id >= state.nextInodeId) {\n throw new StoreLimitError(\"inode ID is not below the unused next inode ID\");\n }\n if (reached.has(inode.id)) {\n throw new StoreLimitError(\"inode has more than one directory owner\");\n }\n reached.add(inode.id);\n validateMode(inode.mode);\n validateTimestamp(inode.atimeMs);\n validateTimestamp(inode.mtimeMs);\n validateTimestamp(inode.ctimeMs);\n if (inode.kind === \"directory\") {\n calculatedBasePayloadBytes += DIRECTORY_INODE_FIXED_BYTES;\n for (const [name, childId] of inode.children) {\n const nameBytes = validatePathComponent(name);\n calculatedBasePayloadBytes += CHILD_FIXED_BYTES + nameBytes;\n const parentEntry = state.parentByInode.get(childId);\n if (parentEntry?.parentId !== inode.id || parentEntry.name !== name) {\n throw new StoreLimitError(\"inode parent index does not match its directory entry\");\n }\n const childMetrics = {\n depth: metrics.depth + 1,\n bytes: metrics.bytes + (metrics.depth === 0 ? 0 : 1) + nameBytes,\n };\n if (childMetrics.depth > MAX_PATH_DEPTH) {\n throw new StoreLimitError(`inode path exceeds ${MAX_PATH_DEPTH} components`);\n }\n if (childMetrics.bytes > MAX_PATH_BYTES) {\n throw new StoreLimitError(`inode path exceeds ${MAX_PATH_BYTES} UTF-8 bytes`);\n }\n const child = state.inodes.get(childId);\n if (child === undefined) {\n throw new StoreLimitError(\"directory entry references a missing inode\");\n }\n visit(childId, child, childMetrics);\n }\n } else if (inode.kind === \"symlink\") {\n let targetBytes: number;\n try {\n targetBytes = validateSymlinkTarget(inode.target);\n } catch (cause) {\n throw new StoreLimitError(`symlink target is invalid: ${String(cause)}`, { cause });\n }\n calculatedBasePayloadBytes += SYMLINK_INODE_FIXED_BYTES + targetBytes;\n } else {\n calculatedBasePayloadBytes += FILE_INODE_FIXED_BYTES + inode.extents.length * 8;\n if (inode.extents.length !== extentCountForSize(inode.size, state.extentSize)) {\n throw new StoreLimitError(\"file extent count does not cover its size exactly\");\n }\n for (const extentId of inode.extents) {\n classify(extentId, \"owned\");\n if (state.allocator.ownedBy.get(extentId) !== inode.id) {\n throw new StoreLimitError(\"owned extent does not map back to its inode\");\n }\n }\n }\n };\n visit(state.rootInodeId, root, { depth: 0, bytes: 1 });\n if (reached.size !== state.inodes.size) {\n throw new StoreLimitError(\"inode graph contains unreachable inodes\");\n }\n if (state.parentByInode.size !== state.inodes.size - 1) {\n throw new StoreLimitError(\"inode parent index does not cover every non-root inode\");\n }\n if (classifiedCount !== state.allocator.ownedBy.size) {\n throw new StoreLimitError(\"allocator contains an owner not referenced by a file\");\n }\n calculatedBasePayloadBytes += state.allocator.available.size * 8 + state.allocator.quarantine.size * 16;\n if (state.basePayloadBytes !== calculatedBasePayloadBytes) {\n throw new StoreLimitError(\"tracked metadata-base size does not match canonical state size\");\n }\n if (state.basePayloadBytes > MAX_METADATA_BASE_WRITER_BYTES) {\n throw new StoreLimitError(`metadata base exceeds ${MAX_METADATA_BASE_WRITER_BYTES} bytes`);\n }\n if (state.retainedGenerations[state.activeMetadataFile] !== state.generation) {\n throw new StoreLimitError(\"active metadata identity does not match the state generation\");\n }\n const inactiveMetadataFile = otherMetadataFile(state.activeMetadataFile);\n const inactiveGeneration = state.retainedGenerations[inactiveMetadataFile];\n if (inactiveGeneration !== null) {\n checkedU64(inactiveGeneration, \"inactive retained generation\");\n if (inactiveGeneration === 0n || inactiveGeneration + 1n !== state.generation) {\n throw new StoreLimitError(\"inactive retained generation is not the immediate predecessor\");\n }\n }\n for (const extentId of state.allocator.available.values()) {\n classify(extentId, \"available\");\n }\n for (const [extentId, firstExcludedGeneration] of state.allocator.quarantine) {\n classify(extentId, \"quarantined\");\n if (firstExcludedGeneration !== null && firstExcludedGeneration !== state.generation) {\n throw new StoreLimitError(\"quarantine generation is inconsistent with retained metadata\");\n }\n }\n if (BigInt(classifiedCount) !== state.allocator.totalExtents) {\n throw new StoreLimitError(\"allocator partition does not cover every extent\");\n }\n}\n\nexport function canonicalStateView(state: VfsState) {\n const inodes = [...state.inodes.values()]\n .sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))\n .map((inode) =>\n inode.kind === \"directory\"\n ? {\n ...inode,\n children: [...inode.children.entries()].sort(([left], [right]) => left.localeCompare(right)),\n }\n : inode.kind === \"file\"\n ? { ...inode, extents: [...inode.extents] }\n : { ...inode },\n );\n return {\n generation: state.generation,\n nextInodeId: state.nextInodeId,\n rootInodeId: state.rootInodeId,\n extentSize: state.extentSize,\n activeMetadataFile: state.activeMetadataFile,\n retainedGenerations: { ...state.retainedGenerations },\n basePayloadBytes: state.basePayloadBytes,\n inodes,\n parentByInode: [...state.parentByInode.entries()].sort(([left], [right]) =>\n left < right ? -1 : left > right ? 1 : 0,\n ),\n allocator: {\n totalExtents: state.allocator.totalExtents,\n ownedBy: [...state.allocator.ownedBy.entries()].sort(([left], [right]) => (left < right ? -1 : 1)),\n available: [...state.allocator.available.values()].sort((left, right) => (left < right ? -1 : 1)),\n quarantine: [...state.allocator.quarantine.entries()].sort(([left], [right]) => (left < right ? -1 : 1)),\n },\n };\n}\n",
11
- "import { crc32, crc32WithZeroedRange } from \"./checksum\";\nimport { CorruptStoreError, ExtentSizeMismatchError, StoreLimitError, StoreRecreationRequiredError } from \"./errors\";\nimport {\n ARENA_HEADER_BYTES,\n FORMAT_VERSION,\n LIMITS_PROFILE_VERSION,\n MAX_COMPONENT_BYTES,\n MAX_EXTENTS_PER_INODE,\n MAX_FRAME_PAYLOAD_BYTES,\n MAX_INODES,\n MAX_METADATA_BASE_READER_BYTES,\n MAX_METADATA_BASE_WRITER_BYTES,\n MAX_PATH_BYTES,\n MAX_TOTAL_EXTENTS,\n checkedU64,\n validateExtentSize,\n} from \"./limits\";\nimport { validatePathComponent, validateSymlinkTarget } from \"./path\";\nimport { IndexedExtentSet, estimateTxnPayloadBytes, validateState } from \"./state-machine\";\nimport type {\n DirectoryInode,\n ExtentRun,\n FileInode,\n Inode,\n MetadataFile,\n SymlinkInode,\n TxnRecord,\n VfsState,\n} from \"./state-machine\";\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nconst ARENA_MAGIC = textEncoder.encode(\"PGXRPA01\");\nconst METADATA_MAGIC = textEncoder.encode(\"PGXRPM01\");\nconst FRAME_MAGIC = textEncoder.encode(\"PGXRPF01\");\nconst ACTIVATION_MAGIC = textEncoder.encode(\"PGXRPK01\");\n\nexport const ARENA_HEADER_CHECKSUM_OFFSET = 24;\nexport const METADATA_HEADER_BYTES = 80;\nexport const TXN_FRAME_HEADER_BYTES = 48;\nexport const ACTIVATION_SLOT_BYTES = 128;\n\nexport const METADATA_HEADER_CHECKSUM_OFFSET = 64;\nexport const FRAME_CHECKSUM_OFFSET = 40;\nexport const ACTIVATION_CHECKSUM_OFFSET = 52;\n\nclass BinaryWriter {\n readonly bytes: Uint8Array;\n readonly #view: DataView;\n #offset = 0;\n\n constructor(length: number, initialOffset = 0) {\n if (\n !Number.isSafeInteger(length) ||\n length < 0 ||\n !Number.isSafeInteger(initialOffset) ||\n initialOffset < 0 ||\n initialOffset > length\n ) {\n throw new StoreLimitError(\"binary output length is invalid\");\n }\n this.bytes = new Uint8Array(length);\n this.#view = new DataView(this.bytes.buffer);\n this.#offset = initialOffset;\n }\n\n u8(value: number): void {\n this.#require(1);\n if (!Number.isSafeInteger(value) || value < 0 || value > 0xff) {\n throw new StoreLimitError(\"unsigned 8-bit value is out of range\");\n }\n this.#view.setUint8(this.#offset, value);\n this.#offset += 1;\n }\n\n u16(value: number): void {\n this.#require(2);\n if (!Number.isSafeInteger(value) || value < 0 || value > 0xffff) {\n throw new StoreLimitError(\"unsigned 16-bit value is out of range\");\n }\n this.#view.setUint16(this.#offset, value, true);\n this.#offset += 2;\n }\n\n u32(value: number): void {\n this.#require(4);\n if (!Number.isSafeInteger(value) || value < 0 || value > 0xffff_ffff) {\n throw new StoreLimitError(\"unsigned 32-bit value is out of range\");\n }\n this.#view.setUint32(this.#offset, value, true);\n this.#offset += 4;\n }\n\n u64(value: bigint): void {\n this.#require(8);\n this.#view.setBigUint64(this.#offset, checkedU64(value, \"encoded integer\"), true);\n this.#offset += 8;\n }\n\n validatedU64(value: bigint): void {\n this.#require(8);\n this.#view.setBigUint64(this.#offset, value, true);\n this.#offset += 8;\n }\n\n raw(value: Uint8Array): void {\n this.#require(value.byteLength);\n this.bytes.set(value, this.#offset);\n this.#offset += value.byteLength;\n }\n\n string(value: string): void {\n validatePathComponent(value);\n this.validatedString(textEncoder.encode(value));\n }\n\n /** A symbolic link's target: a whole PATH, so it is bounded by `MAX_PATH_BYTES`, not by a name. */\n symlinkTarget(value: string): void {\n validateSymlinkTarget(value);\n this.validatedString(textEncoder.encode(value));\n }\n\n validatedString(encoded: Uint8Array): void {\n this.u16(encoded.byteLength);\n this.raw(encoded);\n }\n\n finish(): Uint8Array {\n if (this.#offset !== this.bytes.byteLength) {\n throw new StoreLimitError(\n `binary encoder wrote ${this.#offset} bytes into a ${this.bytes.byteLength}-byte output`,\n );\n }\n return this.bytes;\n }\n\n #require(length: number): void {\n if (this.#offset + length > this.bytes.byteLength) {\n throw new StoreLimitError(\"binary encoder exceeded its preflighted size\");\n }\n }\n}\n\nclass BinaryReader {\n readonly #bytes: Uint8Array;\n readonly #view: DataView;\n #offset = 0;\n\n constructor(bytes: Uint8Array) {\n this.#bytes = bytes;\n this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n }\n\n get remaining(): number {\n return this.#bytes.byteLength - this.#offset;\n }\n\n u8(): number {\n this.#require(1);\n const value = this.#view.getUint8(this.#offset);\n this.#offset += 1;\n return value;\n }\n\n u16(): number {\n this.#require(2);\n const value = this.#view.getUint16(this.#offset, true);\n this.#offset += 2;\n return value;\n }\n\n u32(): number {\n this.#require(4);\n const value = this.#view.getUint32(this.#offset, true);\n this.#offset += 4;\n return value;\n }\n\n u64(): bigint {\n this.#require(8);\n const value = this.#view.getBigUint64(this.#offset, true);\n this.#offset += 8;\n return value;\n }\n\n raw(length: number): Uint8Array {\n this.#require(length);\n const value = this.#bytes.subarray(this.#offset, this.#offset + length);\n this.#offset += length;\n return value;\n }\n\n string(): string {\n const length = this.u16();\n if (length === 0 || length > MAX_COMPONENT_BYTES) {\n throw new CorruptStoreError(\"encoded path component length is invalid\");\n }\n let value: string;\n try {\n value = textDecoder.decode(this.raw(length));\n } catch (cause) {\n throw new CorruptStoreError(\"encoded path component is not valid UTF-8\", { cause });\n }\n if (textEncoder.encode(value).byteLength !== length) {\n throw new CorruptStoreError(\"encoded path component is not canonical UTF-8\");\n }\n try {\n validatePathComponent(value);\n } catch (cause) {\n throw new CorruptStoreError(`encoded path component is invalid: ${String(cause)}`, { cause });\n }\n return value;\n }\n\n /** The reader half of {@link BinaryWriter.symlinkTarget}. */\n symlinkTarget(): string {\n const length = this.u16();\n if (length === 0 || length > MAX_PATH_BYTES) {\n throw new CorruptStoreError(\"encoded symlink target length is invalid\");\n }\n let value: string;\n try {\n value = textDecoder.decode(this.raw(length));\n } catch (cause) {\n throw new CorruptStoreError(\"encoded symlink target is not valid UTF-8\", { cause });\n }\n if (textEncoder.encode(value).byteLength !== length) {\n throw new CorruptStoreError(\"encoded symlink target is not canonical UTF-8\");\n }\n try {\n validateSymlinkTarget(value);\n } catch (cause) {\n throw new CorruptStoreError(`encoded symlink target is invalid: ${String(cause)}`, { cause });\n }\n return value;\n }\n\n end(): void {\n if (this.remaining !== 0) {\n throw new CorruptStoreError(\"binary value has trailing bytes\");\n }\n }\n\n #require(length: number): void {\n if (!Number.isSafeInteger(length) || length < 0 || length > this.remaining) {\n throw new CorruptStoreError(\"binary value is truncated\");\n }\n }\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.byteLength !== right.byteLength) {\n return false;\n }\n for (let index = 0; index < left.byteLength; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n return true;\n}\n\nfunction requireMagic(bytes: Uint8Array, magic: Uint8Array, label: string): void {\n if (!bytesEqual(bytes.subarray(0, magic.byteLength), magic)) {\n throw new CorruptStoreError(`${label} magic is invalid`);\n }\n}\n\nfunction requireZero(bytes: Uint8Array, start: number, end: number, label: string): void {\n for (let offset = start; offset < end; offset += 1) {\n if (bytes[offset] !== 0) {\n throw new CorruptStoreError(`${label} padding is not canonical`);\n }\n }\n}\n\nfunction requireChecksum(bytes: Uint8Array, offset: number, label: string): void {\n const stored = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(offset, true);\n const calculated = crc32WithZeroedRange(bytes, offset, 4);\n if (stored !== calculated) {\n throw new CorruptStoreError(`${label} checksum is invalid`);\n }\n}\n\nfunction requireCurrentIdentity(version: number, profile: number): void {\n if (version !== FORMAT_VERSION || profile !== LIMITS_PROFILE_VERSION) {\n throw new StoreRecreationRequiredError(\n `store format ${version}/limits profile ${profile} is unsupported; delete the store and create it fresh`,\n );\n }\n}\n\nexport interface ArenaHeader {\n extentSize: number;\n limitsProfileVersion: number;\n formatVersion: number;\n}\n\nexport function encodeArenaHeader(options: { extentSize: number }): Uint8Array {\n const extentSize = validateExtentSize(options.extentSize);\n const bytes = new Uint8Array(ARENA_HEADER_BYTES);\n const view = new DataView(bytes.buffer);\n bytes.set(ARENA_MAGIC, 0);\n view.setUint32(8, FORMAT_VERSION, true);\n view.setUint32(12, LIMITS_PROFILE_VERSION, true);\n view.setUint32(16, extentSize, true);\n view.setUint32(ARENA_HEADER_CHECKSUM_OFFSET, crc32WithZeroedRange(bytes, ARENA_HEADER_CHECKSUM_OFFSET, 4), true);\n return bytes;\n}\n\nexport function decodeArenaHeader(bytes: Uint8Array, configuredExtentSize?: number): ArenaHeader {\n if (configuredExtentSize !== undefined) {\n validateExtentSize(configuredExtentSize);\n }\n if (bytes.byteLength !== ARENA_HEADER_BYTES) {\n throw new CorruptStoreError(\"arena header has the wrong length\");\n }\n requireMagic(bytes, ARENA_MAGIC, \"arena header\");\n requireZero(bytes, 20, 24, \"arena header\");\n requireZero(bytes, 28, bytes.byteLength, \"arena header\");\n requireChecksum(bytes, ARENA_HEADER_CHECKSUM_OFFSET, \"arena header\");\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const formatVersion = view.getUint32(8, true);\n const limitsProfileVersion = view.getUint32(12, true);\n requireCurrentIdentity(formatVersion, limitsProfileVersion);\n const extentSize = view.getUint32(16, true);\n try {\n validateExtentSize(extentSize);\n } catch (cause) {\n throw new CorruptStoreError(\"arena header extent size is invalid\", { cause });\n }\n if (configuredExtentSize !== undefined && configuredExtentSize !== extentSize) {\n throw new ExtentSizeMismatchError(configuredExtentSize, extentSize);\n }\n return { extentSize, limitsProfileVersion, formatVersion };\n}\n\nfunction metadataFileCode(file: MetadataFile): number {\n return file === \"a\" ? 0 : 1;\n}\n\nfunction decodeMetadataFile(value: number): MetadataFile {\n if (value === 0) return \"a\";\n if (value === 1) return \"b\";\n throw new CorruptStoreError(\"metadata file selector is invalid\");\n}\n\nfunction compareBigint(left: bigint, right: bigint): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction compareUtf8Names(left: string, right: string): number {\n let leftIndex = 0;\n let rightIndex = 0;\n while (leftIndex < left.length && rightIndex < right.length) {\n const leftPoint = left.codePointAt(leftIndex)!;\n const rightPoint = right.codePointAt(rightIndex)!;\n if (leftPoint !== rightPoint) return leftPoint - rightPoint;\n leftIndex += leftPoint > 0xffff ? 2 : 1;\n rightIndex += rightPoint > 0xffff ? 2 : 1;\n }\n return left.length - right.length;\n}\n\nfunction sortIfNeeded<Value>(values: Value[], compare: (left: Value, right: Value) => number): Value[] {\n for (let index = 1; index < values.length; index += 1) {\n if (compare(values[index - 1]!, values[index]!) > 0) {\n values.sort(compare);\n break;\n }\n }\n return values;\n}\n\nconst INODE_KIND_DIRECTORY = 0;\nconst INODE_KIND_FILE = 1;\nconst INODE_KIND_SYMLINK = 2;\n\nfunction writeInode(writer: BinaryWriter, inode: Inode): void {\n writer.validatedU64(inode.id);\n writer.u8(\n inode.kind === \"directory\" ? INODE_KIND_DIRECTORY : inode.kind === \"file\" ? INODE_KIND_FILE : INODE_KIND_SYMLINK,\n );\n writer.u32(inode.mode);\n writer.validatedU64(inode.atimeMs);\n writer.validatedU64(inode.mtimeMs);\n writer.validatedU64(inode.ctimeMs);\n if (inode.kind === \"directory\") {\n const children = sortIfNeeded([...inode.children], ([left], [right]) => compareUtf8Names(left, right));\n writer.u32(children.length);\n for (const [name, inodeId] of children) {\n writer.validatedString(textEncoder.encode(name));\n writer.validatedU64(inodeId);\n }\n } else if (inode.kind === \"symlink\") {\n writer.symlinkTarget(inode.target);\n } else {\n writer.validatedU64(inode.size);\n writer.u32(inode.extents.length);\n for (const extentId of inode.extents) writer.validatedU64(extentId);\n }\n}\n\nfunction encodeMetadataPayload(state: VfsState, length: number, prefixBytes = 0): Uint8Array {\n if (length > MAX_METADATA_BASE_WRITER_BYTES) {\n throw new StoreLimitError(`metadata base payload exceeds ${MAX_METADATA_BASE_WRITER_BYTES} bytes`);\n }\n const writer = new BinaryWriter(prefixBytes + length, prefixBytes);\n writer.validatedU64(state.allocator.totalExtents);\n writer.validatedU64(state.nextInodeId);\n writer.u32(state.inodes.size);\n const inodes = sortIfNeeded([...state.inodes.values()], (left, right) => compareBigint(left.id, right.id));\n for (const inode of inodes) {\n writeInode(writer, inode);\n }\n const available = sortIfNeeded([...state.allocator.available.values()], compareBigint);\n for (const extentId of available) writer.validatedU64(extentId);\n const quarantine = sortIfNeeded([...state.allocator.quarantine], ([left], [right]) => compareBigint(left, right));\n for (const [extentId, generation] of quarantine) {\n writer.validatedU64(extentId);\n writer.validatedU64(generation ?? 0n);\n }\n return writer.finish();\n}\n\nexport interface DecodedMetadataBase {\n state: VfsState;\n payloadBytes: number;\n baseEnd: bigint;\n baseDigest: number;\n}\n\nexport interface MetadataBaseHeader {\n formatVersion: number;\n limitsProfileVersion: number;\n generation: bigint;\n extentSize: number;\n metadataFileCode: number;\n rootInodeId: bigint;\n payloadLength: number;\n availableCount: number;\n quarantineCount: number;\n baseEnd: bigint;\n}\n\nexport function inspectMetadataBaseHeader(header: Uint8Array): MetadataBaseHeader {\n if (header.byteLength !== METADATA_HEADER_BYTES) {\n throw new CorruptStoreError(\"metadata base header has the wrong length\");\n }\n requireMagic(header, METADATA_MAGIC, \"metadata base\");\n requireZero(header, 29, 32, \"metadata base\");\n requireZero(header, 52, 56, \"metadata base\");\n requireZero(header, 68, 80, \"metadata base\");\n const view = new DataView(header.buffer, header.byteOffset, header.byteLength);\n const payloadLength = view.getUint32(40, true);\n if (payloadLength > MAX_METADATA_BASE_READER_BYTES) {\n throw new CorruptStoreError(\"metadata base payload declaration exceeds the reader limit\");\n }\n const baseEnd = view.getBigUint64(56, true);\n if (baseEnd !== BigInt(METADATA_HEADER_BYTES + payloadLength)) {\n throw new CorruptStoreError(\"metadata base end offset is inconsistent\");\n }\n const availableCount = view.getUint32(44, true);\n const quarantineCount = view.getUint32(48, true);\n return {\n formatVersion: view.getUint32(8, true),\n limitsProfileVersion: view.getUint32(12, true),\n generation: view.getBigUint64(16, true),\n extentSize: view.getUint32(24, true),\n metadataFileCode: view.getUint8(28),\n rootInodeId: view.getBigUint64(32, true),\n payloadLength,\n availableCount,\n quarantineCount,\n baseEnd,\n };\n}\n\nexport function encodeMetadataBase(state: VfsState): Uint8Array {\n validateState(state);\n return encodeValidatedMetadataBase(state);\n}\n\n/** @internal The caller must have validated this exact state immediately before encoding it. */\nexport function encodeValidatedMetadataBase(state: VfsState): Uint8Array {\n const baseEnd = METADATA_HEADER_BYTES + state.basePayloadBytes;\n const bytes = encodeMetadataPayload(state, state.basePayloadBytes, METADATA_HEADER_BYTES);\n const view = new DataView(bytes.buffer);\n bytes.set(METADATA_MAGIC, 0);\n view.setUint32(8, FORMAT_VERSION, true);\n view.setUint32(12, LIMITS_PROFILE_VERSION, true);\n view.setBigUint64(16, state.generation, true);\n view.setUint32(24, state.extentSize, true);\n view.setUint8(28, metadataFileCode(state.activeMetadataFile));\n view.setBigUint64(32, state.rootInodeId, true);\n view.setUint32(40, state.basePayloadBytes, true);\n view.setUint32(44, state.allocator.available.size, true);\n view.setUint32(48, state.allocator.quarantine.size, true);\n view.setBigUint64(56, BigInt(baseEnd), true);\n view.setUint32(\n METADATA_HEADER_CHECKSUM_OFFSET,\n crc32WithZeroedRange(bytes, METADATA_HEADER_CHECKSUM_OFFSET, 4),\n true,\n );\n return bytes;\n}\n\nfunction readBoundedCount(reader: BinaryReader, maximum: number, label: string): number {\n const count = reader.u32();\n if (count > maximum) {\n throw new CorruptStoreError(`${label} count exceeds ${maximum}`);\n }\n return count;\n}\n\nfunction readInode(reader: BinaryReader): Inode {\n const id = reader.u64();\n const kind = reader.u8();\n const mode = reader.u32();\n const atimeMs = reader.u64();\n const mtimeMs = reader.u64();\n const ctimeMs = reader.u64();\n if (kind === INODE_KIND_DIRECTORY) {\n const childCount = readBoundedCount(reader, MAX_INODES, \"directory child\");\n const children = new Map<string, bigint>();\n let previousName: string | undefined;\n for (let index = 0; index < childCount; index += 1) {\n const name = reader.string();\n if (previousName !== undefined && compareUtf8Names(previousName, name) >= 0) {\n throw new CorruptStoreError(\"directory children are not in canonical order\");\n }\n children.set(name, reader.u64());\n previousName = name;\n }\n const inode: DirectoryInode = { id, kind: \"directory\", mode, atimeMs, mtimeMs, ctimeMs, children };\n return inode;\n }\n if (kind === INODE_KIND_FILE) {\n const size = reader.u64();\n const extentCount = readBoundedCount(reader, MAX_EXTENTS_PER_INODE, \"file extent\");\n const extents: bigint[] = [];\n for (let index = 0; index < extentCount; index += 1) extents.push(reader.u64());\n const inode: FileInode = { id, kind: \"file\", mode, atimeMs, mtimeMs, ctimeMs, size, extents };\n return inode;\n }\n if (kind === INODE_KIND_SYMLINK) {\n const inode: SymlinkInode = {\n id,\n kind: \"symlink\",\n mode,\n atimeMs,\n mtimeMs,\n ctimeMs,\n target: reader.symlinkTarget(),\n };\n return inode;\n }\n throw new CorruptStoreError(\"inode type is invalid\");\n}\n\nexport function decodeMetadataBase(bytes: Uint8Array): DecodedMetadataBase {\n if (bytes.byteLength < METADATA_HEADER_BYTES) {\n throw new CorruptStoreError(\"metadata base header is truncated\");\n }\n const inspected = inspectMetadataBaseHeader(bytes.subarray(0, METADATA_HEADER_BYTES));\n const { payloadLength, baseEnd } = inspected;\n if (bytes.byteLength !== Number(baseEnd)) {\n throw new CorruptStoreError(\"metadata base end offset is inconsistent\");\n }\n requireChecksum(bytes, METADATA_HEADER_CHECKSUM_OFFSET, \"metadata base\");\n const payload = bytes.subarray(METADATA_HEADER_BYTES);\n requireCurrentIdentity(inspected.formatVersion, inspected.limitsProfileVersion);\n const { generation, extentSize, rootInodeId, availableCount, quarantineCount } = inspected;\n if (generation === 0n) throw new CorruptStoreError(\"metadata generation must be positive\");\n try {\n validateExtentSize(extentSize);\n } catch (cause) {\n throw new CorruptStoreError(\"metadata base extent size is invalid\", { cause });\n }\n const activeMetadataFile = decodeMetadataFile(inspected.metadataFileCode);\n if (availableCount > MAX_TOTAL_EXTENTS || quarantineCount > MAX_TOTAL_EXTENTS) {\n throw new CorruptStoreError(\"metadata allocator count exceeds the extent limit\");\n }\n\n try {\n const reader = new BinaryReader(payload);\n const totalExtents = reader.u64();\n if (totalExtents > BigInt(MAX_TOTAL_EXTENTS)) {\n throw new CorruptStoreError(\"metadata total extent count exceeds the extent limit\");\n }\n const nextInodeId = reader.u64();\n const inodeCount = readBoundedCount(reader, MAX_INODES, \"inode\");\n const inodes = new Map<bigint, Inode>();\n const ownedBy = new Map<bigint, bigint>();\n let previousInodeId: bigint | undefined;\n for (let index = 0; index < inodeCount; index += 1) {\n const inode = readInode(reader);\n if (previousInodeId !== undefined && inode.id <= previousInodeId) {\n throw new CorruptStoreError(\"inodes are not in canonical order\");\n }\n inodes.set(inode.id, inode);\n previousInodeId = inode.id;\n if (inode.kind === \"file\") {\n for (const extentId of inode.extents) {\n if (ownedBy.has(extentId)) throw new CorruptStoreError(\"metadata contains duplicate extent ownership\");\n ownedBy.set(extentId, inode.id);\n }\n }\n }\n const available = new IndexedExtentSet();\n let previousAvailable: bigint | undefined;\n for (let index = 0; index < availableCount; index += 1) {\n const extentId = reader.u64();\n if (previousAvailable !== undefined && extentId <= previousAvailable) {\n throw new CorruptStoreError(\"available extents are not in canonical order\");\n }\n available.add(extentId);\n previousAvailable = extentId;\n }\n const quarantine = new Map<bigint, bigint | null>();\n let previousQuarantine: bigint | undefined;\n for (let index = 0; index < quarantineCount; index += 1) {\n const extentId = reader.u64();\n const encodedGeneration = reader.u64();\n if (previousQuarantine !== undefined && extentId <= previousQuarantine) {\n throw new CorruptStoreError(\"quarantine extents are not in canonical order\");\n }\n quarantine.set(extentId, encodedGeneration === 0n ? null : encodedGeneration);\n previousQuarantine = extentId;\n }\n reader.end();\n const parentByInode = new Map<bigint, { parentId: bigint; name: string }>();\n for (const inode of inodes.values()) {\n if (inode.kind !== \"directory\") continue;\n for (const [name, childId] of inode.children) {\n if (parentByInode.has(childId)) {\n throw new CorruptStoreError(\"metadata inode has multiple directory owners\");\n }\n parentByInode.set(childId, { parentId: inode.id, name });\n }\n }\n const retainedGenerations: Record<MetadataFile, bigint | null> = { a: null, b: null };\n retainedGenerations[activeMetadataFile] = generation;\n const state: VfsState = {\n generation,\n nextInodeId,\n rootInodeId,\n extentSize,\n activeMetadataFile,\n retainedGenerations,\n basePayloadBytes: payloadLength,\n inodes,\n parentByInode,\n allocator: { totalExtents, ownedBy, available, quarantine },\n };\n validateState(state);\n return { state, payloadBytes: payloadLength, baseEnd, baseDigest: crc32(bytes) };\n } catch (cause) {\n if (cause instanceof CorruptStoreError) throw cause;\n throw new CorruptStoreError(`metadata base is semantically invalid: ${String(cause)}`, { cause });\n }\n}\n\nfunction writeExtentRuns(writer: BinaryWriter, runs: readonly ExtentRun[]): void {\n writer.u32(runs.length);\n for (const run of runs) {\n writer.u64(run.start);\n writer.u32(run.count);\n }\n}\n\nfunction readExtentRuns(reader: BinaryReader): ExtentRun[] {\n const runCount = readBoundedCount(reader, MAX_EXTENTS_PER_INODE, \"extent run\");\n const runs: ExtentRun[] = [];\n let extentCount = 0;\n for (let index = 0; index < runCount; index += 1) {\n const start = reader.u64();\n const count = reader.u32();\n if (count === 0 || extentCount + count > MAX_EXTENTS_PER_INODE) {\n throw new CorruptStoreError(\"extent run count is invalid\");\n }\n extentCount += count;\n runs.push({ start, count });\n }\n return runs;\n}\n\nconst RECORD_CODES: Record<TxnRecord[\"kind\"], number> = {\n createDirectories: 1,\n createFile: 2,\n removeFile: 3,\n changeMode: 4,\n changeTimes: 5,\n resizeFile: 6,\n removeDirectory: 7,\n rename: 8,\n reserveQuarantine: 9,\n createSymlink: 10,\n};\n\nfunction encodeTxnRecord(record: TxnRecord): Uint8Array {\n const writer = new BinaryWriter(estimateTxnPayloadBytes(record));\n writer.u8(RECORD_CODES[record.kind]);\n switch (record.kind) {\n case \"createDirectories\":\n writer.u32(record.entries.length);\n for (const entry of record.entries) {\n writer.u64(entry.parentId);\n writer.string(entry.name);\n writer.u64(entry.inodeId);\n writer.u32(entry.mode);\n writer.u64(entry.atimeMs);\n writer.u64(entry.mtimeMs);\n writer.u64(entry.ctimeMs);\n }\n break;\n case \"createFile\":\n writer.u64(record.parentId);\n writer.string(record.name);\n writer.u64(record.inodeId);\n writer.u32(record.mode);\n writer.u64(record.atimeMs);\n writer.u64(record.mtimeMs);\n writer.u64(record.ctimeMs);\n writer.u64(record.size);\n writeExtentRuns(writer, record.extents);\n break;\n case \"removeFile\":\n case \"removeDirectory\":\n writer.u64(record.parentId);\n writer.string(record.name);\n writer.u64(record.parentMtimeMs);\n writer.u64(record.parentCtimeMs);\n break;\n case \"changeMode\":\n writer.u64(record.inodeId);\n writer.u32(record.mode);\n writer.u64(record.ctimeMs);\n break;\n case \"changeTimes\":\n writer.u64(record.inodeId);\n writer.u64(record.atimeMs);\n writer.u64(record.mtimeMs);\n writer.u64(record.ctimeMs);\n break;\n case \"resizeFile\":\n writer.u8(record.operation === \"truncate\" ? 0 : 1);\n writer.u64(record.inodeId);\n writer.u64(record.size);\n writeExtentRuns(writer, record.allocated);\n writer.u64(record.mtimeMs);\n writer.u64(record.ctimeMs);\n break;\n case \"rename\":\n writer.u64(record.sourceParentId);\n writer.string(record.sourceName);\n writer.u64(record.destinationParentId);\n writer.string(record.destinationName);\n writer.u64(record.timestampMs);\n break;\n case \"createSymlink\":\n writer.u64(record.parentId);\n writer.string(record.name);\n writer.u64(record.inodeId);\n writer.u32(record.mode);\n writer.u64(record.atimeMs);\n writer.u64(record.mtimeMs);\n writer.u64(record.ctimeMs);\n writer.symlinkTarget(record.target);\n break;\n case \"reserveQuarantine\":\n writeExtentRuns(writer, record.extents);\n break;\n }\n return writer.finish();\n}\n\nfunction decodeTxnRecord(bytes: Uint8Array): TxnRecord {\n const reader = new BinaryReader(bytes);\n const type = reader.u8();\n let record: TxnRecord;\n switch (type) {\n case 1: {\n const count = readBoundedCount(reader, MAX_INODES, \"created directory\");\n if (count === 0) throw new CorruptStoreError(\"directory transaction must not be empty\");\n const entries = [];\n for (let index = 0; index < count; index += 1) {\n entries.push({\n parentId: reader.u64(),\n name: reader.string(),\n inodeId: reader.u64(),\n mode: reader.u32(),\n atimeMs: reader.u64(),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n });\n }\n record = { kind: \"createDirectories\", entries };\n break;\n }\n case 2:\n record = {\n kind: \"createFile\",\n parentId: reader.u64(),\n name: reader.string(),\n inodeId: reader.u64(),\n mode: reader.u32(),\n atimeMs: reader.u64(),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n size: reader.u64(),\n extents: readExtentRuns(reader),\n };\n break;\n case 3:\n case 7:\n record = {\n kind: type === 3 ? \"removeFile\" : \"removeDirectory\",\n parentId: reader.u64(),\n name: reader.string(),\n parentMtimeMs: reader.u64(),\n parentCtimeMs: reader.u64(),\n };\n break;\n case 4:\n record = { kind: \"changeMode\", inodeId: reader.u64(), mode: reader.u32(), ctimeMs: reader.u64() };\n break;\n case 5:\n record = {\n kind: \"changeTimes\",\n inodeId: reader.u64(),\n atimeMs: reader.u64(),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n };\n break;\n case 6: {\n const operation = reader.u8();\n if (operation !== 0 && operation !== 1) throw new CorruptStoreError(\"resize operation is invalid\");\n record = {\n kind: \"resizeFile\",\n operation: operation === 0 ? \"truncate\" : \"write\",\n inodeId: reader.u64(),\n size: reader.u64(),\n allocated: readExtentRuns(reader),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n };\n break;\n }\n case 8:\n record = {\n kind: \"rename\",\n sourceParentId: reader.u64(),\n sourceName: reader.string(),\n destinationParentId: reader.u64(),\n destinationName: reader.string(),\n timestampMs: reader.u64(),\n };\n break;\n case 9:\n record = { kind: \"reserveQuarantine\", extents: readExtentRuns(reader) };\n break;\n case 10:\n record = {\n kind: \"createSymlink\",\n parentId: reader.u64(),\n name: reader.string(),\n inodeId: reader.u64(),\n mode: reader.u32(),\n atimeMs: reader.u64(),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n target: reader.symlinkTarget(),\n };\n break;\n default:\n throw new CorruptStoreError(\"transaction record type is invalid\");\n }\n reader.end();\n return record;\n}\n\nexport interface TxnFrame {\n generation: bigint;\n sequence: bigint;\n record: TxnRecord;\n}\n\nexport interface TxnFrameHeader {\n generation: bigint;\n sequence: bigint;\n payloadLength: number;\n frameBytes: number;\n}\n\nexport function txnFrameBytes(record: TxnRecord): number {\n const payloadBytes = estimateTxnPayloadBytes(record);\n if (payloadBytes > MAX_FRAME_PAYLOAD_BYTES) {\n throw new StoreLimitError(`transaction payload exceeds ${MAX_FRAME_PAYLOAD_BYTES} bytes`);\n }\n return TXN_FRAME_HEADER_BYTES + payloadBytes;\n}\n\nexport function inspectTxnFrameHeader(header: Uint8Array): TxnFrameHeader {\n if (header.byteLength !== TXN_FRAME_HEADER_BYTES) {\n throw new CorruptStoreError(\"transaction frame header has the wrong length\");\n }\n const view = new DataView(header.buffer, header.byteOffset, header.byteLength);\n requireMagic(header, FRAME_MAGIC, \"transaction frame\");\n requireZero(header, 36, 40, \"transaction frame\");\n requireZero(header, 44, 48, \"transaction frame\");\n const payloadLength = view.getUint32(32, true);\n if (payloadLength > MAX_FRAME_PAYLOAD_BYTES) {\n throw new CorruptStoreError(\"transaction payload declaration exceeds the frame limit\");\n }\n if (view.getUint32(8, true) !== FORMAT_VERSION || view.getUint32(12, true) !== LIMITS_PROFILE_VERSION) {\n throw new CorruptStoreError(\"transaction frame format is invalid\");\n }\n return {\n generation: view.getBigUint64(16, true),\n sequence: view.getBigUint64(24, true),\n payloadLength,\n frameBytes: TXN_FRAME_HEADER_BYTES + payloadLength,\n };\n}\n\nexport function encodeTxnFrame(frame: TxnFrame): Uint8Array {\n const payload = encodeTxnRecord(frame.record);\n if (payload.byteLength > MAX_FRAME_PAYLOAD_BYTES) {\n throw new StoreLimitError(`transaction payload exceeds ${MAX_FRAME_PAYLOAD_BYTES} bytes`);\n }\n const bytes = new Uint8Array(TXN_FRAME_HEADER_BYTES + payload.byteLength);\n const view = new DataView(bytes.buffer);\n bytes.set(FRAME_MAGIC, 0);\n view.setUint32(8, FORMAT_VERSION, true);\n view.setUint32(12, LIMITS_PROFILE_VERSION, true);\n view.setBigUint64(16, checkedU64(frame.generation, \"frame generation\"), true);\n view.setBigUint64(24, checkedU64(frame.sequence, \"frame sequence\"), true);\n view.setUint32(32, payload.byteLength, true);\n bytes.set(payload, TXN_FRAME_HEADER_BYTES);\n view.setUint32(FRAME_CHECKSUM_OFFSET, crc32WithZeroedRange(bytes, FRAME_CHECKSUM_OFFSET, 4), true);\n return bytes;\n}\n\nexport function decodeTxnFrame(bytes: Uint8Array): TxnFrame {\n if (bytes.byteLength < TXN_FRAME_HEADER_BYTES) throw new CorruptStoreError(\"transaction frame is truncated\");\n const inspected = inspectTxnFrameHeader(bytes.subarray(0, TXN_FRAME_HEADER_BYTES));\n if (bytes.byteLength !== inspected.frameBytes) {\n throw new CorruptStoreError(\"transaction frame length is inconsistent\");\n }\n requireChecksum(bytes, FRAME_CHECKSUM_OFFSET, \"transaction frame\");\n return {\n generation: inspected.generation,\n sequence: inspected.sequence,\n record: decodeTxnRecord(bytes.subarray(TXN_FRAME_HEADER_BYTES)),\n };\n}\n\nexport interface ActivationRecord {\n sequence: bigint;\n metadataFile: MetadataFile;\n generation: bigint;\n baseEnd: bigint;\n baseDigest: number;\n}\n\nexport function encodeActivationSlot(record: ActivationRecord): Uint8Array {\n if (record.sequence === 0n || record.generation === 0n || record.baseEnd < BigInt(METADATA_HEADER_BYTES)) {\n throw new StoreLimitError(\"activation identity values are outside the encodable domain\");\n }\n const bytes = new Uint8Array(ACTIVATION_SLOT_BYTES);\n const view = new DataView(bytes.buffer);\n bytes.set(ACTIVATION_MAGIC, 0);\n view.setUint32(8, FORMAT_VERSION, true);\n view.setUint32(12, LIMITS_PROFILE_VERSION, true);\n view.setBigUint64(16, checkedU64(record.sequence, \"activation sequence\"), true);\n view.setUint8(24, metadataFileCode(record.metadataFile));\n view.setBigUint64(32, checkedU64(record.generation, \"activation generation\"), true);\n view.setBigUint64(40, checkedU64(record.baseEnd, \"activation base end\"), true);\n if (!Number.isSafeInteger(record.baseDigest) || record.baseDigest < 0 || record.baseDigest > 0xffff_ffff) {\n throw new StoreLimitError(\"activation base digest is outside the unsigned 32-bit range\");\n }\n view.setUint32(48, record.baseDigest, true);\n view.setUint32(ACTIVATION_CHECKSUM_OFFSET, crc32WithZeroedRange(bytes, ACTIVATION_CHECKSUM_OFFSET, 4), true);\n return bytes;\n}\n\nexport function decodeActivationSlot(bytes: Uint8Array): ActivationRecord {\n if (bytes.byteLength !== ACTIVATION_SLOT_BYTES) {\n throw new CorruptStoreError(\"activation slot has the wrong length\");\n }\n requireMagic(bytes, ACTIVATION_MAGIC, \"activation slot\");\n requireZero(bytes, 25, 32, \"activation slot\");\n requireZero(bytes, 56, bytes.byteLength, \"activation slot\");\n requireChecksum(bytes, ACTIVATION_CHECKSUM_OFFSET, \"activation slot\");\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n requireCurrentIdentity(view.getUint32(8, true), view.getUint32(12, true));\n const sequence = view.getBigUint64(16, true);\n const generation = view.getBigUint64(32, true);\n const baseEnd = view.getBigUint64(40, true);\n if (sequence === 0n || generation === 0n || baseEnd < BigInt(METADATA_HEADER_BYTES)) {\n throw new CorruptStoreError(\"activation slot contains invalid identity values\");\n }\n return {\n sequence,\n metadataFile: decodeMetadataFile(view.getUint8(24)),\n generation,\n baseEnd,\n baseDigest: view.getUint32(48, true),\n };\n}\n\nexport function tryDecodeActivationSlot(bytes: Uint8Array): ActivationRecord | null {\n try {\n return decodeActivationSlot(bytes);\n } catch (cause) {\n if (cause instanceof CorruptStoreError) return null;\n throw cause;\n }\n}\n\nexport function selectActivation(leftBytes: Uint8Array, rightBytes: Uint8Array): ActivationRecord {\n return selectActivationPair(leftBytes, rightBytes).selected;\n}\n\nexport interface ActivationPairSelection {\n selected: ActivationRecord;\n other: ActivationRecord | null;\n}\n\nexport function selectActivationPair(leftBytes: Uint8Array, rightBytes: Uint8Array): ActivationPairSelection {\n const left = tryDecodeActivationSlot(leftBytes);\n const right = tryDecodeActivationSlot(rightBytes);\n if (left === null && right === null) {\n throw new CorruptStoreError(\"both activation slots are invalid\");\n }\n if (left === null) return { selected: right!, other: null };\n if (right === null) return { selected: left, other: null };\n const older = left.sequence < right.sequence ? left : right;\n const newer = older === left ? right : left;\n if (newer.sequence !== older.sequence + 1n || newer.metadataFile === older.metadataFile) {\n throw new CorruptStoreError(\"activation slots do not form one exact alternating progression\");\n }\n return { selected: newer, other: older };\n}\n\nexport function metadataBaseDigest(bytes: Uint8Array): number {\n return crc32(bytes);\n}\n",
12
- "import { CorruptStoreError, StoreLimitError } from \"./errors\";\nimport {\n ARENA_HEADER_BYTES,\n MAX_TOTAL_EXTENTS,\n checkedAdd,\n checkedMultiply,\n checkedSafeNumber,\n checkedU64,\n validateExtentSize,\n} from \"./limits\";\nimport type { MetadataFile } from \"./state-machine\";\n\nexport const OWNED_FILE_NAMES = [\"arena.bin\", \"metadata-a.bin\", \"metadata-b.bin\", \"activation.bin\"] as const;\nexport type OwnedFileName = (typeof OWNED_FILE_NAMES)[number];\nexport type MetadataFileName = Extract<OwnedFileName, \"metadata-a.bin\" | \"metadata-b.bin\">;\n\nexport function metadataFileName(file: MetadataFile): MetadataFileName {\n return file === \"a\" ? \"metadata-a.bin\" : \"metadata-b.bin\";\n}\n\nexport interface RepackedPortEntry {\n name: string;\n kind: \"file\" | \"directory\";\n}\n\nexport interface RepackedFileHandle {\n readonly name: OwnedFileName;\n getSize(label: string): number;\n read(target: Uint8Array, at: number, label: string): number;\n write(source: Uint8Array, at: number, label: string): number;\n truncate(size: number, label: string): void;\n flush(label: string): void;\n close(): void;\n}\n\nexport interface RepackedPort {\n enumerate(label: string): Promise<readonly RepackedPortEntry[]>;\n acquire(name: OwnedFileName, label: string): Promise<RepackedFileHandle>;\n}\n\nexport class PortWriteError extends Error {\n constructor(label: string) {\n super(`${label} made no valid write progress`);\n this.name = \"PortWriteError\";\n }\n}\n\nfunction checkedRange(offset: bigint, length: number, label: string): number {\n checkedU64(offset, `${label} offset`);\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new StoreLimitError(`${label} length is invalid`);\n }\n checkedSafeNumber(checkedAdd(offset, BigInt(length), `${label} end`), `${label} end`);\n return checkedSafeNumber(offset, `${label} offset`);\n}\n\nexport function readExact(\n handle: RepackedFileHandle,\n offset: bigint,\n length: number,\n maximumLength: number,\n label: string,\n): Uint8Array {\n if (!Number.isSafeInteger(maximumLength) || maximumLength < 0 || length > maximumLength) {\n throw new StoreLimitError(`${label} length exceeds the bounded read limit`);\n }\n const start = checkedRange(offset, length, label);\n const output = new Uint8Array(length);\n let completed = 0;\n while (completed < output.byteLength) {\n const count = handle.read(output.subarray(completed), start + completed, label);\n if (!Number.isSafeInteger(count) || count <= 0 || count > output.byteLength - completed) {\n throw new CorruptStoreError(`${label} ended before the declared byte length`);\n }\n completed += count;\n }\n return output;\n}\n\nexport function writeExact(handle: RepackedFileHandle, offset: bigint, bytes: Uint8Array, label: string): void {\n const start = checkedRange(offset, bytes.byteLength, label);\n let completed = 0;\n while (completed < bytes.byteLength) {\n const count = handle.write(bytes.subarray(completed), start + completed, label);\n if (!Number.isSafeInteger(count) || count <= 0 || count > bytes.byteLength - completed) {\n throw new PortWriteError(label);\n }\n completed += count;\n }\n}\n\nexport function truncateChecked(handle: RepackedFileHandle, size: bigint, label: string): void {\n handle.truncate(checkedSafeNumber(size, `${label} size`), label);\n}\n\nexport function arenaByteOffset(extentId: bigint, extentSize: number, withinExtent = 0): bigint {\n validateExtentSize(extentSize);\n checkedU64(extentId, \"extent ID\");\n if (extentId >= BigInt(MAX_TOTAL_EXTENTS)) {\n throw new StoreLimitError(`extent ID exceeds ${MAX_TOTAL_EXTENTS - 1}`);\n }\n if (!Number.isSafeInteger(withinExtent) || withinExtent < 0 || withinExtent >= extentSize) {\n throw new StoreLimitError(\"within-extent offset is outside the extent\");\n }\n return checkedAdd(\n checkedAdd(\n BigInt(ARENA_HEADER_BYTES),\n checkedMultiply(extentId, BigInt(extentSize), \"arena offset\"),\n \"arena offset\",\n ),\n BigInt(withinExtent),\n \"arena offset\",\n );\n}\n",
13
- "import {\n ACTIVATION_SLOT_BYTES,\n METADATA_HEADER_BYTES,\n TXN_FRAME_HEADER_BYTES,\n decodeArenaHeader,\n decodeMetadataBase,\n decodeTxnFrame,\n encodeActivationSlot,\n encodeArenaHeader,\n encodeMetadataBase,\n inspectMetadataBaseHeader,\n inspectTxnFrameHeader,\n metadataBaseDigest,\n selectActivationPair,\n tryDecodeActivationSlot,\n} from \"./codec\";\nimport type { ActivationRecord } from \"./codec\";\nimport {\n CorruptStoreError,\n ExtentSizeMismatchError,\n FsError,\n StoreLimitError,\n StoreRecreationRequiredError,\n UnexpectedStoreEntryError,\n} from \"./errors\";\nimport {\n ARENA_HEADER_BYTES,\n DEFAULT_EXTENT_BYTES,\n MAX_ACTIVE_LOG_BYTES,\n MAX_ACTIVE_LOG_FRAMES,\n MAX_EXTENT_BYTES,\n MAX_METADATA_BASE_READER_BYTES,\n MIN_EXTENT_BYTES,\n checkedAdd,\n checkedMultiply,\n checkedSafeNumber,\n validateExtentSize,\n} from \"./limits\";\nimport { OWNED_FILE_NAMES, metadataFileName, readExact, truncateChecked, writeExact } from \"./port\";\nimport type { OwnedFileName, RepackedFileHandle, RepackedPort, RepackedPortEntry } from \"./port\";\nimport { applyTxn, createInitialState, otherMetadataFile, validateState } from \"./state-machine\";\nimport type { MetadataFile, VfsState } from \"./state-machine\";\n\nexport interface OpenedMetadataStore {\n handles: Record<OwnedFileName, RepackedFileHandle>;\n state: VfsState;\n activeLogEnd: bigint;\n nextSequence: bigint;\n activeLogBytes: number;\n activeLogFrames: number;\n activationSequence: bigint;\n arenaHighWaterExtents: bigint;\n arenaSize: number;\n arenaDirty: boolean;\n activeMetadataDirty: boolean;\n}\n\nfunction validateEntries(entries: readonly RepackedPortEntry[]): void {\n for (const entry of entries) {\n if (!(OWNED_FILE_NAMES as readonly string[]).includes(entry.name) || entry.kind !== \"file\") {\n throw new UnexpectedStoreEntryError(entry.name);\n }\n }\n}\n\nfunction closeHandles(handles: readonly RepackedFileHandle[]): void {\n for (let index = handles.length - 1; index >= 0; index -= 1) {\n try {\n handles[index]!.close();\n } catch {\n // Failed-open cleanup preserves the opening error; lifecycle closes aggregate later.\n }\n }\n}\n\nasync function acquireHandles(port: RepackedPort): Promise<Record<OwnedFileName, RepackedFileHandle>> {\n validateEntries(await port.enumerate(\"store.enumerate.initial\"));\n const acquired: RepackedFileHandle[] = [];\n try {\n const activation = await port.acquire(\"activation.bin\", \"store.acquire.activation\");\n acquired.push(activation);\n validateEntries(await port.enumerate(\"store.enumerate.locked\"));\n for (const name of [\"arena.bin\", \"metadata-a.bin\", \"metadata-b.bin\"] as const) {\n acquired.push(await port.acquire(name, `store.acquire.${name}`));\n }\n return Object.fromEntries(acquired.map((handle) => [handle.name, handle])) as Record<\n OwnedFileName,\n RepackedFileHandle\n >;\n } catch (cause) {\n closeHandles(acquired);\n throw cause;\n }\n}\n\nfunction getSizes(handles: Record<OwnedFileName, RepackedFileHandle>): Record<OwnedFileName, number> {\n return Object.fromEntries(\n OWNED_FILE_NAMES.map((name) => [name, handles[name].getSize(`store.size.${name}`)]),\n ) as Record<OwnedFileName, number>;\n}\n\nfunction readSlot(handle: RepackedFileHandle, size: number, index: number): Uint8Array {\n const offset = index * ACTIVATION_SLOT_BYTES;\n if (offset >= size) return new Uint8Array();\n const length = Math.min(ACTIVATION_SLOT_BYTES, size - offset);\n return readExact(handle, BigInt(offset), length, ACTIVATION_SLOT_BYTES, `activation.read.slot-${index}`);\n}\n\nfunction isPrefix(bytes: Uint8Array, canonical: Uint8Array): boolean {\n if (bytes.byteLength > canonical.byteLength) return false;\n for (let index = 0; index < bytes.byteLength; index += 1) {\n if (bytes[index] !== canonical[index]) return false;\n }\n return true;\n}\n\nfunction readWhole(handle: RepackedFileHandle, size: number, maximum: number, label: string): Uint8Array {\n return readExact(handle, 0n, size, maximum, label);\n}\n\nfunction bootstrapExtentSize(\n arena: RepackedFileHandle,\n arenaSize: number,\n configuredExtentSize: number | undefined,\n): number {\n if (arenaSize === 0) return configuredExtentSize ?? DEFAULT_EXTENT_BYTES;\n if (arenaSize >= ARENA_HEADER_BYTES) {\n const header = readExact(arena, 0n, ARENA_HEADER_BYTES, ARENA_HEADER_BYTES, \"arena.read.bootstrap\");\n const extentSize = decodeArenaHeader(header).extentSize;\n if (arenaSize > ARENA_HEADER_BYTES) {\n throw new CorruptStoreError(\"unactivated arena contains extent payload\");\n }\n return extentSize;\n }\n const bytes = readWhole(arena, arenaSize, ARENA_HEADER_BYTES, \"arena.read.bootstrap\");\n let partialExtentSize: number | undefined;\n if (arenaSize >= 20) {\n const declared = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(16, true);\n try {\n partialExtentSize = validateExtentSize(declared);\n } catch (cause) {\n if (!(cause instanceof TypeError)) throw cause;\n partialExtentSize = undefined;\n }\n }\n // Candidate order is significance order: an ambiguous short prefix (fewer\n // than 20 bytes never fixes the extent-size field) must resolve to the\n // configured size or the creation default, never to the smallest candidate\n // that happens to share the prefix.\n const candidates = new Set<number>();\n if (configuredExtentSize !== undefined) candidates.add(configuredExtentSize);\n if (partialExtentSize !== undefined) candidates.add(partialExtentSize);\n candidates.add(DEFAULT_EXTENT_BYTES);\n if (arenaSize < 20) {\n for (let candidate = MIN_EXTENT_BYTES; candidate <= MAX_EXTENT_BYTES; candidate += ARENA_HEADER_BYTES) {\n candidates.add(candidate);\n }\n }\n const matchingExtentSize = [...candidates].find((candidate) =>\n isPrefix(bytes, encodeArenaHeader({ extentSize: candidate })),\n );\n if (matchingExtentSize === undefined) {\n throw new CorruptStoreError(\"unactivated arena is not canonical bootstrap residue\");\n }\n return partialExtentSize ?? matchingExtentSize;\n}\n\nfunction detectArenaVersion(handle: RepackedFileHandle, size: number): void {\n if (size < ARENA_HEADER_BYTES) return;\n const bytes = readExact(handle, 0n, ARENA_HEADER_BYTES, ARENA_HEADER_BYTES, \"arena.inspect.identity\");\n try {\n decodeArenaHeader(bytes);\n } catch (cause) {\n if (cause instanceof StoreRecreationRequiredError) throw cause;\n if (!(cause instanceof CorruptStoreError)) throw cause;\n }\n}\n\nfunction detectCompleteMetadataVersion(handle: RepackedFileHandle, size: number, label: string): void {\n if (size < METADATA_HEADER_BYTES) return;\n let header;\n try {\n header = inspectMetadataBaseHeader(readExact(handle, 0n, METADATA_HEADER_BYTES, METADATA_HEADER_BYTES, label));\n } catch (cause) {\n if (cause instanceof CorruptStoreError) return;\n throw cause;\n }\n if (header.baseEnd > BigInt(size)) return;\n const base = readExact(\n handle,\n 0n,\n Number(header.baseEnd),\n METADATA_HEADER_BYTES + MAX_METADATA_BASE_READER_BYTES,\n `${label}.base`,\n );\n try {\n decodeMetadataBase(base);\n } catch (cause) {\n if (cause instanceof StoreRecreationRequiredError) throw cause;\n if (!(cause instanceof CorruptStoreError)) throw cause;\n }\n}\n\nfunction classifyBootstrapResidue(\n handles: Record<OwnedFileName, RepackedFileHandle>,\n sizes: Record<OwnedFileName, number>,\n configuredExtentSize: number | undefined,\n): number {\n const extentSize = bootstrapExtentSize(handles[\"arena.bin\"], sizes[\"arena.bin\"], configuredExtentSize);\n const initialA = createInitialState(extentSize);\n const baseA = encodeMetadataBase(initialA);\n const initialB = createInitialState(extentSize);\n initialB.activeMetadataFile = \"b\";\n initialB.retainedGenerations = { a: null, b: 1n };\n const baseB = encodeMetadataBase(initialB);\n for (const [name, canonical] of [\n [\"metadata-a.bin\", baseA],\n [\"metadata-b.bin\", baseB],\n ] as const) {\n const size = sizes[name];\n detectCompleteMetadataVersion(handles[name], size, `${name}.inspect.bootstrap`);\n if (size > canonical.byteLength) {\n throw new CorruptStoreError(`${name} exceeds the empty-root bootstrap envelope`);\n }\n const bytes = readWhole(handles[name], size, canonical.byteLength, `${name}.read.bootstrap`);\n if (!isPrefix(bytes, canonical)) {\n throw new CorruptStoreError(`${name} is not canonical bootstrap residue`);\n }\n }\n if (sizes[\"activation.bin\"] > ACTIVATION_SLOT_BYTES * 2) {\n throw new CorruptStoreError(\"unactivated manifest exceeds its fixed envelope\");\n }\n const initialSlot = encodeActivationSlot({\n sequence: 1n,\n metadataFile: \"a\",\n generation: 1n,\n baseEnd: BigInt(baseA.byteLength),\n baseDigest: metadataBaseDigest(baseA),\n });\n const canonicalManifest = new Uint8Array(ACTIVATION_SLOT_BYTES * 2);\n canonicalManifest.set(initialSlot);\n const manifest = readWhole(\n handles[\"activation.bin\"],\n sizes[\"activation.bin\"],\n canonicalManifest.byteLength,\n \"activation.read.bootstrap\",\n );\n if (!isPrefix(manifest, canonicalManifest)) {\n throw new CorruptStoreError(\"manifest is not canonical bootstrap residue\");\n }\n if (\n sizes[\"arena.bin\"] === ARENA_HEADER_BYTES &&\n configuredExtentSize !== undefined &&\n configuredExtentSize !== extentSize\n ) {\n throw new ExtentSizeMismatchError(configuredExtentSize, extentSize);\n }\n return sizes[\"arena.bin\"] < ARENA_HEADER_BYTES && configuredExtentSize !== undefined\n ? configuredExtentSize\n : extentSize;\n}\n\nfunction bootstrap(handles: Record<OwnedFileName, RepackedFileHandle>, extentSize: number): OpenedMetadataStore {\n const state = createInitialState(extentSize);\n const arenaBytes = encodeArenaHeader({ extentSize });\n const baseBytes = encodeMetadataBase(state);\n const activationBytes = encodeActivationSlot({\n sequence: 1n,\n metadataFile: \"a\",\n generation: 1n,\n baseEnd: BigInt(baseBytes.byteLength),\n baseDigest: metadataBaseDigest(baseBytes),\n });\n const arena = handles[\"arena.bin\"];\n arena.truncate(0, \"bootstrap.arena.reset\");\n writeExact(arena, 0n, arenaBytes, \"bootstrap.arena.write\");\n arena.flush(\"bootstrap.arena.flush\");\n const metadataA = handles[\"metadata-a.bin\"];\n metadataA.truncate(0, \"bootstrap.metadata-a.reset\");\n writeExact(metadataA, 0n, baseBytes, \"bootstrap.metadata-a.write\");\n metadataA.flush(\"bootstrap.metadata-a.flush\");\n handles[\"metadata-b.bin\"].truncate(0, \"bootstrap.metadata-b.reset\");\n const activation = handles[\"activation.bin\"];\n activation.truncate(0, \"bootstrap.activation.reset\");\n writeExact(activation, 0n, activationBytes, \"bootstrap.activation.write\");\n activation.flush(\"bootstrap.activation.flush\");\n const decoded = decodeMetadataBase(baseBytes);\n return {\n handles,\n state: decoded.state,\n activeLogEnd: decoded.baseEnd,\n nextSequence: 1n,\n activeLogBytes: 0,\n activeLogFrames: 0,\n activationSequence: 1n,\n arenaHighWaterExtents: 0n,\n arenaSize: arenaBytes.byteLength,\n arenaDirty: false,\n activeMetadataDirty: false,\n };\n}\n\nfunction metadataHandle(handles: Record<OwnedFileName, RepackedFileHandle>, file: MetadataFile): RepackedFileHandle {\n return handles[metadataFileName(file)];\n}\n\nfunction verifyInactiveVersion(\n handles: Record<OwnedFileName, RepackedFileHandle>,\n sizes: Record<OwnedFileName, number>,\n selectedFile: MetadataFile,\n): void {\n const inactiveName = metadataFileName(otherMetadataFile(selectedFile));\n detectCompleteMetadataVersion(handles[inactiveName], sizes[inactiveName], `${inactiveName}.inspect.inactive`);\n}\n\nfunction readSelectedBase(\n handle: RepackedFileHandle,\n fileSize: number,\n selected: ActivationRecord,\n): ReturnType<typeof decodeMetadataBase> & { header: ReturnType<typeof inspectMetadataBaseHeader> } {\n if (fileSize < METADATA_HEADER_BYTES) throw new CorruptStoreError(\"selected metadata base is missing or short\");\n const headerBytes = readExact(handle, 0n, METADATA_HEADER_BYTES, METADATA_HEADER_BYTES, \"metadata.read.header\");\n const header = inspectMetadataBaseHeader(headerBytes);\n if (header.baseEnd !== selected.baseEnd || header.baseEnd > BigInt(fileSize)) {\n throw new CorruptStoreError(\"selected metadata base end does not match activation\");\n }\n const baseBytes = readExact(\n handle,\n 0n,\n Number(header.baseEnd),\n METADATA_HEADER_BYTES + MAX_METADATA_BASE_READER_BYTES,\n \"metadata.read.base\",\n );\n const decoded = decodeMetadataBase(baseBytes);\n if (\n decoded.state.activeMetadataFile !== selected.metadataFile ||\n decoded.state.generation !== selected.generation ||\n decoded.baseEnd !== selected.baseEnd ||\n decoded.baseDigest !== selected.baseDigest\n ) {\n throw new CorruptStoreError(\"selected metadata base identity does not match activation\");\n }\n return { ...decoded, header };\n}\n\nfunction requiredArenaEnd(state: VfsState): bigint {\n return checkedAdd(\n BigInt(ARENA_HEADER_BYTES),\n checkedMultiply(state.allocator.totalExtents, BigInt(state.extentSize), \"required arena bytes\"),\n \"required arena end\",\n );\n}\n\nfunction replayLog(\n handle: RepackedFileHandle,\n fileSize: number,\n state: VfsState,\n baseEnd: bigint,\n): { validEnd: bigint; nextSequence: bigint; requiredArenaEnd: bigint } {\n let cursor = checkedSafeNumber(baseEnd, \"active log start\");\n let sequence = 1n;\n let frameCount = 0;\n while (cursor < fileSize && frameCount < MAX_ACTIVE_LOG_FRAMES) {\n const logBytes = cursor - Number(baseEnd);\n const remaining = fileSize - cursor;\n if (remaining < TXN_FRAME_HEADER_BYTES || logBytes + TXN_FRAME_HEADER_BYTES > MAX_ACTIVE_LOG_BYTES) break;\n const headerBytes = readExact(\n handle,\n BigInt(cursor),\n TXN_FRAME_HEADER_BYTES,\n TXN_FRAME_HEADER_BYTES,\n \"metadata.log.read-header\",\n );\n let inspected;\n try {\n inspected = inspectTxnFrameHeader(headerBytes);\n } catch (cause) {\n if (cause instanceof CorruptStoreError) break;\n throw cause;\n }\n if (inspected.frameBytes > remaining || logBytes + inspected.frameBytes > MAX_ACTIVE_LOG_BYTES) break;\n const frameBytes = readExact(\n handle,\n BigInt(cursor),\n inspected.frameBytes,\n TXN_FRAME_HEADER_BYTES + inspected.payloadLength,\n \"metadata.log.read-frame\",\n );\n try {\n const frame = decodeTxnFrame(frameBytes);\n if (frame.generation !== state.generation || frame.sequence !== sequence) break;\n applyTxn(state, frame.record);\n } catch (cause) {\n if (cause instanceof CorruptStoreError || cause instanceof FsError || cause instanceof StoreLimitError) {\n break;\n }\n throw cause;\n }\n cursor += inspected.frameBytes;\n sequence += 1n;\n frameCount += 1;\n }\n validateState(state);\n return { validEnd: BigInt(cursor), nextSequence: sequence, requiredArenaEnd: requiredArenaEnd(state) };\n}\n\nfunction recoverActivated(\n handles: Record<OwnedFileName, RepackedFileHandle>,\n sizes: Record<OwnedFileName, number>,\n leftBytes: Uint8Array,\n rightBytes: Uint8Array,\n configuredExtentSize: number | undefined,\n): OpenedMetadataStore {\n if (sizes[\"arena.bin\"] < ARENA_HEADER_BYTES) {\n throw new CorruptStoreError(\"activated arena header is missing or short\");\n }\n const arenaHeader = decodeArenaHeader(\n readExact(handles[\"arena.bin\"], 0n, ARENA_HEADER_BYTES, ARENA_HEADER_BYTES, \"arena.read.header\"),\n );\n const selection = selectActivationPair(leftBytes, rightBytes);\n verifyInactiveVersion(handles, sizes, selection.selected.metadataFile);\n const selectedHandle = metadataHandle(handles, selection.selected.metadataFile);\n const selectedName = selectedHandle.name;\n const decoded = readSelectedBase(selectedHandle, sizes[selectedName], selection.selected);\n if (\n decoded.state.extentSize !== arenaHeader.extentSize ||\n decoded.header.limitsProfileVersion !== arenaHeader.limitsProfileVersion\n ) {\n throw new CorruptStoreError(\"arena and metadata identities disagree\");\n }\n if (selection.other !== null) {\n decoded.state.retainedGenerations[selection.other.metadataFile] = selection.other.generation;\n }\n try {\n validateState(decoded.state);\n } catch (cause) {\n if (cause instanceof StoreLimitError) {\n throw new CorruptStoreError(`activation retained-generation facts are invalid: ${cause.message}`, { cause });\n }\n throw cause;\n }\n const replayed = replayLog(selectedHandle, sizes[selectedName], decoded.state, decoded.baseEnd);\n if (configuredExtentSize !== undefined && configuredExtentSize !== arenaHeader.extentSize) {\n throw new ExtentSizeMismatchError(configuredExtentSize, arenaHeader.extentSize);\n }\n const requiredEnd = checkedSafeNumber(replayed.requiredArenaEnd, \"required arena end\");\n const arenaDirty = sizes[\"arena.bin\"] < requiredEnd;\n if (arenaDirty) {\n truncateChecked(handles[\"arena.bin\"], replayed.requiredArenaEnd, \"recovery.arena.grow\");\n }\n const activeMetadataDirty = replayed.validEnd < BigInt(sizes[selectedName]);\n if (activeMetadataDirty) {\n truncateChecked(selectedHandle, replayed.validEnd, \"recovery.metadata.discard-suffix\");\n }\n const physicalArenaExtents =\n (BigInt(Math.max(0, sizes[\"arena.bin\"] - ARENA_HEADER_BYTES)) + BigInt(arenaHeader.extentSize) - 1n) /\n BigInt(arenaHeader.extentSize);\n return {\n handles,\n state: decoded.state,\n activeLogEnd: replayed.validEnd,\n nextSequence: replayed.nextSequence,\n activeLogBytes: Number(replayed.validEnd - decoded.baseEnd),\n activeLogFrames: Number(replayed.nextSequence - 1n),\n activationSequence: selection.selected.sequence,\n arenaHighWaterExtents:\n physicalArenaExtents > decoded.state.allocator.totalExtents\n ? physicalArenaExtents\n : decoded.state.allocator.totalExtents,\n arenaSize: arenaDirty ? requiredEnd : sizes[\"arena.bin\"],\n arenaDirty,\n activeMetadataDirty,\n };\n}\n\nexport async function openMetadataStore(\n port: RepackedPort,\n options: { extentSize?: number },\n): Promise<OpenedMetadataStore> {\n const configuredExtentSize = options.extentSize;\n if (configuredExtentSize !== undefined) validateExtentSize(configuredExtentSize);\n const handles = await acquireHandles(port);\n try {\n const sizes = getSizes(handles);\n const leftBytes = readSlot(handles[\"activation.bin\"], sizes[\"activation.bin\"], 0);\n const rightBytes = readSlot(handles[\"activation.bin\"], sizes[\"activation.bin\"], 1);\n detectArenaVersion(handles[\"arena.bin\"], sizes[\"arena.bin\"]);\n detectCompleteMetadataVersion(\n handles[\"metadata-a.bin\"],\n sizes[\"metadata-a.bin\"],\n \"metadata-a.bin.inspect.identity\",\n );\n detectCompleteMetadataVersion(\n handles[\"metadata-b.bin\"],\n sizes[\"metadata-b.bin\"],\n \"metadata-b.bin.inspect.identity\",\n );\n const left = tryDecodeActivationSlot(leftBytes);\n const right = tryDecodeActivationSlot(rightBytes);\n if (sizes[\"activation.bin\"] > ACTIVATION_SLOT_BYTES * 2) {\n throw new CorruptStoreError(\"manifest exceeds its fixed envelope\");\n }\n if (left !== null || right !== null) {\n return recoverActivated(handles, sizes, leftBytes, rightBytes, configuredExtentSize);\n }\n const extentSize = classifyBootstrapResidue(handles, sizes, configuredExtentSize);\n return bootstrap(handles, extentSize);\n } catch (cause) {\n closeHandles(Object.values(handles));\n throw cause;\n }\n}\n",
14
- "import {\n ACTIVATION_SLOT_BYTES,\n encodeActivationSlot,\n encodeValidatedMetadataBase,\n encodeTxnFrame,\n metadataBaseDigest,\n txnFrameBytes,\n} from \"./codec\";\nimport { CorruptStoreError, FS_ERRNO, FsError, StoreClosedError, StoreFailedError, StoreLimitError } from \"./errors\";\nimport {\n ARENA_HEADER_BYTES,\n MAX_ACTIVE_LOG_BYTES,\n MAX_ACTIVE_LOG_FRAMES,\n MAX_EXTENTS_PER_INODE,\n MAX_METADATA_BASE_WRITER_BYTES,\n SOFT_ACTIVE_LOG_BYTES,\n SOFT_ACTIVE_LOG_FRAMES,\n checkedAdd,\n checkedMultiply,\n checkedSafeNumber,\n checkedU64,\n} from \"./limits\";\nimport { openMetadataStore } from \"./metadata-store\";\nimport type { OpenedMetadataStore } from \"./metadata-store\";\nimport { encodedUtf8Length } from \"./path\";\nimport { PortWriteError, arenaByteOffset, metadataFileName, truncateChecked, writeExact } from \"./port\";\nimport type { RepackedFileHandle, RepackedPort } from \"./port\";\nimport {\n applyTxn,\n expandExtentRuns,\n getInodeAtPath,\n makeOrphanRecord,\n planChmod,\n planCreateFile,\n planMkdir,\n planRename,\n planReserveQuarantine,\n planResizeFile,\n planResizeFileForInode,\n planRmdir,\n planSymlink,\n planUnlink,\n planUtimes,\n prepareTxnProjection,\n projectRepackForActivation,\n resolveLinks,\n} from \"./state-machine\";\nimport type {\n ExtentRun,\n FileInode,\n Inode,\n OrphanRecord,\n PreparedTxnProjection,\n SymlinkInode,\n TxnRecord,\n} from \"./state-machine\";\n\ninterface Descriptor {\n inodeId: bigint;\n offset: bigint;\n readable: boolean;\n writable: boolean;\n append: boolean;\n orphan?: OrphanRecord;\n}\n\ninterface ParsedFlags {\n readable: boolean;\n writable: boolean;\n create: boolean;\n exclusive: boolean;\n truncate: boolean;\n append: boolean;\n}\n\ninterface WriteProgress {\n bytes: number;\n error?: unknown;\n}\n\ninterface PreparedCommit {\n readonly frame: Uint8Array | undefined;\n readonly frameBytes: number;\n readonly projection: PreparedTxnProjection;\n readonly materializedRecord: TxnRecord;\n readonly deferResize: boolean;\n readonly replacesPendingResize: boolean;\n}\n\ninterface PendingResizeCommit {\n readonly record: Extract<TxnRecord, { kind: \"resizeFile\" }>;\n readonly frameBytes: number;\n readonly sequence: bigint;\n}\n\ntype FlushKind = \"amortized\" | \"arena\" | \"metadata\" | \"zeroBarrier\" | \"manifest\";\nconst REPACK_INTERVAL_MS = 30_000;\nconst AMORTIZED_ARENA_FLUSH_BYTES = 4 * 1024 * 1024;\nconst BASE_REPACK_PRESSURE_BYTES = Math.floor(MAX_METADATA_BASE_WRITER_BYTES * 0.75);\nconst QUARANTINE_PRESSURE_EXTENTS = 64;\n\nclass ArenaGrowthQuotaError extends Error {\n override readonly cause: unknown;\n\n constructor(cause: unknown) {\n super(\"arena growth exhausted the storage quota\");\n this.name = \"ArenaGrowthQuotaError\";\n this.cause = cause;\n }\n}\n\nfunction isQuotaExceeded(cause: unknown): boolean {\n return typeof cause === \"object\" && cause !== null && \"name\" in cause && cause.name === \"QuotaExceededError\";\n}\n\nfunction mergeExtentRuns(left: readonly ExtentRun[], right: readonly ExtentRun[]): ExtentRun[] {\n const merged = left.map((run) => ({ ...run }));\n for (const run of right) {\n const last = merged.at(-1);\n if (last !== undefined && last.start + BigInt(last.count) === run.start && last.count + run.count <= 0xffff_ffff) {\n last.count += run.count;\n } else {\n merged.push({ ...run });\n }\n }\n return merged;\n}\n\nexport interface RepackedVfsOpenOptions {\n /** Creation extent size: 8 KiB–16 MiB in 8 KiB steps. Defaults to 64 KiB. */\n extentSize?: number;\n}\n\nexport interface RepackedStat {\n /**\n * `symlink` is only ever reported by `lstat` — `stat` follows the link and reports its target.\n * A link's `size` is the UTF-8 byte length of its target, exactly as POSIX `lstat` reports it.\n */\n readonly kind: \"directory\" | \"file\" | \"symlink\";\n readonly mode: number;\n readonly size: bigint;\n readonly atimeMs: bigint;\n readonly mtimeMs: bigint;\n readonly ctimeMs: bigint;\n}\n\nexport type RepackReason =\n | \"manual\"\n | \"time\"\n | \"log-bytes\"\n | \"log-frames\"\n | \"writer-limit\"\n | \"quarantine-pressure\"\n | \"quota\";\n\nexport interface RepackedVfsMetrics {\n readonly generation: bigint;\n readonly totalExtents: bigint;\n readonly availableExtents: number;\n readonly quarantineExtents: number;\n readonly quarantineBytes: bigint;\n readonly activeLogBytes: number;\n readonly activeLogFrames: number;\n readonly lastRepackReason: RepackReason | null;\n readonly lastRepackDurationMs: number | null;\n readonly repackCount: number;\n readonly pendingRepackReason: RepackReason | null;\n readonly flushes: Readonly<{\n amortized: number;\n arena: number;\n metadata: number;\n zeroBarrier: number;\n manifest: number;\n }>;\n}\n\n/**\n * The file surface of a repacked store, as a TYPE.\n *\n * `RepackedVfs` is the one-store implementation; {@link MountedRepackedVfs} is a composite of\n * several. Everything that takes a store — the sync broker above all — takes this, so a host can\n * hand it either without the two knowing about each other.\n */\nexport interface RepackedFileSystem {\n strictSync(): void;\n assertHealthy(): void;\n fail(cause: unknown): never;\n metrics(): RepackedVfsMetrics;\n repack(reason?: RepackReason): void;\n runScheduledRepack(nowMs?: number): boolean;\n /** The link-free absolute path `path` names; `follow` governs the final component only. */\n resolvePath(path: string, follow?: boolean): string;\n stat(path: string): RepackedStat;\n lstat(path: string): RepackedStat;\n symlink(target: string, path: string, nowMs: bigint): void;\n readlink(path: string): string;\n readdir(path: string): string[];\n mkdir(path: string, options: { recursive?: boolean; mode?: number; nowMs: bigint }): void;\n writeFile(\n path: string,\n data: string | Uint8Array,\n options: { encoding?: string; mode?: number; flag?: string; nowMs: bigint },\n ): void;\n readFile(path: string): Uint8Array;\n truncate(path: string, size: bigint, nowMs: bigint): void;\n open(path: string, flags?: string, mode?: number, nowMs?: bigint): number;\n fstat(fd: number): RepackedStat;\n read(fd: number, buffer: Uint8Array, offset: number, length: number, position?: bigint): number;\n write(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: bigint | undefined,\n nowMs: bigint,\n ): number;\n chmod(path: string, mode: number, nowMs: bigint): void;\n utimes(path: string, atimeMs: bigint, mtimeMs: bigint, ctimeMs: bigint): void;\n unlink(path: string, nowMs: bigint): void;\n rmdir(path: string, nowMs: bigint): void;\n rename(oldPath: string, newPath: string, nowMs: bigint): void;\n close(): void;\n close(fd: number): void;\n}\n\nexport class RepackedVfs implements RepackedFileSystem {\n readonly #store: OpenedMetadataStore;\n #status: \"open\" | \"failed\" | \"closed\" = \"open\";\n #failure: unknown;\n readonly #descriptors = new Map<number, Descriptor>();\n #nextDescriptor = 3;\n #pendingResizeCommit: PendingResizeCommit | undefined;\n #arenaSize: number | undefined;\n #arenaDirty: boolean;\n #arenaDirtyBytesSinceFlush = 0;\n #metadataDirtySinceFlush: boolean;\n #repacking = false;\n #lastRepackReason: RepackReason | null = null;\n #lastRepackDurationMs: number | null = null;\n #pendingRepackReason: RepackReason | null = null;\n #repackCount = 0;\n #lastRepackAtMs = Date.now();\n readonly #flushes = { amortized: 0, arena: 0, metadata: 0, zeroBarrier: 0, manifest: 0 };\n\n private constructor(store: OpenedMetadataStore) {\n this.#store = store;\n this.#arenaSize = store.arenaSize;\n this.#arenaDirty = store.arenaDirty;\n this.#metadataDirtySinceFlush = store.activeMetadataDirty;\n }\n\n static async open(port: RepackedPort, options: RepackedVfsOpenOptions = {}): Promise<RepackedVfs> {\n return new RepackedVfs(await openMetadataStore(port, options));\n }\n\n strictSync(): void {\n this.#assertOpen();\n try {\n if (this.#arenaDirty) this.#flush(this.#store.handles[\"arena.bin\"], \"sync.arena.flush\", \"arena\");\n this.#materializePendingResize();\n if (this.#metadataDirtySinceFlush) {\n const activeName = metadataFileName(this.#store.state.activeMetadataFile);\n this.#flush(this.#store.handles[activeName], \"sync.metadata.flush\", \"metadata\");\n }\n this.#arenaDirty = false;\n this.#arenaDirtyBytesSinceFlush = 0;\n this.#metadataDirtySinceFlush = false;\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n }\n\n assertHealthy(): void {\n this.#assertOpen();\n }\n\n fail(cause: unknown): never {\n this.#assertOpen();\n this.#poison(cause);\n throw cause;\n }\n\n cleanupFailedInit(): void {\n if (this.#status === \"closed\") return;\n this.#status = \"closed\";\n this.#descriptors.clear();\n const closeError = this.#closeHandles();\n if (closeError !== undefined) throw closeError;\n }\n\n metrics(): RepackedVfsMetrics {\n this.#assertOpen();\n return {\n generation: this.#store.state.generation,\n totalExtents: this.#store.state.allocator.totalExtents,\n availableExtents: this.#store.state.allocator.available.size,\n quarantineExtents: this.#store.state.allocator.quarantine.size,\n quarantineBytes: BigInt(this.#store.state.allocator.quarantine.size) * BigInt(this.#store.state.extentSize),\n activeLogBytes: this.#store.activeLogBytes,\n activeLogFrames: this.#store.activeLogFrames,\n lastRepackReason: this.#lastRepackReason,\n lastRepackDurationMs: this.#lastRepackDurationMs,\n repackCount: this.#repackCount,\n pendingRepackReason: this.#pendingRepackReason,\n flushes: { ...this.#flushes },\n };\n }\n\n repack(reason: RepackReason = \"manual\"): void {\n this.#assertOpen();\n if (this.#repacking) throw new Error(\"OPFS repacked VFS repack is already running\");\n checkedAdd(this.#store.state.generation, 1n, \"generation\");\n const activationSequence = checkedAdd(this.#store.activationSequence, 1n, \"activation sequence\");\n this.#repacking = true;\n const startedAt = performance.now();\n try {\n this.#materializePendingResize();\n const pinned = new Set<bigint>();\n for (const descriptor of this.#descriptors.values()) {\n if (descriptor.orphan === undefined) continue;\n for (const extentId of descriptor.orphan.extents) pinned.add(extentId);\n }\n const projected = projectRepackForActivation(this.#store.state, pinned);\n const base = encodeValidatedMetadataBase(projected);\n const activation = encodeActivationSlot({\n sequence: activationSequence,\n metadataFile: projected.activeMetadataFile,\n generation: projected.generation,\n baseEnd: BigInt(base.byteLength),\n baseDigest: metadataBaseDigest(base),\n });\n\n this.#flush(this.#store.handles[\"arena.bin\"], \"repack.arena.flush\", \"arena\");\n this.#arenaDirty = false;\n this.#arenaDirtyBytesSinceFlush = 0;\n const inactiveName = metadataFileName(projected.activeMetadataFile);\n const inactive = this.#store.handles[inactiveName];\n inactive.truncate(0, \"repack.metadata.reset\");\n writeExact(inactive, 0n, base, \"repack.metadata.write\");\n this.#flush(inactive, \"repack.metadata.flush\", \"metadata\");\n\n const activationOffset = ((activationSequence - 1n) % 2n) * BigInt(ACTIVATION_SLOT_BYTES);\n try {\n writeExact(this.#store.handles[\"activation.bin\"], activationOffset, activation, \"repack.activation.write\");\n this.#flush(this.#store.handles[\"activation.bin\"], \"repack.activation.flush\", \"manifest\");\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n\n try {\n this.#store.state = projected;\n this.#store.activeLogEnd = BigInt(base.byteLength);\n this.#store.nextSequence = 1n;\n this.#store.activeLogBytes = 0;\n this.#store.activeLogFrames = 0;\n this.#store.activationSequence = activationSequence;\n this.#metadataDirtySinceFlush = false;\n this.#lastRepackReason = reason;\n this.#pendingRepackReason = null;\n this.#repackCount += 1;\n this.#lastRepackAtMs = Date.now();\n this.#scheduleRepack();\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n\n const requiredArenaEnd = checkedAdd(\n BigInt(ARENA_HEADER_BYTES),\n checkedMultiply(projected.allocator.totalExtents, BigInt(projected.extentSize), \"arena byte length\"),\n \"arena byte length\",\n );\n try {\n if (BigInt(this.#arenaSizeChecked(\"repack.arena.size-before-trim\")) > requiredArenaEnd) {\n this.#arenaDirty = true;\n this.#truncateArena(requiredArenaEnd, \"repack.arena.trim\");\n }\n } catch {\n // The activated allocator no longer names this physical tail; recovery can trim it later.\n }\n this.#lastRepackDurationMs = performance.now() - startedAt;\n } finally {\n this.#repacking = false;\n }\n }\n\n runScheduledRepack(nowMs = Date.now()): boolean {\n this.#assertOpen();\n if (!Number.isSafeInteger(nowMs) || nowMs < 0) throw new TypeError(\"repack scheduler time is invalid\");\n this.#materializePendingResize();\n if (this.#arenaDirtyBytesSinceFlush >= AMORTIZED_ARENA_FLUSH_BYTES) {\n try {\n this.#flush(this.#store.handles[\"arena.bin\"], \"sync.arena.amortized.flush\", \"amortized\");\n this.#arenaDirty = false;\n this.#arenaDirtyBytesSinceFlush = 0;\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n }\n const reason = this.#dueRepackReason(nowMs);\n if (reason === null) return false;\n this.repack(reason);\n this.#lastRepackAtMs = nowMs;\n return true;\n }\n\n /**\n * The link-free absolute path `path` names, without touching anything. A composite VFS resolves\n * across a mount boundary with it: this store answers for the part of the path it holds, stops at\n * the first component it does not have, and carries the rest through verbatim.\n */\n resolvePath(path: string, follow = true): string {\n this.#assertOpen();\n return this.#resolve(path, follow);\n }\n\n /** Follows a symbolic link on the final component; every intermediate link is always followed. */\n stat(requestPath: string): RepackedStat {\n this.#assertOpen();\n return this.#statValue(getInodeAtPath(this.#store.state, this.#resolve(requestPath, true)));\n }\n\n /** Reports the LINK itself when the final component is one. */\n lstat(requestPath: string): RepackedStat {\n this.#assertOpen();\n return this.#statValue(getInodeAtPath(this.#store.state, this.#resolve(requestPath, false)));\n }\n\n /** Create a symbolic link at `path` pointing at the ABSOLUTE `target`. The target is not read. */\n symlink(target: string, requestPath: string, nowMs: bigint): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, false);\n this.#commit(planSymlink(this.#store.state, path, target, { nowMs }).record);\n }\n\n /** The target of the symbolic link at `path`. `EINVAL` when the path is not a link. */\n readlink(requestPath: string): string {\n this.#assertOpen();\n const path = this.#resolve(requestPath, false);\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"symlink\") throw new FsError(\"EINVAL\", \"path is not a symbolic link\", { path });\n return inode.target;\n }\n\n readdir(requestPath: string): string[] {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"directory\") throw new FsError(\"ENOTDIR\", \"path is not a directory\", { path });\n return [...inode.children.keys()].sort();\n }\n\n mkdir(requestPath: string, options: { recursive?: boolean; mode?: number; nowMs: bigint }): void {\n this.#assertOpen();\n // The final component is the directory being CREATED, so it is never followed; a link already\n // sitting there is `EEXIST`, exactly as POSIX `mkdir` reports it.\n this.#commit(planMkdir(this.#store.state, this.#resolve(requestPath, false), options).record);\n }\n\n writeFile(\n requestPath: string,\n data: string | Uint8Array,\n options: { encoding?: string; mode?: number; flag?: string; nowMs: bigint },\n ): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n const flags = this.#parseFlags(options.flag ?? \"w\");\n if (!flags.writable)\n throw new FsError(\"EBADF\", \"writeFile flags are not writable\", { operation: \"writeFile\", path });\n let bytes: Uint8Array;\n if (typeof data === \"string\") {\n this.#validateEncoding(options.encoding ?? \"utf8\", path);\n bytes = new TextEncoder().encode(data);\n } else {\n bytes = data;\n }\n checkedU64(options.nowMs, \"timestamp\");\n let existing: FileInode | undefined;\n try {\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n existing = inode;\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) throw cause;\n }\n if (existing !== undefined && flags.create && flags.exclusive) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"writeFile\", path });\n }\n if (existing === undefined && !flags.create) {\n throw new FsError(\"ENOENT\", \"path does not exist\", { operation: \"writeFile\", path });\n }\n const wasExisting = existing !== undefined;\n if (bytes.byteLength === 0 && existing !== undefined && !flags.truncate) return;\n const buildPlan = () => {\n let current: FileInode | undefined;\n if (wasExisting) {\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n current = inode;\n }\n const currentStart = current !== undefined && flags.append ? current.size : 0n;\n const targetSize =\n current === undefined\n ? BigInt(bytes.byteLength)\n : flags.append\n ? checkedAdd(current.size, BigInt(bytes.byteLength), \"writeFile size\")\n : flags.truncate\n ? BigInt(bytes.byteLength)\n : current.size > BigInt(bytes.byteLength)\n ? current.size\n : BigInt(bytes.byteLength);\n const currentPlan =\n current === undefined\n ? planCreateFile(this.#store.state, path, {\n ...(options.mode === undefined ? {} : { mode: options.mode }),\n nowMs: options.nowMs,\n size: targetSize,\n })\n : planResizeFile(this.#store.state, path, targetSize, options.nowMs, \"write\");\n return {\n existing: current,\n start: currentStart,\n plan: currentPlan,\n preparedCommit: this.#preflightCommit(currentPlan.record),\n allocated: expandExtentRuns(\n currentPlan.record.kind === \"createFile\" ? currentPlan.record.extents : currentPlan.record.allocated,\n MAX_EXTENTS_PER_INODE,\n ),\n };\n };\n const prepared = this.#prepareAllocationWithQuotaRetry(buildPlan(), buildPlan);\n existing = prepared.existing;\n const { start, plan, preparedCommit, allocated } = prepared;\n if (bytes.byteLength === 0) {\n this.#commit(plan.record, preparedCommit);\n return;\n }\n const progress = this.#writeLogical(existing?.extents ?? [], start, bytes, \"arena.write-file\", allocated);\n if (progress.bytes === 0) this.#failStore(progress.error);\n const partialSize =\n existing !== undefined && !flags.truncate\n ? existing.size > checkedAdd(start, BigInt(progress.bytes), \"partial writeFile size\")\n ? existing.size\n : checkedAdd(start, BigInt(progress.bytes), \"partial writeFile size\")\n : BigInt(progress.bytes);\n const committedPlan =\n progress.bytes === bytes.byteLength\n ? plan\n : existing === undefined\n ? planCreateFile(this.#store.state, path, {\n ...(options.mode === undefined ? {} : { mode: options.mode }),\n nowMs: options.nowMs,\n size: partialSize,\n })\n : planResizeFile(this.#store.state, path, partialSize, options.nowMs, \"write\");\n if (progress.error === undefined || partialSize !== existing?.size) {\n this.#commit(committedPlan.record, committedPlan === plan ? preparedCommit : undefined);\n }\n if (progress.error !== undefined) throw progress.error;\n }\n\n readFile(requestPath: string): Uint8Array {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n const output = new Uint8Array(checkedSafeNumber(inode.size, \"file read size\"));\n this.#readLogical(inode.extents, 0n, output);\n return output;\n }\n\n truncate(requestPath: string, size: bigint, nowMs: bigint): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n let inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n if (size === inode.size) return;\n let plan = planResizeFile(this.#store.state, path, size, nowMs, \"truncate\");\n let preparedCommit = this.#preflightCommit(plan.record);\n if (size > inode.size) {\n const buildPlan = () => {\n const current = getInodeAtPath(this.#store.state, path);\n if (current.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n const currentPlan = planResizeFile(this.#store.state, path, size, nowMs, \"truncate\");\n return {\n inode: current,\n plan: currentPlan,\n preparedCommit: this.#preflightCommit(currentPlan.record),\n allocated: expandExtentRuns(currentPlan.record.allocated, MAX_EXTENTS_PER_INODE),\n arenaSizeBefore: this.#arenaSizeChecked(\"arena.size.before-extension\"),\n };\n };\n const prepared = this.#prepareAllocationWithQuotaRetry(\n {\n inode,\n plan,\n preparedCommit,\n allocated: expandExtentRuns(plan.record.allocated, MAX_EXTENTS_PER_INODE),\n arenaSizeBefore: this.#arenaSizeChecked(\"arena.size.before-extension\"),\n },\n buildPlan,\n );\n inode = prepared.inode;\n plan = prepared.plan;\n preparedCommit = prepared.preparedCommit;\n const touchedExisting = this.#zeroLogical(\n inode.extents,\n inode.size,\n size - inode.size,\n prepared.arenaSizeBefore,\n prepared.allocated,\n );\n if (touchedExisting) this.#flushPreparedArena(\"arena.gap-zero.flush\");\n }\n this.#commit(plan.record, preparedCommit);\n }\n\n open(requestPath: string, flags = \"r\", mode = 0o100666, nowMs = 0n): number {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n const parsed = this.#parseFlags(flags);\n let inode: FileInode;\n try {\n const found = getInodeAtPath(this.#store.state, path);\n if (found.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n if (parsed.exclusive && parsed.create) throw new FsError(\"EEXIST\", \"path already exists\", { path });\n inode = found;\n if (parsed.truncate) {\n this.truncate(path, 0n, nowMs);\n inode = getInodeAtPath(this.#store.state, path) as FileInode;\n }\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT || !parsed.create) throw cause;\n this.#commit(planCreateFile(this.#store.state, path, { mode, nowMs, size: 0n }).record);\n inode = getInodeAtPath(this.#store.state, path) as FileInode;\n }\n const fd = this.#nextDescriptor++;\n this.#descriptors.set(fd, {\n inodeId: inode.id,\n offset: parsed.append ? inode.size : 0n,\n readable: parsed.readable,\n writable: parsed.writable,\n append: parsed.append,\n });\n return fd;\n }\n\n fstat(fd: number): RepackedStat {\n this.#assertOpen();\n const descriptor = this.#descriptor(fd);\n const inode = descriptor.orphan ?? this.#linkedFile(descriptor.inodeId);\n return this.#statValue(inode);\n }\n\n read(fd: number, buffer: Uint8Array, offset: number, length: number, position?: bigint): number {\n this.#assertOpen();\n this.#validateBufferRange(buffer, offset, length);\n const descriptor = this.#descriptor(fd);\n if (!descriptor.readable) throw new FsError(\"EBADF\", \"descriptor is not readable\");\n const inode = descriptor.orphan ?? this.#linkedFile(descriptor.inodeId);\n const start = position ?? descriptor.offset;\n if (start < 0n) throw new FsError(\"EINVAL\", \"read position is negative\");\n const available = start >= inode.size ? 0 : Math.min(length, checkedSafeNumber(inode.size - start, \"read length\"));\n if (available > 0) this.#readLogical(inode.extents, start, buffer.subarray(offset, offset + available));\n if (position === undefined) descriptor.offset = start + BigInt(available);\n return available;\n }\n\n write(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: bigint | undefined,\n nowMs: bigint,\n ): number {\n this.#assertOpen();\n this.#validateBufferRange(buffer, offset, length);\n checkedU64(nowMs, \"timestamp\");\n const descriptor = this.#descriptor(fd);\n if (!descriptor.writable) throw new FsError(\"EBADF\", \"descriptor is not writable\");\n if (descriptor.orphan !== undefined) {\n return this.#writeOrphan(descriptor, buffer.subarray(offset, offset + length), position, nowMs);\n }\n let inode = this.#linkedFile(descriptor.inodeId);\n const start = descriptor.append ? inode.size : (position ?? descriptor.offset);\n if (start < 0n) throw new FsError(\"EINVAL\", \"write position is negative\");\n if (length === 0) return 0;\n const requestedEnd = checkedAdd(start, BigInt(length), \"write end\");\n let admittedLength = length;\n let allocated: readonly bigint[] = [];\n let plan: ReturnType<typeof planResizeFile> | undefined;\n let preparedCommit: PreparedCommit | undefined;\n if (requestedEnd > inode.size) {\n const buildPlan = () => {\n const current = this.#linkedFile(descriptor.inodeId);\n const admitted = this.#planLinkedWrite(current, start, length, nowMs);\n return {\n inode: current,\n admitted,\n allocated:\n admitted.plan === undefined ? [] : expandExtentRuns(admitted.plan.record.allocated, MAX_EXTENTS_PER_INODE),\n arenaSizeBefore: start > current.size ? this.#arenaSizeChecked(\"arena.size.before-write-extension\") : 0,\n };\n };\n const prepared = this.#prepareAllocationWithQuotaRetry(buildPlan(), buildPlan);\n inode = prepared.inode;\n plan = prepared.admitted.plan;\n preparedCommit = prepared.admitted.preparedCommit;\n admittedLength = prepared.admitted.length;\n if (plan !== undefined) {\n allocated = prepared.allocated;\n if (start > inode.size) {\n const touchedExisting = this.#zeroLogical(\n inode.extents,\n inode.size,\n start - inode.size,\n prepared.arenaSizeBefore,\n allocated,\n );\n if (touchedExisting) this.#flushPreparedArena(\"arena.gap-zero.flush\");\n }\n }\n }\n const source = buffer.subarray(offset, offset + admittedLength);\n const progress = this.#writeLogical(inode.extents, start, source, \"arena.write\", allocated);\n if (progress.bytes === 0) this.#failStore(progress.error);\n const completedEnd = checkedAdd(start, BigInt(progress.bytes), \"completed write end\");\n if (completedEnd > inode.size) {\n const committedPlan =\n plan !== undefined && completedEnd === plan.record.size\n ? plan\n : planResizeFileForInode(this.#store.state, inode, completedEnd, nowMs, \"write\");\n this.#commit(committedPlan.record, committedPlan === plan ? preparedCommit : undefined);\n }\n if (position === undefined) descriptor.offset = completedEnd;\n return progress.bytes;\n }\n\n chmod(requestPath: string, mode: number, nowMs: bigint): void {\n this.#assertOpen();\n this.#commit(planChmod(this.#store.state, this.#resolve(requestPath, true), mode, nowMs).record);\n }\n\n utimes(requestPath: string, atimeMs: bigint, mtimeMs: bigint, ctimeMs: bigint): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n this.#commit(planUtimes(this.#store.state, path, atimeMs, mtimeMs, ctimeMs).record);\n }\n\n /** Removes a file or a SYMBOLIC LINK. The final component is never followed. */\n unlink(requestPath: string, nowMs: bigint): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, false);\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind === \"directory\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n const affected =\n inode.kind === \"file\"\n ? [...this.#descriptors.values()].filter(\n (descriptor) => descriptor.orphan === undefined && descriptor.inodeId === inode.id,\n )\n : [];\n const orphan = inode.kind === \"file\" && affected.length > 0 ? makeOrphanRecord(inode) : undefined;\n this.#commit(planUnlink(this.#store.state, path, nowMs).record);\n if (orphan !== undefined) for (const descriptor of affected) descriptor.orphan = orphan;\n }\n\n rmdir(requestPath: string, nowMs: bigint): void {\n this.#assertOpen();\n this.#commit(planRmdir(this.#store.state, this.#resolve(requestPath, false), nowMs).record);\n }\n\n /** Renames the entry itself: a symbolic link moves as a link, and its target is never followed. */\n rename(oldRequestPath: string, newRequestPath: string, nowMs: bigint): void {\n this.#assertOpen();\n const oldPath = this.#resolve(oldRequestPath, false);\n const newPath = this.#resolve(newRequestPath, false);\n let destination: FileInode | undefined;\n try {\n const inode = getInodeAtPath(this.#store.state, newPath);\n if (inode.kind === \"file\") destination = inode;\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) throw cause;\n }\n const affected =\n destination === undefined\n ? []\n : [...this.#descriptors.values()].filter(\n (descriptor) => descriptor.orphan === undefined && descriptor.inodeId === destination.id,\n );\n const orphan = destination !== undefined && affected.length > 0 ? makeOrphanRecord(destination) : undefined;\n this.#commit(planRename(this.#store.state, oldPath, newPath, nowMs).record);\n if (orphan !== undefined) for (const descriptor of affected) descriptor.orphan = orphan;\n }\n\n close(): void;\n close(fd: number): void;\n close(fd?: number): void {\n if (fd !== undefined) {\n this.#assertOpen();\n if (!this.#descriptors.delete(fd)) throw new FsError(\"EBADF\", \"descriptor is invalid\");\n return;\n }\n if (this.#status === \"closed\") return;\n let firstError: unknown;\n if (this.#status === \"open\") {\n try {\n this.strictSync();\n } catch (cause) {\n firstError = cause;\n }\n } else {\n firstError = new StoreFailedError(this.#failure);\n }\n this.#status = \"closed\";\n this.#descriptors.clear();\n const closeError = this.#closeHandles();\n firstError ??= closeError;\n if (firstError !== undefined) throw firstError;\n }\n\n #closeHandles(): unknown {\n let firstError: unknown;\n for (const name of [\"metadata-b.bin\", \"metadata-a.bin\", \"arena.bin\", \"activation.bin\"] as const) {\n try {\n this.#store.handles[name].close();\n } catch (cause) {\n firstError ??= cause;\n }\n }\n return firstError;\n }\n\n #prepareAllocated(extents: readonly bigint[]): void {\n if (extents.length === 0) return;\n const totalBefore = this.#store.state.allocator.totalExtents;\n const highWaterBefore = this.#store.arenaHighWaterExtents;\n const fresh = extents.filter((extentId) => extentId >= totalBefore);\n const arenaSizeBefore = this.#arenaSizeChecked(\"arena.size.before-allocation\");\n if (fresh.length > 0) {\n const last = fresh[fresh.length - 1]!;\n const requiredExtents = checkedAdd(last, 1n, \"arena extent count\");\n const requiredEnd = checkedAdd(\n BigInt(ARENA_HEADER_BYTES),\n checkedMultiply(requiredExtents, BigInt(this.#store.state.extentSize), \"arena byte length\"),\n \"arena byte length\",\n );\n if (requiredEnd > BigInt(arenaSizeBefore)) {\n this.#arenaDirty = true;\n if (requiredExtents > this.#store.arenaHighWaterExtents) {\n this.#store.arenaHighWaterExtents = requiredExtents;\n }\n try {\n this.#truncateArena(requiredEnd, \"arena.grow\");\n } catch (cause) {\n if (isQuotaExceeded(cause)) throw new ArenaGrowthQuotaError(cause);\n throw cause;\n }\n }\n }\n\n const reused = extents.filter((extentId) => extentId < totalBefore || extentId < highWaterBefore);\n if (reused.length === 0) return;\n const zeros = new Uint8Array(Math.min(this.#store.state.extentSize, 64 * 1024));\n for (const extentId of reused) {\n let within = 0;\n while (within < this.#store.state.extentSize) {\n const count = Math.min(zeros.byteLength, this.#store.state.extentSize - within);\n this.#arenaDirty = true;\n this.#writeArenaExact(\n arenaByteOffset(extentId, this.#store.state.extentSize, within),\n zeros.subarray(0, count),\n \"arena.allocation.zero\",\n );\n this.#recordArenaWrite(count);\n within += count;\n }\n }\n this.#flushPreparedArena(\"arena.allocation.flush\");\n }\n\n #readLogical(extents: readonly bigint[], position: bigint, target: Uint8Array): void {\n checkedU64(position, \"read position\");\n let completed = 0;\n while (completed < target.byteLength) {\n const logical = checkedAdd(position, BigInt(completed), \"read position\");\n const extentIndex = checkedSafeNumber(logical / BigInt(this.#store.state.extentSize), \"extent index\");\n const extentId = this.#extentAt(extents, [], extentIndex);\n if (extentId === undefined) throw new CorruptStoreError(\"file metadata does not cover its visible data\");\n const within = Number(logical % BigInt(this.#store.state.extentSize));\n const count = Math.min(target.byteLength - completed, this.#store.state.extentSize - within);\n let extentCompleted = 0;\n while (extentCompleted < count) {\n const read = this.#store.handles[\"arena.bin\"].read(\n target.subarray(completed + extentCompleted, completed + count),\n checkedSafeNumber(\n arenaByteOffset(extentId, this.#store.state.extentSize, within + extentCompleted),\n \"arena read offset\",\n ),\n \"arena.read\",\n );\n if (!Number.isSafeInteger(read) || read <= 0 || read > count - extentCompleted) {\n throw new CorruptStoreError(\"arena data ended before the visible file range\");\n }\n extentCompleted += read;\n }\n completed += count;\n }\n }\n\n #writeLogical(\n extents: readonly bigint[],\n position: bigint,\n source: Uint8Array,\n label: string,\n allocated: readonly bigint[] = [],\n ): WriteProgress {\n checkedU64(position, \"write position\");\n let completed = 0;\n while (completed < source.byteLength) {\n const logical = checkedAdd(position, BigInt(completed), \"write position\");\n const extentIndex = checkedSafeNumber(logical / BigInt(this.#store.state.extentSize), \"extent index\");\n const extentId = this.#extentAt(extents, allocated, extentIndex);\n if (extentId === undefined) throw new StoreLimitError(\"planned extents do not cover the write range\");\n const within = Number(logical % BigInt(this.#store.state.extentSize));\n const requested = Math.min(source.byteLength - completed, this.#store.state.extentSize - within);\n try {\n this.#arenaDirty = true;\n const written = this.#writeArena(\n source.subarray(completed, completed + requested),\n checkedSafeNumber(arenaByteOffset(extentId, this.#store.state.extentSize, within), \"arena write offset\"),\n label,\n );\n if (!Number.isSafeInteger(written) || written <= 0 || written > requested) {\n throw new PortWriteError(label);\n }\n this.#recordArenaWrite(written);\n completed += written;\n } catch (error) {\n return { bytes: completed, error };\n }\n }\n return { bytes: completed };\n }\n\n #zeroLogical(\n extents: readonly bigint[],\n position: bigint,\n length: bigint,\n arenaSizeBefore: number,\n allocated: readonly bigint[] = [],\n ): boolean {\n checkedU64(position, \"zero position\");\n checkedU64(length, \"zero length\");\n const zeros = new Uint8Array(64 * 1024);\n const previousEnd = BigInt(arenaSizeBefore);\n let completed = 0n;\n let touchedExisting = false;\n while (completed < length) {\n const logical = checkedAdd(position, completed, \"zero position\");\n const extentIndex = checkedSafeNumber(logical / BigInt(this.#store.state.extentSize), \"extent index\");\n const extentId = this.#extentAt(extents, allocated, extentIndex);\n if (extentId === undefined) throw new StoreLimitError(\"planned extents do not cover the zero range\");\n const within = Number(logical % BigInt(this.#store.state.extentSize));\n const remainingInExtent = this.#store.state.extentSize - within;\n const count = Math.min(\n zeros.byteLength,\n remainingInExtent,\n checkedSafeNumber(length - completed, \"remaining zero length\"),\n );\n const physical = arenaByteOffset(extentId, this.#store.state.extentSize, within);\n if (physical < previousEnd) {\n const existingCount = Math.min(count, checkedSafeNumber(previousEnd - physical, \"existing zero length\"));\n this.#arenaDirty = true;\n this.#writeArenaExact(physical, zeros.subarray(0, existingCount), \"arena.gap-zero.write\");\n this.#recordArenaWrite(existingCount);\n touchedExisting = true;\n }\n completed += BigInt(count);\n }\n return touchedExisting;\n }\n\n #extentAt(head: readonly bigint[], tail: readonly bigint[], index: number): bigint | undefined {\n return index < head.length ? head[index] : tail[index - head.length];\n }\n\n #planLinkedWrite(\n inode: FileInode,\n start: bigint,\n requestedLength: number,\n nowMs: bigint,\n ): {\n length: number;\n plan: ReturnType<typeof planResizeFile> | undefined;\n preparedCommit: PreparedCommit | undefined;\n } {\n const attempt = (\n length: number,\n ): { plan: ReturnType<typeof planResizeFile>; preparedCommit: PreparedCommit } | undefined => {\n const end = checkedAdd(start, BigInt(length), \"write end\");\n if (end <= inode.size) return undefined;\n const plan = planResizeFileForInode(this.#store.state, inode, end, nowMs, \"write\");\n return { plan, preparedCommit: this.#preflightCommit(plan.record) };\n };\n try {\n const admitted = attempt(requestedLength);\n return {\n length: requestedLength,\n plan: admitted?.plan,\n preparedCommit: admitted?.preparedCommit,\n };\n } catch (cause) {\n if (!(cause instanceof StoreLimitError)) throw cause;\n let low = 0;\n let high = requestedLength - 1;\n let admitted = 0;\n let admittedPlan: ReturnType<typeof planResizeFile> | undefined;\n let admittedCommit: PreparedCommit | undefined;\n while (low <= high) {\n const candidate = low + Math.floor((high - low) / 2);\n try {\n const candidatePlan = attempt(candidate);\n admitted = candidate;\n admittedPlan = candidatePlan?.plan;\n admittedCommit = candidatePlan?.preparedCommit;\n low = candidate + 1;\n } catch (candidateCause) {\n if (!(candidateCause instanceof StoreLimitError)) throw candidateCause;\n high = candidate - 1;\n }\n }\n if (admitted === 0) throw cause;\n return { length: admitted, plan: admittedPlan, preparedCommit: admittedCommit };\n }\n }\n\n #writeOrphan(descriptor: Descriptor, source: Uint8Array, position: bigint | undefined, nowMs: bigint): number {\n const orphan = descriptor.orphan!;\n const start = descriptor.append ? orphan.size : (position ?? descriptor.offset);\n if (start < 0n) throw new FsError(\"EINVAL\", \"write position is negative\");\n if (source.byteLength === 0) return 0;\n const buildPlan = () => {\n const admitted = this.#planOrphanWrite(orphan, start, source.byteLength);\n return {\n admitted,\n allocated:\n admitted.reservation === undefined\n ? []\n : expandExtentRuns(admitted.reservation.record.extents, MAX_EXTENTS_PER_INODE),\n arenaSizeBefore: this.#arenaSizeChecked(\"arena.size.before-orphan-extension\"),\n };\n };\n const prepared = this.#prepareAllocationWithQuotaRetry(buildPlan(), buildPlan);\n const { admitted, allocated, arenaSizeBefore } = prepared;\n if (admitted.reservation !== undefined) {\n this.#commit(admitted.reservation.record);\n orphan.extents.push(...allocated);\n }\n if (start > orphan.size) {\n const touchedExisting = this.#zeroLogical(orphan.extents, orphan.size, start - orphan.size, arenaSizeBefore);\n if (touchedExisting) this.#flushPreparedArena(\"arena.gap-zero.flush\");\n }\n const progress = this.#writeLogical(orphan.extents, start, source.subarray(0, admitted.length), \"arena.write\");\n if (progress.bytes === 0) this.#failStore(progress.error);\n const completedEnd = checkedAdd(start, BigInt(progress.bytes), \"completed orphan write end\");\n if (completedEnd > orphan.size) orphan.size = completedEnd;\n orphan.mtimeMs = nowMs;\n orphan.ctimeMs = nowMs;\n if (position === undefined) descriptor.offset = completedEnd;\n return progress.bytes;\n }\n\n #planOrphanWrite(\n orphan: OrphanRecord,\n start: bigint,\n requestedLength: number,\n ): { length: number; reservation: ReturnType<typeof planReserveQuarantine> | undefined } {\n const attempt = (length: number): ReturnType<typeof planReserveQuarantine> | undefined => {\n const end = checkedAdd(start, BigInt(length), \"orphan write end\");\n const required = this.#extentCount(end);\n const additional = Math.max(0, required - orphan.extents.length);\n if (additional === 0) return undefined;\n const reservation = planReserveQuarantine(this.#store.state, additional);\n this.#preflightCommit(reservation.record);\n return reservation;\n };\n try {\n return { length: requestedLength, reservation: attempt(requestedLength) };\n } catch (cause) {\n if (!(cause instanceof StoreLimitError)) throw cause;\n let low = 0;\n let high = requestedLength - 1;\n let admitted = 0;\n let reservation: ReturnType<typeof planReserveQuarantine> | undefined;\n while (low <= high) {\n const candidate = low + Math.floor((high - low) / 2);\n try {\n const candidateReservation = attempt(candidate);\n admitted = candidate;\n reservation = candidateReservation;\n low = candidate + 1;\n } catch (candidateCause) {\n if (!(candidateCause instanceof StoreLimitError)) throw candidateCause;\n high = candidate - 1;\n }\n }\n if (admitted === 0) throw cause;\n return { length: admitted, reservation };\n }\n }\n\n #extentCount(size: bigint): number {\n checkedU64(size, \"file size\");\n if (size === 0n) return 0;\n const count = (size + BigInt(this.#store.state.extentSize) - 1n) / BigInt(this.#store.state.extentSize);\n const result = checkedSafeNumber(count, \"file extent count\");\n if (result > MAX_EXTENTS_PER_INODE) {\n throw new StoreLimitError(`file extent count exceeds ${MAX_EXTENTS_PER_INODE}`);\n }\n return result;\n }\n\n #parseFlags(flags: string): ParsedFlags {\n const parsed: Record<string, ParsedFlags> = {\n r: { readable: true, writable: false, create: false, exclusive: false, truncate: false, append: false },\n \"r+\": { readable: true, writable: true, create: false, exclusive: false, truncate: false, append: false },\n w: { readable: false, writable: true, create: true, exclusive: false, truncate: true, append: false },\n \"w+\": { readable: true, writable: true, create: true, exclusive: false, truncate: true, append: false },\n wx: { readable: false, writable: true, create: true, exclusive: true, truncate: true, append: false },\n \"wx+\": { readable: true, writable: true, create: true, exclusive: true, truncate: true, append: false },\n a: { readable: false, writable: true, create: true, exclusive: false, truncate: false, append: true },\n \"a+\": { readable: true, writable: true, create: true, exclusive: false, truncate: false, append: true },\n ax: { readable: false, writable: true, create: true, exclusive: true, truncate: false, append: true },\n \"ax+\": { readable: true, writable: true, create: true, exclusive: true, truncate: false, append: true },\n };\n const result = parsed[flags];\n if (result === undefined) throw new FsError(\"EINVAL\", `unsupported open flags: ${flags}`);\n return result;\n }\n\n #validateEncoding(encoding: string, path: string): \"utf8\" {\n if (encoding !== \"utf8\" && encoding !== \"utf-8\") {\n throw new FsError(\"EINVAL\", `unsupported writeFile encoding: ${encoding}`, { operation: \"writeFile\", path });\n }\n return \"utf8\";\n }\n\n #flushPreparedArena(label: string): void {\n this.#flush(this.#store.handles[\"arena.bin\"], label, \"zeroBarrier\");\n this.#arenaDirty = false;\n this.#arenaDirtyBytesSinceFlush = 0;\n }\n\n #recordArenaWrite(bytes: number): void {\n if (!Number.isSafeInteger(bytes) || bytes < 0) throw new TypeError(\"arena dirty byte count is invalid\");\n this.#arenaDirtyBytesSinceFlush = Math.min(Number.MAX_SAFE_INTEGER, this.#arenaDirtyBytesSinceFlush + bytes);\n }\n\n #arenaSizeChecked(label: string): number {\n if (this.#arenaSize !== undefined) return this.#arenaSize;\n const size = this.#store.handles[\"arena.bin\"].getSize(label);\n if (!Number.isSafeInteger(size) || size < 0) throw new Error(`${label} returned an invalid arena size`);\n this.#arenaSize = size;\n return size;\n }\n\n #writeArena(source: Uint8Array, at: number, label: string): number {\n const sizeBefore = this.#arenaSize;\n this.#arenaSize = undefined;\n const written = this.#store.handles[\"arena.bin\"].write(source, at, label);\n if (sizeBefore !== undefined && Number.isSafeInteger(written) && written >= 0 && written <= source.byteLength) {\n const end = at + written;\n if (!Number.isSafeInteger(end)) return written;\n this.#arenaSize = Math.max(sizeBefore, end);\n }\n return written;\n }\n\n #writeArenaExact(at: bigint, source: Uint8Array, label: string): void {\n const sizeBefore = this.#arenaSize;\n this.#arenaSize = undefined;\n writeExact(this.#store.handles[\"arena.bin\"], at, source, label);\n if (sizeBefore !== undefined) {\n this.#arenaSize = Math.max(\n sizeBefore,\n checkedSafeNumber(checkedAdd(at, BigInt(source.byteLength), \"arena write end\"), \"arena write end\"),\n );\n }\n }\n\n #truncateArena(size: bigint, label: string): void {\n this.#arenaSize = undefined;\n truncateChecked(this.#store.handles[\"arena.bin\"], size, label);\n this.#arenaSize = checkedSafeNumber(size, \"arena truncate size\");\n }\n\n #flush(handle: RepackedFileHandle, label: string, kind: FlushKind): void {\n this.#flushes[kind] += 1;\n handle.flush(label);\n }\n\n #prepareAllocationWithQuotaRetry<T extends { allocated: readonly bigint[] }>(initial: T, retry: () => T): T {\n try {\n this.#prepareAllocated(initial.allocated);\n return initial;\n } catch (cause) {\n if (!(cause instanceof ArenaGrowthQuotaError)) throw cause;\n this.repack(\"quota\");\n this.repack(\"quota\");\n const retried = retry();\n try {\n this.#prepareAllocated(retried.allocated);\n } catch (retryCause) {\n if (retryCause instanceof ArenaGrowthQuotaError) throw retryCause.cause;\n throw retryCause;\n }\n return retried;\n }\n }\n\n #descriptor(fd: number): Descriptor {\n if (!Number.isSafeInteger(fd)) throw new FsError(\"EBADF\", \"descriptor is invalid\");\n const descriptor = this.#descriptors.get(fd);\n if (descriptor === undefined) throw new FsError(\"EBADF\", \"descriptor is invalid\");\n return descriptor;\n }\n\n /** Every path entering the store is resolved here exactly once; planners then see no links. */\n #resolve(path: string, follow: boolean): string {\n return resolveLinks(this.#store.state, path, follow);\n }\n\n #linkedFile(inodeId: bigint): FileInode {\n const inode = this.#store.state.inodes.get(inodeId);\n if (inode?.kind !== \"file\") throw new FsError(\"EBADF\", \"descriptor no longer references a file\");\n return inode;\n }\n\n #statValue(inode: Inode | OrphanRecord): RepackedStat {\n const kind = \"kind\" in inode ? inode.kind : \"file\";\n return {\n kind,\n mode: inode.mode,\n size:\n kind === \"file\"\n ? (inode as FileInode | OrphanRecord).size\n : kind === \"symlink\"\n ? BigInt(encodedUtf8Length((inode as SymlinkInode).target))\n : 0n,\n atimeMs: inode.atimeMs,\n mtimeMs: inode.mtimeMs,\n ctimeMs: inode.ctimeMs,\n };\n }\n\n #validateBufferRange(buffer: Uint8Array, offset: number, length: number): void {\n if (\n !Number.isSafeInteger(offset) ||\n !Number.isSafeInteger(length) ||\n offset < 0 ||\n length < 0 ||\n offset + length > buffer.byteLength\n ) {\n throw new FsError(\"EINVAL\", \"buffer range is invalid\");\n }\n }\n\n #preflightCommit(record: TxnRecord): PreparedCommit {\n this.#assertOpen();\n const projection = prepareTxnProjection(this.#store.state, record);\n const deferResize = this.#isDeferrableResize(record);\n const pending = this.#pendingResizeCommit;\n const replacesPendingResize =\n deferResize && pending !== undefined && record.kind === \"resizeFile\" && pending.record.inodeId === record.inodeId;\n const materializedRecord: TxnRecord = replacesPendingResize\n ? {\n ...record,\n allocated: mergeExtentRuns(pending.record.allocated, record.allocated),\n }\n : record;\n const sequence = replacesPendingResize ? pending.sequence : this.#store.nextSequence;\n const frameBytes = txnFrameBytes(materializedRecord);\n const frame = deferResize\n ? undefined\n : encodeTxnFrame({\n generation: this.#store.state.generation,\n sequence,\n record: materializedRecord,\n });\n const projectedLogBytes = replacesPendingResize\n ? this.#store.activeLogBytes - pending.frameBytes + frameBytes\n : this.#store.activeLogBytes + frameBytes;\n if (\n (!replacesPendingResize && this.#store.activeLogFrames >= MAX_ACTIVE_LOG_FRAMES) ||\n projectedLogBytes > MAX_ACTIVE_LOG_BYTES\n ) {\n throw new StoreLimitError(\"active metadata log reached its hard limit\");\n }\n return {\n frame,\n frameBytes,\n projection,\n materializedRecord,\n deferResize,\n replacesPendingResize,\n };\n }\n\n #commit(record: TxnRecord, preparedCommit?: PreparedCommit): void {\n this.#assertOpen();\n const prepared = preparedCommit ?? this.#preflightCommit(record);\n if (prepared.replacesPendingResize) {\n const pending = this.#pendingResizeCommit;\n if (pending === undefined || prepared.materializedRecord.kind !== \"resizeFile\") {\n const cause = new Error(\"pending resize preflight no longer matches live state\");\n this.#poison(cause);\n throw cause;\n }\n try {\n applyTxn(this.#store.state, record, prepared.projection);\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n this.#store.activeLogBytes += prepared.frameBytes - pending.frameBytes;\n this.#pendingResizeCommit = {\n record: prepared.materializedRecord,\n frameBytes: prepared.frameBytes,\n sequence: pending.sequence,\n };\n this.#scheduleRepack();\n return;\n }\n\n this.#materializePendingResize();\n if (prepared.deferResize && prepared.materializedRecord.kind === \"resizeFile\") {\n try {\n applyTxn(this.#store.state, record, prepared.projection);\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n this.#pendingResizeCommit = {\n record: prepared.materializedRecord,\n frameBytes: prepared.frameBytes,\n sequence: this.#store.nextSequence,\n };\n this.#store.activeLogBytes += prepared.frameBytes;\n this.#store.activeLogFrames += 1;\n this.#store.nextSequence += 1n;\n this.#scheduleRepack();\n return;\n }\n\n if (prepared.frame === undefined) {\n const cause = new Error(\"immediate commit has no encoded transaction frame\");\n this.#poison(cause);\n throw cause;\n }\n this.#appendFrame(prepared.frame);\n try {\n applyTxn(this.#store.state, record, prepared.projection);\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n this.#store.activeLogBytes += prepared.frameBytes;\n this.#store.activeLogFrames += 1;\n this.#store.nextSequence += 1n;\n this.#scheduleRepack();\n }\n\n #isDeferrableResize(record: TxnRecord): record is Extract<TxnRecord, { kind: \"resizeFile\" }> {\n if (record.kind !== \"resizeFile\" || record.operation !== \"write\") return false;\n const inode = this.#store.state.inodes.get(record.inodeId);\n return inode?.kind === \"file\" && record.size > inode.size;\n }\n\n #appendFrame(frame: Uint8Array): void {\n const activeName = metadataFileName(this.#store.state.activeMetadataFile);\n try {\n writeExact(this.#store.handles[activeName], this.#store.activeLogEnd, frame, \"metadata.log.append\");\n this.#metadataDirtySinceFlush = true;\n this.#store.activeLogEnd += BigInt(frame.byteLength);\n } catch (cause) {\n this.#failStore(cause);\n }\n }\n\n #materializePendingResize(): void {\n const pending = this.#pendingResizeCommit;\n if (pending === undefined) return;\n let frame: Uint8Array;\n try {\n frame = encodeTxnFrame({\n generation: this.#store.state.generation,\n sequence: pending.sequence,\n record: pending.record,\n });\n if (frame.byteLength !== pending.frameBytes) {\n throw new Error(\"pending resize frame length changed after preflight\");\n }\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n this.#appendFrame(frame);\n this.#pendingResizeCommit = undefined;\n }\n\n #scheduleRepack(): void {\n if (this.#store.activeLogBytes >= SOFT_ACTIVE_LOG_BYTES) {\n this.#pendingRepackReason = \"log-bytes\";\n } else if (this.#store.activeLogFrames >= SOFT_ACTIVE_LOG_FRAMES) {\n this.#pendingRepackReason = \"log-frames\";\n } else if (this.#store.state.basePayloadBytes >= BASE_REPACK_PRESSURE_BYTES) {\n this.#pendingRepackReason = \"writer-limit\";\n } else if (\n this.#store.state.allocator.quarantine.size >= QUARANTINE_PRESSURE_EXTENTS ||\n (this.#store.state.allocator.quarantine.size > 0 && this.#store.state.allocator.available.size === 0)\n ) {\n this.#pendingRepackReason ??= \"quarantine-pressure\";\n }\n }\n\n #dueRepackReason(nowMs: number): RepackReason | null {\n if (this.#pendingRepackReason !== null) return this.#pendingRepackReason;\n if (this.#store.activeLogBytes >= SOFT_ACTIVE_LOG_BYTES) return \"log-bytes\";\n if (this.#store.activeLogFrames >= SOFT_ACTIVE_LOG_FRAMES) return \"log-frames\";\n if (this.#store.state.basePayloadBytes >= BASE_REPACK_PRESSURE_BYTES) {\n return \"writer-limit\";\n }\n return this.#store.activeLogFrames > 0 && nowMs - this.#lastRepackAtMs >= REPACK_INTERVAL_MS ? \"time\" : null;\n }\n\n #assertOpen(): void {\n if (this.#status === \"failed\") throw new StoreFailedError(this.#failure);\n if (this.#status === \"closed\") throw new StoreClosedError();\n }\n\n #poison(cause: unknown): void {\n if (this.#status === \"open\") {\n this.#status = \"failed\";\n this.#failure = cause;\n }\n }\n\n /**\n * The poison rule for a platform write the store could not complete: an arena write that made no\n * progress (the platform threw before confirming a byte, so what the range now holds is unknown) or a\n * metadata-log append (ambiguous by construction). Continuing would build on bytes nobody can vouch\n * for, so the store poisons itself, and this call — like every later one until close — throws the\n * coded `StoreFailedError` (`code` EIO) carrying the platform's error as its cause. The code is what\n * lets an engine's errno bridge report an I/O error instead of an exception it cannot map.\n */\n #failStore(cause: unknown): never {\n this.#poison(cause);\n throw new StoreFailedError(this.#failure);\n }\n}\n",
10
+ "import { FsError, StoreLimitError } from \"./errors\";\nimport {\n checkedAdd,\n checkedU64,\n MAX_EXTENTS_PER_INODE,\n MAX_FRAME_PAYLOAD_BYTES,\n MAX_INODES,\n MAX_METADATA_BASE_WRITER_BYTES,\n MAX_PATH_BYTES,\n MAX_PATH_DEPTH,\n MAX_SYMLINK_HOPS,\n MAX_TOTAL_EXTENTS,\n MAX_U64,\n validateExtentSize,\n} from \"./limits\";\nimport { encodedUtf8Length, parsePath, validatePathComponent, validateSymlinkTarget } from \"./path\";\n\nexport type InodeId = bigint;\nexport type ExtentId = bigint;\nexport type MetadataFile = \"a\" | \"b\";\n\nexport function otherMetadataFile(file: MetadataFile): MetadataFile {\n return file === \"a\" ? \"b\" : \"a\";\n}\n\ninterface BaseInode {\n id: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n}\n\nexport interface DirectoryInode extends BaseInode {\n kind: \"directory\";\n children: Map<string, InodeId>;\n}\n\nexport interface FileInode extends BaseInode {\n kind: \"file\";\n size: bigint;\n extents: ExtentId[];\n}\n\n/**\n * A symbolic link. It owns no extents and no children — the whole entry IS its absolute `target`,\n * which path resolution restarts the walk at. See {@link validateSymlinkTarget} for why relative\n * targets are refused.\n */\nexport interface SymlinkInode extends BaseInode {\n kind: \"symlink\";\n target: string;\n}\n\nexport type Inode = DirectoryInode | FileInode | SymlinkInode;\n\nexport interface OrphanRecord {\n inodeId: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n size: bigint;\n extents: ExtentId[];\n}\n\nexport function makeOrphanRecord(inode: FileInode): OrphanRecord {\n return {\n inodeId: inode.id,\n mode: inode.mode,\n atimeMs: inode.atimeMs,\n mtimeMs: inode.mtimeMs,\n ctimeMs: inode.ctimeMs,\n size: inode.size,\n extents: [...inode.extents],\n };\n}\n\nexport class IndexedExtentSet {\n readonly #items: ExtentId[] = [];\n readonly #indexes = new Map<ExtentId, number>();\n\n get size(): number {\n return this.#items.length;\n }\n\n has(extentId: ExtentId): boolean {\n return this.#indexes.has(extentId);\n }\n\n add(extentId: ExtentId): void {\n if (this.#indexes.has(extentId)) {\n return;\n }\n this.#indexes.set(extentId, this.#items.length);\n this.#items.push(extentId);\n }\n\n delete(extentId: ExtentId): boolean {\n const index = this.#indexes.get(extentId);\n if (index === undefined) {\n return false;\n }\n const last = this.#items.pop();\n this.#indexes.delete(extentId);\n if (last !== undefined && index < this.#items.length) {\n this.#items[index] = last;\n this.#indexes.set(last, index);\n }\n return true;\n }\n\n values(): readonly ExtentId[] {\n return this.#items;\n }\n\n peekLast(count: number): ExtentId[] {\n if (!Number.isSafeInteger(count) || count < 0 || count > this.#items.length) {\n throw new StoreLimitError(\"invalid available-extent selection count\");\n }\n return this.#items.slice(this.#items.length - count).reverse();\n }\n\n clone(): IndexedExtentSet {\n const copy = new IndexedExtentSet();\n for (const extentId of this.#items) {\n copy.add(extentId);\n }\n return copy;\n }\n}\n\nexport interface AllocatorState {\n totalExtents: bigint;\n ownedBy: Map<ExtentId, InodeId>;\n available: IndexedExtentSet;\n quarantine: Map<ExtentId, bigint | null>;\n}\n\nexport interface VfsState {\n generation: bigint;\n nextInodeId: bigint;\n rootInodeId: bigint;\n extentSize: number;\n activeMetadataFile: MetadataFile;\n retainedGenerations: Record<MetadataFile, bigint | null>;\n basePayloadBytes: number;\n inodes: Map<InodeId, Inode>;\n parentByInode: Map<InodeId, { parentId: InodeId; name: string }>;\n allocator: AllocatorState;\n}\n\nexport interface CreateDirectoryChoice {\n parentId: InodeId;\n name: string;\n inodeId: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n}\n\nexport interface ExtentRun {\n start: ExtentId;\n count: number;\n}\n\nexport type TxnRecord =\n | {\n kind: \"createDirectories\";\n entries: readonly CreateDirectoryChoice[];\n }\n | {\n kind: \"createFile\";\n parentId: InodeId;\n name: string;\n inodeId: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n size: bigint;\n extents: readonly ExtentRun[];\n }\n | {\n kind: \"removeFile\";\n parentId: InodeId;\n name: string;\n parentMtimeMs: bigint;\n parentCtimeMs: bigint;\n }\n | {\n kind: \"changeMode\";\n inodeId: InodeId;\n mode: number;\n ctimeMs: bigint;\n }\n | {\n kind: \"changeTimes\";\n inodeId: InodeId;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n }\n | {\n kind: \"resizeFile\";\n operation: \"truncate\" | \"write\";\n inodeId: InodeId;\n size: bigint;\n allocated: readonly ExtentRun[];\n mtimeMs: bigint;\n ctimeMs: bigint;\n }\n | {\n kind: \"removeDirectory\";\n parentId: InodeId;\n name: string;\n parentMtimeMs: bigint;\n parentCtimeMs: bigint;\n }\n | {\n kind: \"rename\";\n sourceParentId: InodeId;\n sourceName: string;\n destinationParentId: InodeId;\n destinationName: string;\n timestampMs: bigint;\n }\n | {\n kind: \"createSymlink\";\n parentId: InodeId;\n name: string;\n inodeId: InodeId;\n mode: number;\n atimeMs: bigint;\n mtimeMs: bigint;\n ctimeMs: bigint;\n target: string;\n }\n | {\n kind: \"reserveQuarantine\";\n extents: readonly ExtentRun[];\n };\n\nexport interface TxnPlan<RecordType extends TxnRecord = TxnRecord> {\n record: RecordType;\n}\n\nexport interface PreflightLimits {\n maxFramePayloadBytes: number;\n maxBasePayloadBytes: number;\n}\n\nconst BASE_STATE_FIXED_BYTES = 20;\nconst DIRECTORY_INODE_FIXED_BYTES = 41;\nconst FILE_INODE_FIXED_BYTES = 49;\n/** The common inode header plus the target's `u16` length prefix; the target bytes are added on. */\nconst SYMLINK_INODE_FIXED_BYTES = 39;\nconst CHILD_FIXED_BYTES = 10;\n/** The mode a symbolic link carries: `S_IFLNK | 0777`, the only mode POSIX gives a link. */\nexport const SYMLINK_MODE = 0o120777;\n\nfunction childBaseBytes(name: string): number {\n return CHILD_FIXED_BYTES + encodedUtf8Length(name);\n}\n\nfunction inodeBaseBytes(inode: Inode): number {\n if (inode.kind === \"file\") {\n return FILE_INODE_FIXED_BYTES + inode.extents.length * 8;\n }\n if (inode.kind === \"symlink\") {\n return SYMLINK_INODE_FIXED_BYTES + encodedUtf8Length(inode.target);\n }\n let bytes = DIRECTORY_INODE_FIXED_BYTES;\n for (const name of inode.children.keys()) {\n bytes += childBaseBytes(name);\n }\n return bytes;\n}\n\nexport function estimateMetadataBasePayloadBytes(state: VfsState): number {\n let bytes = BASE_STATE_FIXED_BYTES;\n for (const inode of state.inodes.values()) {\n bytes += inodeBaseBytes(inode);\n }\n bytes += state.allocator.available.size * 8;\n bytes += state.allocator.quarantine.size * 16;\n return bytes;\n}\n\nfunction extentRunsPayloadBytes(runs: readonly ExtentRun[]): number {\n return 4 + runs.length * 12;\n}\n\nexport function estimateTxnPayloadBytes(record: TxnRecord): number {\n switch (record.kind) {\n case \"createDirectories\":\n return 5 + record.entries.reduce((bytes, entry) => bytes + 8 + 2 + encodedUtf8Length(entry.name) + 8 + 4 + 24, 0);\n case \"createFile\":\n return 1 + 8 + 2 + encodedUtf8Length(record.name) + 8 + 4 + 24 + 8 + extentRunsPayloadBytes(record.extents);\n case \"removeFile\":\n case \"removeDirectory\":\n return 1 + 8 + 2 + encodedUtf8Length(record.name) + 16;\n case \"changeMode\":\n return 1 + 8 + 4 + 8;\n case \"changeTimes\":\n return 1 + 8 + 24;\n case \"resizeFile\":\n return 1 + 1 + 8 + 8 + extentRunsPayloadBytes(record.allocated) + 16;\n case \"rename\":\n return 1 + 8 + 2 + encodedUtf8Length(record.sourceName) + 8 + 2 + encodedUtf8Length(record.destinationName) + 8;\n case \"createSymlink\":\n return 1 + 8 + 2 + encodedUtf8Length(record.name) + 8 + 4 + 24 + 2 + encodedUtf8Length(record.target);\n case \"reserveQuarantine\":\n return 1 + extentRunsPayloadBytes(record.extents);\n }\n}\n\nfunction selectedExtentsAlreadyAvailable(state: VfsState, runs: readonly ExtentRun[]): number {\n let count = 0;\n for (const extentId of expandExtentRuns(runs, MAX_EXTENTS_PER_INODE)) {\n if (extentId < state.allocator.totalExtents) {\n count += 1;\n }\n }\n return count;\n}\n\nfunction projectedBaseDelta(state: VfsState, record: TxnRecord): number {\n switch (record.kind) {\n case \"createDirectories\":\n return record.entries.reduce(\n (bytes, entry) => bytes + DIRECTORY_INODE_FIXED_BYTES + childBaseBytes(entry.name),\n 0,\n );\n case \"createFile\": {\n const extentCount = expandExtentRuns(record.extents, MAX_EXTENTS_PER_INODE).length;\n const reused = selectedExtentsAlreadyAvailable(state, record.extents);\n return FILE_INODE_FIXED_BYTES + extentCount * 8 + childBaseBytes(record.name) - reused * 8;\n }\n case \"removeFile\": {\n const parent = directoryById(state, record.parentId);\n const inodeId = parent.children.get(record.name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined || inode.kind === \"directory\") {\n throw new FsError(\"ENOENT\", \"file does not exist\");\n }\n const quarantined = inode.kind === \"file\" ? inode.extents.length * 16 : 0;\n return -inodeBaseBytes(inode) - childBaseBytes(record.name) + quarantined;\n }\n case \"changeMode\":\n case \"changeTimes\":\n return 0;\n case \"resizeFile\": {\n const inode = fileById(state, record.inodeId);\n const required = extentCountForSize(record.size, state.extentSize);\n const allocatedCount = Math.max(0, required - inode.extents.length);\n const releasedCount = Math.max(0, inode.extents.length - required);\n const reused = selectedExtentsAlreadyAvailable(state, record.allocated);\n return (allocatedCount - releasedCount) * 8 - reused * 8 + releasedCount * 16;\n }\n case \"removeDirectory\": {\n const parent = directoryById(state, record.parentId);\n const inodeId = parent.children.get(record.name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode?.kind !== \"directory\") {\n throw new FsError(\"ENOENT\", \"directory does not exist\");\n }\n return -inodeBaseBytes(inode) - childBaseBytes(record.name);\n }\n case \"rename\": {\n const sourceParent = directoryById(state, record.sourceParentId);\n const destinationParent = directoryById(state, record.destinationParentId);\n const destinationId = destinationParent.children.get(record.destinationName);\n const destination = destinationId === undefined ? undefined : state.inodes.get(destinationId);\n let delta = -childBaseBytes(record.sourceName);\n if (destination === undefined) {\n delta += childBaseBytes(record.destinationName);\n } else {\n delta -= inodeBaseBytes(destination);\n if (destination.kind === \"file\") {\n delta += destination.extents.length * 16;\n }\n }\n const sourceId = sourceParent.children.get(record.sourceName);\n if (sourceId === undefined) {\n throw new FsError(\"ENOENT\", \"rename source does not exist\");\n }\n return delta;\n }\n case \"createSymlink\":\n return SYMLINK_INODE_FIXED_BYTES + encodedUtf8Length(record.target) + childBaseBytes(record.name);\n case \"reserveQuarantine\": {\n const count = expandExtentRuns(record.extents, MAX_EXTENTS_PER_INODE).length;\n const reused = selectedExtentsAlreadyAvailable(state, record.extents);\n return count * 16 - reused * 8;\n }\n }\n}\n\nexport function preflightTxn(\n state: VfsState,\n record: TxnRecord,\n limits: PreflightLimits = {\n maxFramePayloadBytes: MAX_FRAME_PAYLOAD_BYTES,\n maxBasePayloadBytes: MAX_METADATA_BASE_WRITER_BYTES,\n },\n): number {\n const payloadBytes = estimateTxnPayloadBytes(record);\n if (payloadBytes > limits.maxFramePayloadBytes) {\n throw new StoreLimitError(`transaction payload would exceed ${limits.maxFramePayloadBytes} bytes`);\n }\n const projected = state.basePayloadBytes + projectedBaseDelta(state, record);\n if (!Number.isSafeInteger(projected) || projected < 0 || projected > limits.maxBasePayloadBytes) {\n throw new StoreLimitError(`metadata base would exceed ${limits.maxBasePayloadBytes} bytes`);\n }\n return projected;\n}\n\nconst PREPARED_TXN_PROJECTION = Symbol(\"prepared transaction projection\");\n\nexport interface PreparedTxnProjection {\n readonly projectedBasePayloadBytes: number;\n readonly state: VfsState;\n readonly record: TxnRecord;\n readonly [PREPARED_TXN_PROJECTION]: true;\n}\n\n/** @internal Bind one projected size to the exact live state and record it preflighted. */\nexport function prepareTxnProjection(state: VfsState, record: TxnRecord): PreparedTxnProjection {\n return {\n projectedBasePayloadBytes: preflightTxn(state, record),\n state,\n record,\n [PREPARED_TXN_PROJECTION]: true,\n };\n}\n\nfunction checkedPlan<RecordType extends TxnRecord>(state: VfsState, record: RecordType): TxnPlan<RecordType> {\n preflightTxn(state, record);\n return { record };\n}\n\nexport function createInitialState(extentSize: number): VfsState {\n validateExtentSize(extentSize);\n const root: DirectoryInode = {\n id: 1n,\n kind: \"directory\",\n mode: 0o40777,\n atimeMs: 0n,\n mtimeMs: 0n,\n ctimeMs: 0n,\n children: new Map(),\n };\n return {\n generation: 1n,\n nextInodeId: 2n,\n rootInodeId: root.id,\n extentSize,\n activeMetadataFile: \"a\",\n retainedGenerations: { a: 1n, b: null },\n basePayloadBytes: BASE_STATE_FIXED_BYTES + DIRECTORY_INODE_FIXED_BYTES,\n inodes: new Map([[root.id, root]]),\n parentByInode: new Map(),\n allocator: {\n totalExtents: 0n,\n ownedBy: new Map(),\n available: new IndexedExtentSet(),\n quarantine: new Map(),\n },\n };\n}\n\nfunction validateMode(mode: number): number {\n if (!Number.isSafeInteger(mode) || mode < 0 || mode > 0xffff_ffff) {\n throw new FsError(\"EINVAL\", \"mode must be an unsigned 32-bit integer\");\n }\n return mode;\n}\n\nfunction validateTimestamp(timestamp: bigint): bigint {\n return checkedU64(timestamp, \"timestamp\");\n}\n\nfunction advanceNextInodeId(inodeId: InodeId): InodeId {\n if (inodeId === MAX_U64) {\n throw new StoreLimitError(\"next inode ID is exhausted; the store must be recreated\");\n }\n return checkedAdd(inodeId, 1n, \"next inode ID\");\n}\n\nfunction directoryById(state: VfsState, inodeId: InodeId): DirectoryInode {\n const inode = state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"directory does not exist\");\n }\n if (inode.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path component is not a directory\");\n }\n return inode;\n}\n\nfunction inodeById(state: VfsState, inodeId: InodeId): Inode {\n const inode = state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"inode does not exist\");\n }\n return inode;\n}\n\nfunction fileById(state: VfsState, inodeId: InodeId): FileInode {\n const inode = inodeById(state, inodeId);\n if (inode.kind !== \"file\") {\n throw new FsError(\"EISDIR\", \"inode is not a file\");\n }\n return inode;\n}\n\nfunction joinPath(base: string, rest: readonly string[]): string {\n if (rest.length === 0) return base;\n return base === \"/\" ? `/${rest.join(\"/\")}` : `${base}/${rest.join(\"/\")}`;\n}\n\nfunction parentAndName(state: VfsState, path: string): { parent: DirectoryInode; name: string } {\n const components = parsePath(path);\n const name = components.pop();\n if (name === undefined) {\n throw new FsError(\"EINVAL\", \"operation is not permitted on root\", { path });\n }\n let parent = directoryById(state, state.rootInodeId);\n for (const component of components) {\n const childId = parent.children.get(component);\n if (childId === undefined) {\n throw new FsError(\"ENOENT\", \"parent directory does not exist\", { path });\n }\n parent = directoryById(state, childId);\n }\n return { parent, name };\n}\n\nfunction extentCountForSize(size: bigint, extentSize: number): number {\n checkedU64(size, \"file size\");\n if (size === 0n) {\n return 0;\n }\n const count = (size + BigInt(extentSize) - 1n) / BigInt(extentSize);\n if (count > BigInt(MAX_EXTENTS_PER_INODE)) {\n throw new StoreLimitError(`file would exceed ${MAX_EXTENTS_PER_INODE} extents`);\n }\n return Number(count);\n}\n\nexport function toExtentRuns(extents: readonly ExtentId[]): ExtentRun[] {\n const runs: ExtentRun[] = [];\n for (const extentId of extents) {\n checkedU64(extentId, \"extent ID\");\n const last = runs.at(-1);\n if (last !== undefined && last.start + BigInt(last.count) === extentId && last.count < 0xffff_ffff) {\n last.count += 1;\n } else {\n runs.push({ start: extentId, count: 1 });\n }\n }\n return runs;\n}\n\nexport function expandExtentRuns(runs: readonly ExtentRun[], maximum: number): ExtentId[] {\n const extents: ExtentId[] = [];\n for (const run of runs) {\n checkedU64(run.start, \"extent run start\");\n if (!Number.isSafeInteger(run.count) || run.count <= 0) {\n throw new FsError(\"EINVAL\", \"extent run count must be a positive safe integer\");\n }\n if (extents.length + run.count > maximum) {\n throw new StoreLimitError(`extent list exceeds ${maximum} entries`);\n }\n for (let offset = 0; offset < run.count; offset += 1) {\n extents.push(checkedAdd(run.start, BigInt(offset), \"extent ID\"));\n }\n }\n return extents;\n}\n\nfunction chooseExtents(state: VfsState, count: number): ExtentId[] {\n if (count > MAX_EXTENTS_PER_INODE) {\n throw new StoreLimitError(`allocation exceeds ${MAX_EXTENTS_PER_INODE} extents`);\n }\n const availableCount = Math.min(count, state.allocator.available.size);\n const chosen = state.allocator.available.peekLast(availableCount);\n const freshCount = count - availableCount;\n if (state.allocator.totalExtents + BigInt(freshCount) > BigInt(MAX_TOTAL_EXTENTS)) {\n throw new StoreLimitError(`total extent count would exceed ${MAX_TOTAL_EXTENTS}`);\n }\n for (let offset = 0; offset < freshCount; offset += 1) {\n chosen.push(state.allocator.totalExtents + BigInt(offset));\n }\n return chosen;\n}\n\nexport function getInodeAtPath(state: VfsState, path: string): Inode {\n const components = parsePath(path);\n let inode = state.inodes.get(state.rootInodeId);\n if (inode === undefined) {\n throw new StoreLimitError(\"root inode is missing\");\n }\n for (const component of components) {\n if (inode.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path component is not a directory\", { path });\n }\n const childId = inode.children.get(component);\n if (childId === undefined) {\n throw new FsError(\"ENOENT\", \"path does not exist\", { path });\n }\n const child = state.inodes.get(childId);\n if (child === undefined) {\n throw new StoreLimitError(\"directory entry references a missing inode\");\n }\n inode = child;\n }\n return inode;\n}\n\n/**\n * Resolve every symbolic link on `path` and report the link-free absolute path it names.\n *\n * `follow` governs the FINAL component only — the POSIX `stat`/`lstat` split. Every INTERMEDIATE\n * link is always followed, because a path can only continue through the thing a link points at.\n *\n * A component that does not exist, or one whose parent turned out not to be a directory, stops the\n * walk and the remainder is carried through verbatim: resolution answers \"which path does this\n * name\", not \"does it exist\". The operation that follows reports `ENOENT`/`ENOTDIR` itself, or\n * creates the tail — which is exactly what an `open(O_CREAT)` through a symlinked directory needs.\n *\n * Targets are absolute, so a hop restarts the walk at the root. `MAX_SYMLINK_HOPS` hops is `ELOOP`,\n * and each expansion is re-validated by `parsePath`, so a chain that outgrows the store's depth or\n * byte limits is rejected here rather than in a planner.\n */\nexport function resolveLinks(state: VfsState, path: string, follow: boolean): string {\n const root = state.inodes.get(state.rootInodeId);\n if (root === undefined) {\n throw new StoreLimitError(\"root inode is missing\");\n }\n let pending = parsePath(path);\n let index = 0;\n let current: Inode = root;\n const resolved: string[] = [];\n let hops = 0;\n while (index < pending.length) {\n const name = pending[index]!;\n if (current.kind !== \"directory\") break;\n const childId = current.children.get(name);\n if (childId === undefined) break;\n const child = state.inodes.get(childId);\n if (child === undefined) {\n throw new StoreLimitError(\"directory entry references a missing inode\");\n }\n if (child.kind === \"symlink\" && (follow || index < pending.length - 1)) {\n hops += 1;\n if (hops > MAX_SYMLINK_HOPS) {\n throw new FsError(\"ELOOP\", `path traverses more than ${MAX_SYMLINK_HOPS} symbolic links`, { path });\n }\n pending = parsePath(joinPath(child.target, pending.slice(index + 1)));\n index = 0;\n current = root;\n resolved.length = 0;\n continue;\n }\n resolved.push(name);\n current = child;\n index += 1;\n }\n return joinPath(`/${resolved.join(\"/\")}`, pending.slice(index));\n}\n\nexport function planMkdir(\n state: VfsState,\n path: string,\n options: { recursive?: boolean; mode?: number; nowMs: bigint },\n): TxnPlan<Extract<TxnRecord, { kind: \"createDirectories\" }>> {\n const components = parsePath(path);\n if (components.length === 0) {\n throw new FsError(\"EEXIST\", \"root directory already exists\", { operation: \"mkdir\", path });\n }\n const mode = validateMode(options.mode ?? 0o40777);\n const nowMs = validateTimestamp(options.nowMs);\n const entries: CreateDirectoryChoice[] = [];\n let parent = directoryById(state, state.rootInodeId);\n let nextInodeId = state.nextInodeId;\n\n for (let index = 0; index < components.length; index += 1) {\n const name = components[index]!;\n const existingId = parent.children.get(name);\n if (existingId !== undefined) {\n const existing = state.inodes.get(existingId);\n if (existing?.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path component is not a directory\", { operation: \"mkdir\", path });\n }\n if (index === components.length - 1) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"mkdir\", path });\n }\n parent = existing;\n continue;\n }\n if (!options.recursive && index !== components.length - 1) {\n throw new FsError(\"ENOENT\", \"parent directory does not exist\", { operation: \"mkdir\", path });\n }\n if (state.inodes.size + entries.length >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n checkedU64(nextInodeId, \"next inode ID\");\n const followingInodeId = advanceNextInodeId(nextInodeId);\n const entry: CreateDirectoryChoice = {\n parentId: parent.id,\n name,\n inodeId: nextInodeId,\n mode,\n atimeMs: nowMs,\n mtimeMs: nowMs,\n ctimeMs: nowMs,\n };\n entries.push(entry);\n parent = { ...entry, kind: \"directory\", id: entry.inodeId, children: new Map() };\n nextInodeId = followingInodeId;\n }\n\n if (entries.length === 0) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"mkdir\", path });\n }\n return checkedPlan(state, { kind: \"createDirectories\", entries });\n}\n\nexport function planCreateFile(\n state: VfsState,\n path: string,\n options: { mode?: number; nowMs: bigint; size?: bigint },\n): TxnPlan<Extract<TxnRecord, { kind: \"createFile\" }>> {\n const { parent, name } = parentAndName(state, path);\n if (parent.children.has(name)) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"writeFile\", path });\n }\n if (state.inodes.size >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n const inodeId = checkedU64(state.nextInodeId, \"next inode ID\");\n advanceNextInodeId(inodeId);\n const mode = validateMode(options.mode ?? 0o100666);\n const nowMs = validateTimestamp(options.nowMs);\n const size = checkedU64(options.size ?? 0n, \"file size\");\n const extents = toExtentRuns(chooseExtents(state, extentCountForSize(size, state.extentSize)));\n return checkedPlan(state, {\n kind: \"createFile\",\n parentId: parent.id,\n name,\n inodeId,\n mode,\n atimeMs: nowMs,\n mtimeMs: nowMs,\n ctimeMs: nowMs,\n size,\n extents,\n });\n}\n\n/** A symbolic link. Nothing about the TARGET is consulted — the link entry is the whole record. */\nexport function planSymlink(\n state: VfsState,\n path: string,\n target: string,\n options: { mode?: number; nowMs: bigint },\n): TxnPlan<Extract<TxnRecord, { kind: \"createSymlink\" }>> {\n const { parent, name } = parentAndName(state, path);\n if (parent.children.has(name)) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"symlink\", path });\n }\n if (state.inodes.size >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n validateSymlinkTarget(target);\n const inodeId = checkedU64(state.nextInodeId, \"next inode ID\");\n advanceNextInodeId(inodeId);\n const nowMs = validateTimestamp(options.nowMs);\n return checkedPlan(state, {\n kind: \"createSymlink\",\n parentId: parent.id,\n name,\n inodeId,\n mode: validateMode(options.mode ?? SYMLINK_MODE),\n atimeMs: nowMs,\n mtimeMs: nowMs,\n ctimeMs: nowMs,\n target,\n });\n}\n\n/** Removes a FILE or a SYMBOLIC LINK. A link is unlinked as itself; its target is never touched. */\nexport function planUnlink(\n state: VfsState,\n path: string,\n nowMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"removeFile\" }>> {\n const { parent, name } = parentAndName(state, path);\n const inodeId = parent.children.get(name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"path does not exist\", { operation: \"unlink\", path });\n }\n if (inode.kind === \"directory\") {\n throw new FsError(\"EISDIR\", \"path is a directory\", { operation: \"unlink\", path });\n }\n const timestamp = validateTimestamp(nowMs);\n return checkedPlan(state, {\n kind: \"removeFile\",\n parentId: parent.id,\n name,\n parentMtimeMs: timestamp,\n parentCtimeMs: timestamp,\n });\n}\n\nexport function planChmod(\n state: VfsState,\n path: string,\n mode: number,\n nowMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"changeMode\" }>> {\n const inode = getInodeAtPath(state, path);\n return checkedPlan(state, {\n kind: \"changeMode\",\n inodeId: inode.id,\n mode: validateMode(mode),\n ctimeMs: validateTimestamp(nowMs),\n });\n}\n\nexport function planUtimes(\n state: VfsState,\n path: string,\n atimeMs: bigint,\n mtimeMs: bigint,\n ctimeMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"changeTimes\" }>> {\n const inode = getInodeAtPath(state, path);\n return checkedPlan(state, {\n kind: \"changeTimes\",\n inodeId: inode.id,\n atimeMs: validateTimestamp(atimeMs),\n mtimeMs: validateTimestamp(mtimeMs),\n ctimeMs: validateTimestamp(ctimeMs),\n });\n}\n\nexport function planResizeFile(\n state: VfsState,\n path: string,\n size: bigint,\n nowMs: bigint,\n operation: \"truncate\" | \"write\",\n): TxnPlan<Extract<TxnRecord, { kind: \"resizeFile\" }>> {\n const inode = getInodeAtPath(state, path);\n if (inode.kind !== \"file\") {\n throw new FsError(\"EISDIR\", \"path is a directory\", { operation, path });\n }\n return planResizeFileForInode(state, inode, size, nowMs, operation);\n}\n\n/** @internal Inode-first planner for descriptor operations that already resolved the file. */\nexport function planResizeFileForInode(\n state: VfsState,\n inode: FileInode,\n size: bigint,\n nowMs: bigint,\n operation: \"truncate\" | \"write\",\n): TxnPlan<Extract<TxnRecord, { kind: \"resizeFile\" }>> {\n if (state.inodes.get(inode.id) !== inode) {\n throw new StoreLimitError(\"resize planner requires the current file inode\");\n }\n const checkedSize = checkedU64(size, \"file size\");\n const required = extentCountForSize(checkedSize, state.extentSize);\n const additional = Math.max(0, required - inode.extents.length);\n const timestamp = validateTimestamp(nowMs);\n return checkedPlan(state, {\n kind: \"resizeFile\",\n operation,\n inodeId: inode.id,\n size: checkedSize,\n allocated: toExtentRuns(chooseExtents(state, additional)),\n mtimeMs: timestamp,\n ctimeMs: timestamp,\n });\n}\n\nexport function planRmdir(\n state: VfsState,\n path: string,\n nowMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"removeDirectory\" }>> {\n const { parent, name } = parentAndName(state, path);\n const inodeId = parent.children.get(name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"directory does not exist\", { operation: \"rmdir\", path });\n }\n if (inode.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path is not a directory\", { operation: \"rmdir\", path });\n }\n if (inode.children.size !== 0) {\n throw new FsError(\"ENOTEMPTY\", \"directory is not empty\", { operation: \"rmdir\", path });\n }\n const timestamp = validateTimestamp(nowMs);\n return checkedPlan(state, {\n kind: \"removeDirectory\",\n parentId: parent.id,\n name,\n parentMtimeMs: timestamp,\n parentCtimeMs: timestamp,\n });\n}\n\nfunction directoryContains(state: VfsState, directory: DirectoryInode, candidateId: InodeId): boolean {\n if (directory.id === candidateId) {\n return true;\n }\n for (const childId of directory.children.values()) {\n const child = inodeById(state, childId);\n if (child.kind === \"directory\" && directoryContains(state, child, candidateId)) {\n return true;\n }\n }\n return false;\n}\n\ninterface PathMetrics {\n depth: number;\n bytes: number;\n}\n\nfunction childPathMetrics(parent: PathMetrics, name: string): PathMetrics {\n return {\n depth: parent.depth + 1,\n bytes: parent.bytes + (parent.depth === 0 ? 0 : 1) + encodedUtf8Length(name),\n };\n}\n\nfunction findPathMetrics(state: VfsState, targetId: InodeId): PathMetrics {\n let currentId = targetId;\n let depth = 0;\n let componentBytes = 0;\n const visited = new Set<InodeId>();\n while (currentId !== state.rootInodeId) {\n if (visited.has(currentId)) {\n throw new StoreLimitError(\"inode parent index contains a cycle\");\n }\n visited.add(currentId);\n const entry = state.parentByInode.get(currentId);\n if (entry === undefined) {\n throw new StoreLimitError(\"inode parent index does not reach root\");\n }\n depth += 1;\n componentBytes += encodedUtf8Length(entry.name);\n currentId = entry.parentId;\n }\n return { depth, bytes: 1 + componentBytes + Math.max(0, depth - 1) };\n}\n\nfunction validateRenamedSubtreeBounds(\n state: VfsState,\n source: Inode,\n destinationParent: DirectoryInode,\n destinationName: string,\n): void {\n const visit = (inode: Inode, metrics: PathMetrics): void => {\n if (metrics.depth > MAX_PATH_DEPTH) {\n throw new FsError(\"EINVAL\", `rename would exceed ${MAX_PATH_DEPTH} path components`);\n }\n if (metrics.bytes > MAX_PATH_BYTES) {\n throw new FsError(\"EINVAL\", `rename would exceed ${MAX_PATH_BYTES} UTF-8 path bytes`);\n }\n if (inode.kind === \"directory\") {\n for (const [name, childId] of inode.children) {\n visit(inodeById(state, childId), childPathMetrics(metrics, name));\n }\n }\n };\n const destinationMetrics = findPathMetrics(state, destinationParent.id);\n visit(source, childPathMetrics(destinationMetrics, destinationName));\n}\n\nfunction validateRenameTypes(source: Inode, destination: Inode | undefined): void {\n if (destination === undefined) {\n return;\n }\n if (source.kind !== \"directory\" && destination.kind === \"directory\") {\n throw new FsError(\"EISDIR\", \"cannot replace a directory with a file\");\n }\n if (source.kind === \"directory\" && destination.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"cannot replace a file with a directory\");\n }\n if (destination.kind === \"directory\" && destination.children.size !== 0) {\n throw new FsError(\"ENOTEMPTY\", \"destination directory is not empty\");\n }\n}\n\nexport function planRename(\n state: VfsState,\n oldPath: string,\n newPath: string,\n nowMs: bigint,\n): TxnPlan<Extract<TxnRecord, { kind: \"rename\" }>> {\n if (oldPath === newPath) {\n throw new FsError(\"EINVAL\", \"source and destination are identical\", { operation: \"rename\", path: oldPath });\n }\n const sourceLocation = parentAndName(state, oldPath);\n const destinationLocation = parentAndName(state, newPath);\n const sourceId = sourceLocation.parent.children.get(sourceLocation.name);\n if (sourceId === undefined) {\n throw new FsError(\"ENOENT\", \"rename source does not exist\", { operation: \"rename\", path: oldPath });\n }\n const source = inodeById(state, sourceId);\n const destinationId = destinationLocation.parent.children.get(destinationLocation.name);\n const destination = destinationId === undefined ? undefined : inodeById(state, destinationId);\n validateRenameTypes(source, destination);\n if (source.kind === \"directory\" && directoryContains(state, source, destinationLocation.parent.id)) {\n throw new FsError(\"EINVAL\", \"cannot move a directory into itself\", { operation: \"rename\", path: newPath });\n }\n validateRenamedSubtreeBounds(state, source, destinationLocation.parent, destinationLocation.name);\n return checkedPlan(state, {\n kind: \"rename\",\n sourceParentId: sourceLocation.parent.id,\n sourceName: sourceLocation.name,\n destinationParentId: destinationLocation.parent.id,\n destinationName: destinationLocation.name,\n timestampMs: validateTimestamp(nowMs),\n });\n}\n\nexport function planReserveQuarantine(\n state: VfsState,\n count: number,\n): TxnPlan<Extract<TxnRecord, { kind: \"reserveQuarantine\" }>> {\n if (!Number.isSafeInteger(count) || count <= 0 || count > MAX_EXTENTS_PER_INODE) {\n throw new StoreLimitError(`orphan reservation must contain 1 to ${MAX_EXTENTS_PER_INODE} extents`);\n }\n return checkedPlan(state, {\n kind: \"reserveQuarantine\",\n extents: toExtentRuns(chooseExtents(state, count)),\n });\n}\n\nfunction validateCreateDirectories(state: VfsState, entries: readonly CreateDirectoryChoice[]): void {\n if (entries.length === 0) {\n throw new FsError(\"EINVAL\", \"createDirectories record is empty\");\n }\n const staged = new Map<InodeId, DirectoryInode>();\n const stagedDirectory = (inodeId: InodeId): DirectoryInode => {\n const alreadyStaged = staged.get(inodeId);\n if (alreadyStaged !== undefined) {\n return alreadyStaged;\n }\n const existing = directoryById(state, inodeId);\n const copy = { ...existing, children: new Map(existing.children) };\n staged.set(inodeId, copy);\n return copy;\n };\n let expectedInodeId = state.nextInodeId;\n for (const entry of entries) {\n validatePathComponent(entry.name);\n validateMode(entry.mode);\n validateTimestamp(entry.atimeMs);\n validateTimestamp(entry.mtimeMs);\n validateTimestamp(entry.ctimeMs);\n if (entry.inodeId !== expectedInodeId || entry.inodeId > MAX_U64) {\n throw new FsError(\"EINVAL\", \"createDirectories record has a non-canonical inode sequence\");\n }\n const parent = stagedDirectory(entry.parentId);\n if (parent.children.has(entry.name)) {\n throw new FsError(\"EEXIST\", \"directory entry already exists\");\n }\n const created: DirectoryInode = {\n id: entry.inodeId,\n kind: \"directory\",\n mode: entry.mode,\n atimeMs: entry.atimeMs,\n mtimeMs: entry.mtimeMs,\n ctimeMs: entry.ctimeMs,\n children: new Map(),\n };\n parent.children.set(entry.name, entry.inodeId);\n staged.set(entry.inodeId, created);\n expectedInodeId = advanceNextInodeId(expectedInodeId);\n }\n if (state.inodes.size + entries.length > MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n}\n\nfunction validateExtentAssignment(state: VfsState, runs: readonly ExtentRun[], expectedCount: number): ExtentId[] {\n const extents = expandExtentRuns(runs, MAX_EXTENTS_PER_INODE);\n if (extents.length !== expectedCount) {\n throw new FsError(\"EINVAL\", \"extent choices do not cover the file size exactly\");\n }\n const unique = new Set(extents);\n if (unique.size !== extents.length) {\n throw new FsError(\"EINVAL\", \"extent choices contain a duplicate\");\n }\n let nextFresh = state.allocator.totalExtents;\n for (const extentId of extents) {\n if (extentId < state.allocator.totalExtents) {\n if (!state.allocator.available.has(extentId)) {\n throw new FsError(\"EINVAL\", \"extent choice is not safely available\");\n }\n continue;\n }\n if (extentId !== nextFresh) {\n throw new FsError(\"EINVAL\", \"fresh extent choices must grow the arena contiguously\");\n }\n nextFresh += 1n;\n }\n if (nextFresh > BigInt(MAX_TOTAL_EXTENTS)) {\n throw new StoreLimitError(`total extent count would exceed ${MAX_TOTAL_EXTENTS}`);\n }\n return extents;\n}\n\nfunction applyCreateFile(state: VfsState, record: Extract<TxnRecord, { kind: \"createFile\" }>): void {\n validatePathComponent(record.name);\n const parent = directoryById(state, record.parentId);\n if (parent.children.has(record.name)) {\n throw new FsError(\"EEXIST\", \"directory entry already exists\");\n }\n if (record.inodeId !== state.nextInodeId || state.inodes.has(record.inodeId)) {\n throw new FsError(\"EINVAL\", \"createFile record has a non-canonical inode ID\");\n }\n const nextInodeId = advanceNextInodeId(record.inodeId);\n validateMode(record.mode);\n validateTimestamp(record.atimeMs);\n validateTimestamp(record.mtimeMs);\n validateTimestamp(record.ctimeMs);\n const size = checkedU64(record.size, \"file size\");\n const extents = validateExtentAssignment(state, record.extents, extentCountForSize(size, state.extentSize));\n if (state.inodes.size >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n\n const inode: FileInode = {\n id: record.inodeId,\n kind: \"file\",\n mode: record.mode,\n atimeMs: record.atimeMs,\n mtimeMs: record.mtimeMs,\n ctimeMs: record.ctimeMs,\n size,\n extents,\n };\n for (const extentId of extents) {\n if (extentId < state.allocator.totalExtents) {\n state.allocator.available.delete(extentId);\n } else {\n state.allocator.totalExtents += 1n;\n }\n state.allocator.ownedBy.set(extentId, inode.id);\n }\n parent.children.set(record.name, inode.id);\n state.inodes.set(inode.id, inode);\n state.parentByInode.set(inode.id, { parentId: parent.id, name: record.name });\n state.nextInodeId = nextInodeId;\n}\n\nfunction applyRemoveFile(state: VfsState, record: Extract<TxnRecord, { kind: \"removeFile\" }>): void {\n validatePathComponent(record.name);\n validateTimestamp(record.parentMtimeMs);\n validateTimestamp(record.parentCtimeMs);\n const parent = directoryById(state, record.parentId);\n const inodeId = parent.children.get(record.name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"file does not exist\");\n }\n if (inode.kind === \"directory\") {\n throw new FsError(\"EISDIR\", \"path is a directory\");\n }\n const extents = inode.kind === \"file\" ? inode.extents : [];\n for (const extentId of extents) {\n if (state.allocator.ownedBy.get(extentId) !== inode.id || state.allocator.quarantine.has(extentId)) {\n throw new StoreLimitError(\"file extent ownership is inconsistent\");\n }\n }\n\n parent.children.delete(record.name);\n parent.mtimeMs = record.parentMtimeMs;\n parent.ctimeMs = record.parentCtimeMs;\n state.inodes.delete(inode.id);\n state.parentByInode.delete(inode.id);\n for (const extentId of extents) {\n state.allocator.ownedBy.delete(extentId);\n state.allocator.quarantine.set(extentId, null);\n }\n}\n\nfunction applyCreateSymlink(state: VfsState, record: Extract<TxnRecord, { kind: \"createSymlink\" }>): void {\n validatePathComponent(record.name);\n const parent = directoryById(state, record.parentId);\n if (parent.children.has(record.name)) {\n throw new FsError(\"EEXIST\", \"directory entry already exists\");\n }\n if (record.inodeId !== state.nextInodeId || state.inodes.has(record.inodeId)) {\n throw new FsError(\"EINVAL\", \"createSymlink record has a non-canonical inode ID\");\n }\n const nextInodeId = advanceNextInodeId(record.inodeId);\n validateMode(record.mode);\n validateTimestamp(record.atimeMs);\n validateTimestamp(record.mtimeMs);\n validateTimestamp(record.ctimeMs);\n validateSymlinkTarget(record.target);\n if (state.inodes.size >= MAX_INODES) {\n throw new StoreLimitError(`inode count would exceed ${MAX_INODES}`);\n }\n const inode: SymlinkInode = {\n id: record.inodeId,\n kind: \"symlink\",\n mode: record.mode,\n atimeMs: record.atimeMs,\n mtimeMs: record.mtimeMs,\n ctimeMs: record.ctimeMs,\n target: record.target,\n };\n parent.children.set(record.name, inode.id);\n state.inodes.set(inode.id, inode);\n state.parentByInode.set(inode.id, { parentId: parent.id, name: record.name });\n state.nextInodeId = nextInodeId;\n}\n\nfunction applyChangeMode(state: VfsState, record: Extract<TxnRecord, { kind: \"changeMode\" }>): void {\n const inode = inodeById(state, record.inodeId);\n const mode = validateMode(record.mode);\n const ctimeMs = validateTimestamp(record.ctimeMs);\n inode.mode = mode;\n inode.ctimeMs = ctimeMs;\n}\n\nfunction applyChangeTimes(state: VfsState, record: Extract<TxnRecord, { kind: \"changeTimes\" }>): void {\n const inode = inodeById(state, record.inodeId);\n const atimeMs = validateTimestamp(record.atimeMs);\n const mtimeMs = validateTimestamp(record.mtimeMs);\n const ctimeMs = validateTimestamp(record.ctimeMs);\n inode.atimeMs = atimeMs;\n inode.mtimeMs = mtimeMs;\n inode.ctimeMs = ctimeMs;\n}\n\nfunction applyResizeFile(state: VfsState, record: Extract<TxnRecord, { kind: \"resizeFile\" }>): void {\n const inode = fileById(state, record.inodeId);\n const size = checkedU64(record.size, \"file size\");\n const required = extentCountForSize(size, state.extentSize);\n const additionalCount = Math.max(0, required - inode.extents.length);\n const allocated = validateExtentAssignment(state, record.allocated, additionalCount);\n const retained = required >= inode.extents.length ? inode.extents : inode.extents.slice(0, required);\n const released = inode.extents.slice(required);\n for (const extentId of released) {\n if (state.allocator.ownedBy.get(extentId) !== inode.id || state.allocator.quarantine.has(extentId)) {\n throw new StoreLimitError(\"file extent ownership is inconsistent\");\n }\n }\n const mtimeMs = validateTimestamp(record.mtimeMs);\n const ctimeMs = validateTimestamp(record.ctimeMs);\n\n for (const extentId of allocated) {\n if (extentId < state.allocator.totalExtents) {\n state.allocator.available.delete(extentId);\n } else {\n state.allocator.totalExtents += 1n;\n }\n state.allocator.ownedBy.set(extentId, inode.id);\n retained.push(extentId);\n }\n for (const extentId of released) {\n state.allocator.ownedBy.delete(extentId);\n state.allocator.quarantine.set(extentId, null);\n }\n inode.size = size;\n inode.extents = retained;\n inode.mtimeMs = mtimeMs;\n inode.ctimeMs = ctimeMs;\n}\n\nfunction applyRemoveDirectory(state: VfsState, record: Extract<TxnRecord, { kind: \"removeDirectory\" }>): void {\n validatePathComponent(record.name);\n const parent = directoryById(state, record.parentId);\n const inodeId = parent.children.get(record.name);\n const inode = inodeId === undefined ? undefined : state.inodes.get(inodeId);\n if (inode === undefined) {\n throw new FsError(\"ENOENT\", \"directory does not exist\");\n }\n if (inode.kind !== \"directory\") {\n throw new FsError(\"ENOTDIR\", \"path is not a directory\");\n }\n if (inode.children.size !== 0) {\n throw new FsError(\"ENOTEMPTY\", \"directory is not empty\");\n }\n const mtimeMs = validateTimestamp(record.parentMtimeMs);\n const ctimeMs = validateTimestamp(record.parentCtimeMs);\n parent.children.delete(record.name);\n parent.mtimeMs = mtimeMs;\n parent.ctimeMs = ctimeMs;\n state.inodes.delete(inode.id);\n state.parentByInode.delete(inode.id);\n}\n\nfunction applyRename(state: VfsState, record: Extract<TxnRecord, { kind: \"rename\" }>): void {\n validatePathComponent(record.sourceName);\n validatePathComponent(record.destinationName);\n if (record.sourceParentId === record.destinationParentId && record.sourceName === record.destinationName) {\n throw new FsError(\"EINVAL\", \"rename source and destination are identical\");\n }\n const timestampMs = validateTimestamp(record.timestampMs);\n const sourceParent = directoryById(state, record.sourceParentId);\n const destinationParent = directoryById(state, record.destinationParentId);\n const sourceId = sourceParent.children.get(record.sourceName);\n if (sourceId === undefined) {\n throw new FsError(\"ENOENT\", \"rename source does not exist\");\n }\n const source = inodeById(state, sourceId);\n const destinationId = destinationParent.children.get(record.destinationName);\n const destination = destinationId === undefined ? undefined : inodeById(state, destinationId);\n validateRenameTypes(source, destination);\n if (source.kind === \"directory\" && directoryContains(state, source, destinationParent.id)) {\n throw new FsError(\"EINVAL\", \"cannot move a directory into itself\");\n }\n validateRenamedSubtreeBounds(state, source, destinationParent, record.destinationName);\n if (destination?.kind === \"file\") {\n for (const extentId of destination.extents) {\n if (state.allocator.ownedBy.get(extentId) !== destination.id || state.allocator.quarantine.has(extentId)) {\n throw new StoreLimitError(\"replacement extent ownership is inconsistent\");\n }\n }\n }\n\n sourceParent.children.delete(record.sourceName);\n if (destination !== undefined) {\n destinationParent.children.delete(record.destinationName);\n state.inodes.delete(destination.id);\n state.parentByInode.delete(destination.id);\n if (destination.kind === \"file\") {\n for (const extentId of destination.extents) {\n state.allocator.ownedBy.delete(extentId);\n state.allocator.quarantine.set(extentId, null);\n }\n }\n }\n destinationParent.children.set(record.destinationName, source.id);\n state.parentByInode.set(source.id, {\n parentId: destinationParent.id,\n name: record.destinationName,\n });\n source.ctimeMs = timestampMs;\n sourceParent.mtimeMs = timestampMs;\n sourceParent.ctimeMs = timestampMs;\n destinationParent.mtimeMs = timestampMs;\n destinationParent.ctimeMs = timestampMs;\n}\n\nfunction applyReserveQuarantine(state: VfsState, record: Extract<TxnRecord, { kind: \"reserveQuarantine\" }>): void {\n const declaredCount = record.extents.reduce((sum, run) => sum + run.count, 0);\n if (declaredCount <= 0 || declaredCount > MAX_EXTENTS_PER_INODE) {\n throw new StoreLimitError(\"orphan reservation extent count is outside limits\");\n }\n const extents = validateExtentAssignment(state, record.extents, declaredCount);\n for (const extentId of extents) {\n if (extentId < state.allocator.totalExtents) {\n state.allocator.available.delete(extentId);\n } else {\n state.allocator.totalExtents += 1n;\n }\n state.allocator.quarantine.set(extentId, null);\n }\n}\n\nexport function applyTxn(state: VfsState, record: TxnRecord, prepared?: PreparedTxnProjection): void {\n if (\n prepared !== undefined &&\n (prepared[PREPARED_TXN_PROJECTION] !== true || prepared.state !== state || prepared.record !== record)\n ) {\n throw new StoreLimitError(\"prepared transaction projection does not match the live transition\");\n }\n const projectedBasePayloadBytes = prepared?.projectedBasePayloadBytes ?? preflightTxn(state, record);\n switch (record.kind) {\n case \"createDirectories\":\n validateCreateDirectories(state, record.entries);\n for (const entry of record.entries) {\n const parent = directoryById(state, entry.parentId);\n const created: DirectoryInode = {\n id: entry.inodeId,\n kind: \"directory\",\n mode: entry.mode,\n atimeMs: entry.atimeMs,\n mtimeMs: entry.mtimeMs,\n ctimeMs: entry.ctimeMs,\n children: new Map(),\n };\n parent.children.set(entry.name, created.id);\n state.inodes.set(created.id, created);\n state.parentByInode.set(created.id, { parentId: parent.id, name: entry.name });\n state.nextInodeId = advanceNextInodeId(created.id);\n }\n break;\n case \"createFile\":\n applyCreateFile(state, record);\n break;\n case \"removeFile\":\n applyRemoveFile(state, record);\n break;\n case \"changeMode\":\n applyChangeMode(state, record);\n break;\n case \"changeTimes\":\n applyChangeTimes(state, record);\n break;\n case \"resizeFile\":\n applyResizeFile(state, record);\n break;\n case \"removeDirectory\":\n applyRemoveDirectory(state, record);\n break;\n case \"rename\":\n applyRename(state, record);\n break;\n case \"createSymlink\":\n applyCreateSymlink(state, record);\n break;\n case \"reserveQuarantine\":\n applyReserveQuarantine(state, record);\n break;\n }\n state.basePayloadBytes = projectedBasePayloadBytes;\n}\n\nfunction cloneState(state: VfsState): VfsState {\n return {\n ...state,\n retainedGenerations: { ...state.retainedGenerations },\n inodes: new Map(\n [...state.inodes].map(([inodeId, inode]) => [\n inodeId,\n inode.kind === \"directory\"\n ? { ...inode, children: new Map(inode.children) }\n : inode.kind === \"file\"\n ? { ...inode, extents: [...inode.extents] }\n : { ...inode },\n ]),\n ),\n parentByInode: new Map([...state.parentByInode].map(([inodeId, entry]) => [inodeId, { ...entry }])),\n allocator: {\n totalExtents: state.allocator.totalExtents,\n ownedBy: new Map(state.allocator.ownedBy),\n available: state.allocator.available.clone(),\n quarantine: new Map(state.allocator.quarantine),\n },\n };\n}\n\nfunction projectRepackFromCopy(\n state: VfsState,\n projected: VfsState,\n pinnedQuarantine: ReadonlySet<ExtentId>,\n): VfsState {\n // Activated/recovered state and every live reducer transition are already validated.\n // The projected result is validated below before its canonical base can be activated.\n if (state.generation === MAX_U64) {\n throw new StoreLimitError(\"generation is exhausted; the store must be recreated\");\n }\n let projectedBasePayloadBytes = state.basePayloadBytes;\n const nextGeneration = state.generation + 1n;\n const target = otherMetadataFile(state.activeMetadataFile);\n const targetPreviousGeneration = state.retainedGenerations[target];\n for (const [extentId, firstExcludedGeneration] of projected.allocator.quarantine) {\n if (pinnedQuarantine.has(extentId)) {\n projected.allocator.quarantine.set(extentId, null);\n } else if (firstExcludedGeneration === null) {\n projected.allocator.quarantine.set(extentId, nextGeneration);\n } else if (targetPreviousGeneration === null || targetPreviousGeneration < firstExcludedGeneration) {\n projected.allocator.quarantine.delete(extentId);\n projected.allocator.available.add(extentId);\n projectedBasePayloadBytes -= 8;\n }\n }\n while (projected.allocator.totalExtents > 0n) {\n const tail = projected.allocator.totalExtents - 1n;\n if (!projected.allocator.available.delete(tail)) break;\n projected.allocator.totalExtents = tail;\n projectedBasePayloadBytes -= 8;\n }\n projected.generation = nextGeneration;\n projected.activeMetadataFile = target;\n projected.retainedGenerations[target] = nextGeneration;\n projected.basePayloadBytes = projectedBasePayloadBytes;\n validateState(projected);\n return projected;\n}\n\nexport function projectRepack(state: VfsState, pinnedQuarantine: ReadonlySet<ExtentId> = new Set()): VfsState {\n return projectRepackFromCopy(state, cloneState(state), pinnedQuarantine);\n}\n\n/**\n * @internal Activation-only projection. Structures repack never mutates are shared read-only until\n * durable activation; allocator and generation structures remain isolated from the live state.\n */\nexport function projectRepackForActivation(\n state: VfsState,\n pinnedQuarantine: ReadonlySet<ExtentId> = new Set(),\n): VfsState {\n const projected: VfsState = {\n ...state,\n retainedGenerations: { ...state.retainedGenerations },\n inodes: state.inodes,\n parentByInode: state.parentByInode,\n allocator: {\n totalExtents: state.allocator.totalExtents,\n ownedBy: state.allocator.ownedBy,\n available: state.allocator.available.clone(),\n quarantine: new Map(state.allocator.quarantine),\n },\n };\n return projectRepackFromCopy(state, projected, pinnedQuarantine);\n}\n\nexport function validateState(state: VfsState): void {\n validateExtentSize(state.extentSize);\n checkedU64(state.generation, \"generation\");\n if (state.generation === 0n) {\n throw new StoreLimitError(\"generation must be positive\");\n }\n checkedU64(state.nextInodeId, \"next inode ID\");\n const root = state.inodes.get(state.rootInodeId);\n if (root?.kind !== \"directory\") {\n throw new StoreLimitError(\"root inode is missing or is not a directory\");\n }\n if (state.parentByInode.has(state.rootInodeId)) {\n throw new StoreLimitError(\"root inode must not have a parent entry\");\n }\n if (state.inodes.size > MAX_INODES) {\n throw new StoreLimitError(`inode count exceeds ${MAX_INODES}`);\n }\n checkedU64(state.allocator.totalExtents, \"total extent count\");\n if (state.allocator.totalExtents > BigInt(MAX_TOTAL_EXTENTS)) {\n throw new StoreLimitError(`total extent count exceeds ${MAX_TOTAL_EXTENTS}`);\n }\n const classified = new Uint8Array(Number(state.allocator.totalExtents));\n let classifiedCount = 0;\n const classify = (extentId: ExtentId, label: string): void => {\n if (extentId < 0n || extentId >= state.allocator.totalExtents) {\n throw new StoreLimitError(`${label} extent is out of range or multiply classified`);\n }\n const index = Number(extentId);\n if (classified[index] !== 0) {\n throw new StoreLimitError(`${label} extent is out of range or multiply classified`);\n }\n classified[index] = 1;\n classifiedCount += 1;\n };\n const reached = new Set<InodeId>();\n let calculatedBasePayloadBytes = BASE_STATE_FIXED_BYTES;\n const visit = (inodeKey: InodeId, inode: Inode, metrics: PathMetrics): void => {\n checkedU64(inodeKey, \"inode map key\");\n checkedU64(inode.id, \"inode ID\");\n if (inodeKey !== inode.id) {\n throw new StoreLimitError(\"inode map key does not match the inode ID\");\n }\n if (inode.id >= state.nextInodeId) {\n throw new StoreLimitError(\"inode ID is not below the unused next inode ID\");\n }\n if (reached.has(inode.id)) {\n throw new StoreLimitError(\"inode has more than one directory owner\");\n }\n reached.add(inode.id);\n validateMode(inode.mode);\n validateTimestamp(inode.atimeMs);\n validateTimestamp(inode.mtimeMs);\n validateTimestamp(inode.ctimeMs);\n if (inode.kind === \"directory\") {\n calculatedBasePayloadBytes += DIRECTORY_INODE_FIXED_BYTES;\n for (const [name, childId] of inode.children) {\n const nameBytes = validatePathComponent(name);\n calculatedBasePayloadBytes += CHILD_FIXED_BYTES + nameBytes;\n const parentEntry = state.parentByInode.get(childId);\n if (parentEntry?.parentId !== inode.id || parentEntry.name !== name) {\n throw new StoreLimitError(\"inode parent index does not match its directory entry\");\n }\n const childMetrics = {\n depth: metrics.depth + 1,\n bytes: metrics.bytes + (metrics.depth === 0 ? 0 : 1) + nameBytes,\n };\n if (childMetrics.depth > MAX_PATH_DEPTH) {\n throw new StoreLimitError(`inode path exceeds ${MAX_PATH_DEPTH} components`);\n }\n if (childMetrics.bytes > MAX_PATH_BYTES) {\n throw new StoreLimitError(`inode path exceeds ${MAX_PATH_BYTES} UTF-8 bytes`);\n }\n const child = state.inodes.get(childId);\n if (child === undefined) {\n throw new StoreLimitError(\"directory entry references a missing inode\");\n }\n visit(childId, child, childMetrics);\n }\n } else if (inode.kind === \"symlink\") {\n let targetBytes: number;\n try {\n targetBytes = validateSymlinkTarget(inode.target);\n } catch (cause) {\n throw new StoreLimitError(`symlink target is invalid: ${String(cause)}`, { cause });\n }\n calculatedBasePayloadBytes += SYMLINK_INODE_FIXED_BYTES + targetBytes;\n } else {\n calculatedBasePayloadBytes += FILE_INODE_FIXED_BYTES + inode.extents.length * 8;\n if (inode.extents.length !== extentCountForSize(inode.size, state.extentSize)) {\n throw new StoreLimitError(\"file extent count does not cover its size exactly\");\n }\n for (const extentId of inode.extents) {\n classify(extentId, \"owned\");\n if (state.allocator.ownedBy.get(extentId) !== inode.id) {\n throw new StoreLimitError(\"owned extent does not map back to its inode\");\n }\n }\n }\n };\n visit(state.rootInodeId, root, { depth: 0, bytes: 1 });\n if (reached.size !== state.inodes.size) {\n throw new StoreLimitError(\"inode graph contains unreachable inodes\");\n }\n if (state.parentByInode.size !== state.inodes.size - 1) {\n throw new StoreLimitError(\"inode parent index does not cover every non-root inode\");\n }\n if (classifiedCount !== state.allocator.ownedBy.size) {\n throw new StoreLimitError(\"allocator contains an owner not referenced by a file\");\n }\n calculatedBasePayloadBytes += state.allocator.available.size * 8 + state.allocator.quarantine.size * 16;\n if (state.basePayloadBytes !== calculatedBasePayloadBytes) {\n throw new StoreLimitError(\"tracked metadata-base size does not match canonical state size\");\n }\n if (state.basePayloadBytes > MAX_METADATA_BASE_WRITER_BYTES) {\n throw new StoreLimitError(`metadata base exceeds ${MAX_METADATA_BASE_WRITER_BYTES} bytes`);\n }\n if (state.retainedGenerations[state.activeMetadataFile] !== state.generation) {\n throw new StoreLimitError(\"active metadata identity does not match the state generation\");\n }\n const inactiveMetadataFile = otherMetadataFile(state.activeMetadataFile);\n const inactiveGeneration = state.retainedGenerations[inactiveMetadataFile];\n if (inactiveGeneration !== null) {\n checkedU64(inactiveGeneration, \"inactive retained generation\");\n if (inactiveGeneration === 0n || inactiveGeneration + 1n !== state.generation) {\n throw new StoreLimitError(\"inactive retained generation is not the immediate predecessor\");\n }\n }\n for (const extentId of state.allocator.available.values()) {\n classify(extentId, \"available\");\n }\n for (const [extentId, firstExcludedGeneration] of state.allocator.quarantine) {\n classify(extentId, \"quarantined\");\n if (firstExcludedGeneration !== null && firstExcludedGeneration !== state.generation) {\n throw new StoreLimitError(\"quarantine generation is inconsistent with retained metadata\");\n }\n }\n if (BigInt(classifiedCount) !== state.allocator.totalExtents) {\n throw new StoreLimitError(\"allocator partition does not cover every extent\");\n }\n}\n\nexport function canonicalStateView(state: VfsState) {\n const inodes = [...state.inodes.values()]\n .sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))\n .map((inode) =>\n inode.kind === \"directory\"\n ? {\n ...inode,\n children: [...inode.children.entries()].sort(([left], [right]) => left.localeCompare(right)),\n }\n : inode.kind === \"file\"\n ? { ...inode, extents: [...inode.extents] }\n : { ...inode },\n );\n return {\n generation: state.generation,\n nextInodeId: state.nextInodeId,\n rootInodeId: state.rootInodeId,\n extentSize: state.extentSize,\n activeMetadataFile: state.activeMetadataFile,\n retainedGenerations: { ...state.retainedGenerations },\n basePayloadBytes: state.basePayloadBytes,\n inodes,\n parentByInode: [...state.parentByInode.entries()].sort(([left], [right]) =>\n left < right ? -1 : left > right ? 1 : 0,\n ),\n allocator: {\n totalExtents: state.allocator.totalExtents,\n ownedBy: [...state.allocator.ownedBy.entries()].sort(([left], [right]) => (left < right ? -1 : 1)),\n available: [...state.allocator.available.values()].sort((left, right) => (left < right ? -1 : 1)),\n quarantine: [...state.allocator.quarantine.entries()].sort(([left], [right]) => (left < right ? -1 : 1)),\n },\n };\n}\n",
11
+ "import { crc32, crc32WithZeroedRange } from \"./checksum\";\nimport { CorruptStoreError, ExtentSizeMismatchError, StoreLimitError, StoreRecreationRequiredError } from \"./errors\";\nimport {\n ARENA_HEADER_BYTES,\n checkedU64,\n FORMAT_VERSION,\n LIMITS_PROFILE_VERSION,\n MAX_COMPONENT_BYTES,\n MAX_EXTENTS_PER_INODE,\n MAX_FRAME_PAYLOAD_BYTES,\n MAX_INODES,\n MAX_METADATA_BASE_READER_BYTES,\n MAX_METADATA_BASE_WRITER_BYTES,\n MAX_PATH_BYTES,\n MAX_TOTAL_EXTENTS,\n validateExtentSize,\n} from \"./limits\";\nimport { validatePathComponent, validateSymlinkTarget } from \"./path\";\nimport { estimateTxnPayloadBytes, IndexedExtentSet, validateState } from \"./state-machine\";\nimport type {\n DirectoryInode,\n ExtentRun,\n FileInode,\n Inode,\n MetadataFile,\n SymlinkInode,\n TxnRecord,\n VfsState,\n} from \"./state-machine\";\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nconst ARENA_MAGIC = textEncoder.encode(\"PGXRPA01\");\nconst METADATA_MAGIC = textEncoder.encode(\"PGXRPM01\");\nconst FRAME_MAGIC = textEncoder.encode(\"PGXRPF01\");\nconst ACTIVATION_MAGIC = textEncoder.encode(\"PGXRPK01\");\n\nexport const ARENA_HEADER_CHECKSUM_OFFSET = 24;\nexport const METADATA_HEADER_BYTES = 80;\nexport const TXN_FRAME_HEADER_BYTES = 48;\nexport const ACTIVATION_SLOT_BYTES = 128;\n\nexport const METADATA_HEADER_CHECKSUM_OFFSET = 64;\nexport const FRAME_CHECKSUM_OFFSET = 40;\nexport const ACTIVATION_CHECKSUM_OFFSET = 52;\n\nclass BinaryWriter {\n readonly bytes: Uint8Array;\n readonly #view: DataView;\n #offset = 0;\n\n constructor(length: number, initialOffset = 0) {\n if (\n !Number.isSafeInteger(length) ||\n length < 0 ||\n !Number.isSafeInteger(initialOffset) ||\n initialOffset < 0 ||\n initialOffset > length\n ) {\n throw new StoreLimitError(\"binary output length is invalid\");\n }\n this.bytes = new Uint8Array(length);\n this.#view = new DataView(this.bytes.buffer);\n this.#offset = initialOffset;\n }\n\n u8(value: number): void {\n this.#require(1);\n if (!Number.isSafeInteger(value) || value < 0 || value > 0xff) {\n throw new StoreLimitError(\"unsigned 8-bit value is out of range\");\n }\n this.#view.setUint8(this.#offset, value);\n this.#offset += 1;\n }\n\n u16(value: number): void {\n this.#require(2);\n if (!Number.isSafeInteger(value) || value < 0 || value > 0xffff) {\n throw new StoreLimitError(\"unsigned 16-bit value is out of range\");\n }\n this.#view.setUint16(this.#offset, value, true);\n this.#offset += 2;\n }\n\n u32(value: number): void {\n this.#require(4);\n if (!Number.isSafeInteger(value) || value < 0 || value > 0xffff_ffff) {\n throw new StoreLimitError(\"unsigned 32-bit value is out of range\");\n }\n this.#view.setUint32(this.#offset, value, true);\n this.#offset += 4;\n }\n\n u64(value: bigint): void {\n this.#require(8);\n this.#view.setBigUint64(this.#offset, checkedU64(value, \"encoded integer\"), true);\n this.#offset += 8;\n }\n\n validatedU64(value: bigint): void {\n this.#require(8);\n this.#view.setBigUint64(this.#offset, value, true);\n this.#offset += 8;\n }\n\n raw(value: Uint8Array): void {\n this.#require(value.byteLength);\n this.bytes.set(value, this.#offset);\n this.#offset += value.byteLength;\n }\n\n string(value: string): void {\n validatePathComponent(value);\n this.validatedString(textEncoder.encode(value));\n }\n\n /** A symbolic link's target: a whole PATH, so it is bounded by `MAX_PATH_BYTES`, not by a name. */\n symlinkTarget(value: string): void {\n validateSymlinkTarget(value);\n this.validatedString(textEncoder.encode(value));\n }\n\n validatedString(encoded: Uint8Array): void {\n this.u16(encoded.byteLength);\n this.raw(encoded);\n }\n\n finish(): Uint8Array {\n if (this.#offset !== this.bytes.byteLength) {\n throw new StoreLimitError(\n `binary encoder wrote ${this.#offset} bytes into a ${this.bytes.byteLength}-byte output`,\n );\n }\n return this.bytes;\n }\n\n #require(length: number): void {\n if (this.#offset + length > this.bytes.byteLength) {\n throw new StoreLimitError(\"binary encoder exceeded its preflighted size\");\n }\n }\n}\n\nclass BinaryReader {\n readonly #bytes: Uint8Array;\n readonly #view: DataView;\n #offset = 0;\n\n constructor(bytes: Uint8Array) {\n this.#bytes = bytes;\n this.#view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n }\n\n get remaining(): number {\n return this.#bytes.byteLength - this.#offset;\n }\n\n u8(): number {\n this.#require(1);\n const value = this.#view.getUint8(this.#offset);\n this.#offset += 1;\n return value;\n }\n\n u16(): number {\n this.#require(2);\n const value = this.#view.getUint16(this.#offset, true);\n this.#offset += 2;\n return value;\n }\n\n u32(): number {\n this.#require(4);\n const value = this.#view.getUint32(this.#offset, true);\n this.#offset += 4;\n return value;\n }\n\n u64(): bigint {\n this.#require(8);\n const value = this.#view.getBigUint64(this.#offset, true);\n this.#offset += 8;\n return value;\n }\n\n raw(length: number): Uint8Array {\n this.#require(length);\n const value = this.#bytes.subarray(this.#offset, this.#offset + length);\n this.#offset += length;\n return value;\n }\n\n string(): string {\n const length = this.u16();\n if (length === 0 || length > MAX_COMPONENT_BYTES) {\n throw new CorruptStoreError(\"encoded path component length is invalid\");\n }\n let value: string;\n try {\n value = textDecoder.decode(this.raw(length));\n } catch (cause) {\n throw new CorruptStoreError(\"encoded path component is not valid UTF-8\", { cause });\n }\n if (textEncoder.encode(value).byteLength !== length) {\n throw new CorruptStoreError(\"encoded path component is not canonical UTF-8\");\n }\n try {\n validatePathComponent(value);\n } catch (cause) {\n throw new CorruptStoreError(`encoded path component is invalid: ${String(cause)}`, { cause });\n }\n return value;\n }\n\n /** The reader half of {@link BinaryWriter.symlinkTarget}. */\n symlinkTarget(): string {\n const length = this.u16();\n if (length === 0 || length > MAX_PATH_BYTES) {\n throw new CorruptStoreError(\"encoded symlink target length is invalid\");\n }\n let value: string;\n try {\n value = textDecoder.decode(this.raw(length));\n } catch (cause) {\n throw new CorruptStoreError(\"encoded symlink target is not valid UTF-8\", { cause });\n }\n if (textEncoder.encode(value).byteLength !== length) {\n throw new CorruptStoreError(\"encoded symlink target is not canonical UTF-8\");\n }\n try {\n validateSymlinkTarget(value);\n } catch (cause) {\n throw new CorruptStoreError(`encoded symlink target is invalid: ${String(cause)}`, { cause });\n }\n return value;\n }\n\n end(): void {\n if (this.remaining !== 0) {\n throw new CorruptStoreError(\"binary value has trailing bytes\");\n }\n }\n\n #require(length: number): void {\n if (!Number.isSafeInteger(length) || length < 0 || length > this.remaining) {\n throw new CorruptStoreError(\"binary value is truncated\");\n }\n }\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.byteLength !== right.byteLength) {\n return false;\n }\n for (let index = 0; index < left.byteLength; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n return true;\n}\n\nfunction requireMagic(bytes: Uint8Array, magic: Uint8Array, label: string): void {\n if (!bytesEqual(bytes.subarray(0, magic.byteLength), magic)) {\n throw new CorruptStoreError(`${label} magic is invalid`);\n }\n}\n\nfunction requireZero(bytes: Uint8Array, start: number, end: number, label: string): void {\n for (let offset = start; offset < end; offset += 1) {\n if (bytes[offset] !== 0) {\n throw new CorruptStoreError(`${label} padding is not canonical`);\n }\n }\n}\n\nfunction requireChecksum(bytes: Uint8Array, offset: number, label: string): void {\n const stored = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(offset, true);\n const calculated = crc32WithZeroedRange(bytes, offset, 4);\n if (stored !== calculated) {\n throw new CorruptStoreError(`${label} checksum is invalid`);\n }\n}\n\nfunction requireCurrentIdentity(version: number, profile: number): void {\n if (version !== FORMAT_VERSION || profile !== LIMITS_PROFILE_VERSION) {\n throw new StoreRecreationRequiredError(\n `store format ${version}/limits profile ${profile} is unsupported; delete the store and create it fresh`,\n );\n }\n}\n\nexport interface ArenaHeader {\n extentSize: number;\n limitsProfileVersion: number;\n formatVersion: number;\n}\n\nexport function encodeArenaHeader(options: { extentSize: number }): Uint8Array {\n const extentSize = validateExtentSize(options.extentSize);\n const bytes = new Uint8Array(ARENA_HEADER_BYTES);\n const view = new DataView(bytes.buffer);\n bytes.set(ARENA_MAGIC, 0);\n view.setUint32(8, FORMAT_VERSION, true);\n view.setUint32(12, LIMITS_PROFILE_VERSION, true);\n view.setUint32(16, extentSize, true);\n view.setUint32(ARENA_HEADER_CHECKSUM_OFFSET, crc32WithZeroedRange(bytes, ARENA_HEADER_CHECKSUM_OFFSET, 4), true);\n return bytes;\n}\n\nexport function decodeArenaHeader(bytes: Uint8Array, configuredExtentSize?: number): ArenaHeader {\n if (configuredExtentSize !== undefined) {\n validateExtentSize(configuredExtentSize);\n }\n if (bytes.byteLength !== ARENA_HEADER_BYTES) {\n throw new CorruptStoreError(\"arena header has the wrong length\");\n }\n requireMagic(bytes, ARENA_MAGIC, \"arena header\");\n requireZero(bytes, 20, 24, \"arena header\");\n requireZero(bytes, 28, bytes.byteLength, \"arena header\");\n requireChecksum(bytes, ARENA_HEADER_CHECKSUM_OFFSET, \"arena header\");\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const formatVersion = view.getUint32(8, true);\n const limitsProfileVersion = view.getUint32(12, true);\n requireCurrentIdentity(formatVersion, limitsProfileVersion);\n const extentSize = view.getUint32(16, true);\n try {\n validateExtentSize(extentSize);\n } catch (cause) {\n throw new CorruptStoreError(\"arena header extent size is invalid\", { cause });\n }\n if (configuredExtentSize !== undefined && configuredExtentSize !== extentSize) {\n throw new ExtentSizeMismatchError(configuredExtentSize, extentSize);\n }\n return { extentSize, limitsProfileVersion, formatVersion };\n}\n\nfunction metadataFileCode(file: MetadataFile): number {\n return file === \"a\" ? 0 : 1;\n}\n\nfunction decodeMetadataFile(value: number): MetadataFile {\n if (value === 0) return \"a\";\n if (value === 1) return \"b\";\n throw new CorruptStoreError(\"metadata file selector is invalid\");\n}\n\nfunction compareBigint(left: bigint, right: bigint): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction compareUtf8Names(left: string, right: string): number {\n let leftIndex = 0;\n let rightIndex = 0;\n while (leftIndex < left.length && rightIndex < right.length) {\n const leftPoint = left.codePointAt(leftIndex)!;\n const rightPoint = right.codePointAt(rightIndex)!;\n if (leftPoint !== rightPoint) return leftPoint - rightPoint;\n leftIndex += leftPoint > 0xffff ? 2 : 1;\n rightIndex += rightPoint > 0xffff ? 2 : 1;\n }\n return left.length - right.length;\n}\n\nfunction sortIfNeeded<Value>(values: Value[], compare: (left: Value, right: Value) => number): Value[] {\n for (let index = 1; index < values.length; index += 1) {\n if (compare(values[index - 1]!, values[index]!) > 0) {\n values.sort(compare);\n break;\n }\n }\n return values;\n}\n\nconst INODE_KIND_DIRECTORY = 0;\nconst INODE_KIND_FILE = 1;\nconst INODE_KIND_SYMLINK = 2;\n\nfunction writeInode(writer: BinaryWriter, inode: Inode): void {\n writer.validatedU64(inode.id);\n writer.u8(\n inode.kind === \"directory\" ? INODE_KIND_DIRECTORY : inode.kind === \"file\" ? INODE_KIND_FILE : INODE_KIND_SYMLINK,\n );\n writer.u32(inode.mode);\n writer.validatedU64(inode.atimeMs);\n writer.validatedU64(inode.mtimeMs);\n writer.validatedU64(inode.ctimeMs);\n if (inode.kind === \"directory\") {\n const children = sortIfNeeded([...inode.children], ([left], [right]) => compareUtf8Names(left, right));\n writer.u32(children.length);\n for (const [name, inodeId] of children) {\n writer.validatedString(textEncoder.encode(name));\n writer.validatedU64(inodeId);\n }\n } else if (inode.kind === \"symlink\") {\n writer.symlinkTarget(inode.target);\n } else {\n writer.validatedU64(inode.size);\n writer.u32(inode.extents.length);\n for (const extentId of inode.extents) writer.validatedU64(extentId);\n }\n}\n\nfunction encodeMetadataPayload(state: VfsState, length: number, prefixBytes = 0): Uint8Array {\n if (length > MAX_METADATA_BASE_WRITER_BYTES) {\n throw new StoreLimitError(`metadata base payload exceeds ${MAX_METADATA_BASE_WRITER_BYTES} bytes`);\n }\n const writer = new BinaryWriter(prefixBytes + length, prefixBytes);\n writer.validatedU64(state.allocator.totalExtents);\n writer.validatedU64(state.nextInodeId);\n writer.u32(state.inodes.size);\n const inodes = sortIfNeeded([...state.inodes.values()], (left, right) => compareBigint(left.id, right.id));\n for (const inode of inodes) {\n writeInode(writer, inode);\n }\n const available = sortIfNeeded([...state.allocator.available.values()], compareBigint);\n for (const extentId of available) writer.validatedU64(extentId);\n const quarantine = sortIfNeeded([...state.allocator.quarantine], ([left], [right]) => compareBigint(left, right));\n for (const [extentId, generation] of quarantine) {\n writer.validatedU64(extentId);\n writer.validatedU64(generation ?? 0n);\n }\n return writer.finish();\n}\n\nexport interface DecodedMetadataBase {\n state: VfsState;\n payloadBytes: number;\n baseEnd: bigint;\n baseDigest: number;\n}\n\nexport interface MetadataBaseHeader {\n formatVersion: number;\n limitsProfileVersion: number;\n generation: bigint;\n extentSize: number;\n metadataFileCode: number;\n rootInodeId: bigint;\n payloadLength: number;\n availableCount: number;\n quarantineCount: number;\n baseEnd: bigint;\n}\n\nexport function inspectMetadataBaseHeader(header: Uint8Array): MetadataBaseHeader {\n if (header.byteLength !== METADATA_HEADER_BYTES) {\n throw new CorruptStoreError(\"metadata base header has the wrong length\");\n }\n requireMagic(header, METADATA_MAGIC, \"metadata base\");\n requireZero(header, 29, 32, \"metadata base\");\n requireZero(header, 52, 56, \"metadata base\");\n requireZero(header, 68, 80, \"metadata base\");\n const view = new DataView(header.buffer, header.byteOffset, header.byteLength);\n const payloadLength = view.getUint32(40, true);\n if (payloadLength > MAX_METADATA_BASE_READER_BYTES) {\n throw new CorruptStoreError(\"metadata base payload declaration exceeds the reader limit\");\n }\n const baseEnd = view.getBigUint64(56, true);\n if (baseEnd !== BigInt(METADATA_HEADER_BYTES + payloadLength)) {\n throw new CorruptStoreError(\"metadata base end offset is inconsistent\");\n }\n const availableCount = view.getUint32(44, true);\n const quarantineCount = view.getUint32(48, true);\n return {\n formatVersion: view.getUint32(8, true),\n limitsProfileVersion: view.getUint32(12, true),\n generation: view.getBigUint64(16, true),\n extentSize: view.getUint32(24, true),\n metadataFileCode: view.getUint8(28),\n rootInodeId: view.getBigUint64(32, true),\n payloadLength,\n availableCount,\n quarantineCount,\n baseEnd,\n };\n}\n\nexport function encodeMetadataBase(state: VfsState): Uint8Array {\n validateState(state);\n return encodeValidatedMetadataBase(state);\n}\n\n/** @internal The caller must have validated this exact state immediately before encoding it. */\nexport function encodeValidatedMetadataBase(state: VfsState): Uint8Array {\n const baseEnd = METADATA_HEADER_BYTES + state.basePayloadBytes;\n const bytes = encodeMetadataPayload(state, state.basePayloadBytes, METADATA_HEADER_BYTES);\n const view = new DataView(bytes.buffer);\n bytes.set(METADATA_MAGIC, 0);\n view.setUint32(8, FORMAT_VERSION, true);\n view.setUint32(12, LIMITS_PROFILE_VERSION, true);\n view.setBigUint64(16, state.generation, true);\n view.setUint32(24, state.extentSize, true);\n view.setUint8(28, metadataFileCode(state.activeMetadataFile));\n view.setBigUint64(32, state.rootInodeId, true);\n view.setUint32(40, state.basePayloadBytes, true);\n view.setUint32(44, state.allocator.available.size, true);\n view.setUint32(48, state.allocator.quarantine.size, true);\n view.setBigUint64(56, BigInt(baseEnd), true);\n view.setUint32(\n METADATA_HEADER_CHECKSUM_OFFSET,\n crc32WithZeroedRange(bytes, METADATA_HEADER_CHECKSUM_OFFSET, 4),\n true,\n );\n return bytes;\n}\n\nfunction readBoundedCount(reader: BinaryReader, maximum: number, label: string): number {\n const count = reader.u32();\n if (count > maximum) {\n throw new CorruptStoreError(`${label} count exceeds ${maximum}`);\n }\n return count;\n}\n\nfunction readInode(reader: BinaryReader): Inode {\n const id = reader.u64();\n const kind = reader.u8();\n const mode = reader.u32();\n const atimeMs = reader.u64();\n const mtimeMs = reader.u64();\n const ctimeMs = reader.u64();\n if (kind === INODE_KIND_DIRECTORY) {\n const childCount = readBoundedCount(reader, MAX_INODES, \"directory child\");\n const children = new Map<string, bigint>();\n let previousName: string | undefined;\n for (let index = 0; index < childCount; index += 1) {\n const name = reader.string();\n if (previousName !== undefined && compareUtf8Names(previousName, name) >= 0) {\n throw new CorruptStoreError(\"directory children are not in canonical order\");\n }\n children.set(name, reader.u64());\n previousName = name;\n }\n const inode: DirectoryInode = { id, kind: \"directory\", mode, atimeMs, mtimeMs, ctimeMs, children };\n return inode;\n }\n if (kind === INODE_KIND_FILE) {\n const size = reader.u64();\n const extentCount = readBoundedCount(reader, MAX_EXTENTS_PER_INODE, \"file extent\");\n const extents: bigint[] = [];\n for (let index = 0; index < extentCount; index += 1) extents.push(reader.u64());\n const inode: FileInode = { id, kind: \"file\", mode, atimeMs, mtimeMs, ctimeMs, size, extents };\n return inode;\n }\n if (kind === INODE_KIND_SYMLINK) {\n const inode: SymlinkInode = {\n id,\n kind: \"symlink\",\n mode,\n atimeMs,\n mtimeMs,\n ctimeMs,\n target: reader.symlinkTarget(),\n };\n return inode;\n }\n throw new CorruptStoreError(\"inode type is invalid\");\n}\n\nexport function decodeMetadataBase(bytes: Uint8Array): DecodedMetadataBase {\n if (bytes.byteLength < METADATA_HEADER_BYTES) {\n throw new CorruptStoreError(\"metadata base header is truncated\");\n }\n const inspected = inspectMetadataBaseHeader(bytes.subarray(0, METADATA_HEADER_BYTES));\n const { payloadLength, baseEnd } = inspected;\n if (bytes.byteLength !== Number(baseEnd)) {\n throw new CorruptStoreError(\"metadata base end offset is inconsistent\");\n }\n requireChecksum(bytes, METADATA_HEADER_CHECKSUM_OFFSET, \"metadata base\");\n const payload = bytes.subarray(METADATA_HEADER_BYTES);\n requireCurrentIdentity(inspected.formatVersion, inspected.limitsProfileVersion);\n const { generation, extentSize, rootInodeId, availableCount, quarantineCount } = inspected;\n if (generation === 0n) throw new CorruptStoreError(\"metadata generation must be positive\");\n try {\n validateExtentSize(extentSize);\n } catch (cause) {\n throw new CorruptStoreError(\"metadata base extent size is invalid\", { cause });\n }\n const activeMetadataFile = decodeMetadataFile(inspected.metadataFileCode);\n if (availableCount > MAX_TOTAL_EXTENTS || quarantineCount > MAX_TOTAL_EXTENTS) {\n throw new CorruptStoreError(\"metadata allocator count exceeds the extent limit\");\n }\n\n try {\n const reader = new BinaryReader(payload);\n const totalExtents = reader.u64();\n if (totalExtents > BigInt(MAX_TOTAL_EXTENTS)) {\n throw new CorruptStoreError(\"metadata total extent count exceeds the extent limit\");\n }\n const nextInodeId = reader.u64();\n const inodeCount = readBoundedCount(reader, MAX_INODES, \"inode\");\n const inodes = new Map<bigint, Inode>();\n const ownedBy = new Map<bigint, bigint>();\n let previousInodeId: bigint | undefined;\n for (let index = 0; index < inodeCount; index += 1) {\n const inode = readInode(reader);\n if (previousInodeId !== undefined && inode.id <= previousInodeId) {\n throw new CorruptStoreError(\"inodes are not in canonical order\");\n }\n inodes.set(inode.id, inode);\n previousInodeId = inode.id;\n if (inode.kind === \"file\") {\n for (const extentId of inode.extents) {\n if (ownedBy.has(extentId)) throw new CorruptStoreError(\"metadata contains duplicate extent ownership\");\n ownedBy.set(extentId, inode.id);\n }\n }\n }\n const available = new IndexedExtentSet();\n let previousAvailable: bigint | undefined;\n for (let index = 0; index < availableCount; index += 1) {\n const extentId = reader.u64();\n if (previousAvailable !== undefined && extentId <= previousAvailable) {\n throw new CorruptStoreError(\"available extents are not in canonical order\");\n }\n available.add(extentId);\n previousAvailable = extentId;\n }\n const quarantine = new Map<bigint, bigint | null>();\n let previousQuarantine: bigint | undefined;\n for (let index = 0; index < quarantineCount; index += 1) {\n const extentId = reader.u64();\n const encodedGeneration = reader.u64();\n if (previousQuarantine !== undefined && extentId <= previousQuarantine) {\n throw new CorruptStoreError(\"quarantine extents are not in canonical order\");\n }\n quarantine.set(extentId, encodedGeneration === 0n ? null : encodedGeneration);\n previousQuarantine = extentId;\n }\n reader.end();\n const parentByInode = new Map<bigint, { parentId: bigint; name: string }>();\n for (const inode of inodes.values()) {\n if (inode.kind !== \"directory\") continue;\n for (const [name, childId] of inode.children) {\n if (parentByInode.has(childId)) {\n throw new CorruptStoreError(\"metadata inode has multiple directory owners\");\n }\n parentByInode.set(childId, { parentId: inode.id, name });\n }\n }\n const retainedGenerations: Record<MetadataFile, bigint | null> = { a: null, b: null };\n retainedGenerations[activeMetadataFile] = generation;\n const state: VfsState = {\n generation,\n nextInodeId,\n rootInodeId,\n extentSize,\n activeMetadataFile,\n retainedGenerations,\n basePayloadBytes: payloadLength,\n inodes,\n parentByInode,\n allocator: { totalExtents, ownedBy, available, quarantine },\n };\n validateState(state);\n return { state, payloadBytes: payloadLength, baseEnd, baseDigest: crc32(bytes) };\n } catch (cause) {\n if (cause instanceof CorruptStoreError) throw cause;\n throw new CorruptStoreError(`metadata base is semantically invalid: ${String(cause)}`, { cause });\n }\n}\n\nfunction writeExtentRuns(writer: BinaryWriter, runs: readonly ExtentRun[]): void {\n writer.u32(runs.length);\n for (const run of runs) {\n writer.u64(run.start);\n writer.u32(run.count);\n }\n}\n\nfunction readExtentRuns(reader: BinaryReader): ExtentRun[] {\n const runCount = readBoundedCount(reader, MAX_EXTENTS_PER_INODE, \"extent run\");\n const runs: ExtentRun[] = [];\n let extentCount = 0;\n for (let index = 0; index < runCount; index += 1) {\n const start = reader.u64();\n const count = reader.u32();\n if (count === 0 || extentCount + count > MAX_EXTENTS_PER_INODE) {\n throw new CorruptStoreError(\"extent run count is invalid\");\n }\n extentCount += count;\n runs.push({ start, count });\n }\n return runs;\n}\n\nconst RECORD_CODES: Record<TxnRecord[\"kind\"], number> = {\n createDirectories: 1,\n createFile: 2,\n removeFile: 3,\n changeMode: 4,\n changeTimes: 5,\n resizeFile: 6,\n removeDirectory: 7,\n rename: 8,\n reserveQuarantine: 9,\n createSymlink: 10,\n};\n\nfunction encodeTxnRecord(record: TxnRecord): Uint8Array {\n const writer = new BinaryWriter(estimateTxnPayloadBytes(record));\n writer.u8(RECORD_CODES[record.kind]);\n switch (record.kind) {\n case \"createDirectories\":\n writer.u32(record.entries.length);\n for (const entry of record.entries) {\n writer.u64(entry.parentId);\n writer.string(entry.name);\n writer.u64(entry.inodeId);\n writer.u32(entry.mode);\n writer.u64(entry.atimeMs);\n writer.u64(entry.mtimeMs);\n writer.u64(entry.ctimeMs);\n }\n break;\n case \"createFile\":\n writer.u64(record.parentId);\n writer.string(record.name);\n writer.u64(record.inodeId);\n writer.u32(record.mode);\n writer.u64(record.atimeMs);\n writer.u64(record.mtimeMs);\n writer.u64(record.ctimeMs);\n writer.u64(record.size);\n writeExtentRuns(writer, record.extents);\n break;\n case \"removeFile\":\n case \"removeDirectory\":\n writer.u64(record.parentId);\n writer.string(record.name);\n writer.u64(record.parentMtimeMs);\n writer.u64(record.parentCtimeMs);\n break;\n case \"changeMode\":\n writer.u64(record.inodeId);\n writer.u32(record.mode);\n writer.u64(record.ctimeMs);\n break;\n case \"changeTimes\":\n writer.u64(record.inodeId);\n writer.u64(record.atimeMs);\n writer.u64(record.mtimeMs);\n writer.u64(record.ctimeMs);\n break;\n case \"resizeFile\":\n writer.u8(record.operation === \"truncate\" ? 0 : 1);\n writer.u64(record.inodeId);\n writer.u64(record.size);\n writeExtentRuns(writer, record.allocated);\n writer.u64(record.mtimeMs);\n writer.u64(record.ctimeMs);\n break;\n case \"rename\":\n writer.u64(record.sourceParentId);\n writer.string(record.sourceName);\n writer.u64(record.destinationParentId);\n writer.string(record.destinationName);\n writer.u64(record.timestampMs);\n break;\n case \"createSymlink\":\n writer.u64(record.parentId);\n writer.string(record.name);\n writer.u64(record.inodeId);\n writer.u32(record.mode);\n writer.u64(record.atimeMs);\n writer.u64(record.mtimeMs);\n writer.u64(record.ctimeMs);\n writer.symlinkTarget(record.target);\n break;\n case \"reserveQuarantine\":\n writeExtentRuns(writer, record.extents);\n break;\n }\n return writer.finish();\n}\n\nfunction decodeTxnRecord(bytes: Uint8Array): TxnRecord {\n const reader = new BinaryReader(bytes);\n const type = reader.u8();\n let record: TxnRecord;\n switch (type) {\n case 1: {\n const count = readBoundedCount(reader, MAX_INODES, \"created directory\");\n if (count === 0) throw new CorruptStoreError(\"directory transaction must not be empty\");\n const entries = [];\n for (let index = 0; index < count; index += 1) {\n entries.push({\n parentId: reader.u64(),\n name: reader.string(),\n inodeId: reader.u64(),\n mode: reader.u32(),\n atimeMs: reader.u64(),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n });\n }\n record = { kind: \"createDirectories\", entries };\n break;\n }\n case 2:\n record = {\n kind: \"createFile\",\n parentId: reader.u64(),\n name: reader.string(),\n inodeId: reader.u64(),\n mode: reader.u32(),\n atimeMs: reader.u64(),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n size: reader.u64(),\n extents: readExtentRuns(reader),\n };\n break;\n case 3:\n case 7:\n record = {\n kind: type === 3 ? \"removeFile\" : \"removeDirectory\",\n parentId: reader.u64(),\n name: reader.string(),\n parentMtimeMs: reader.u64(),\n parentCtimeMs: reader.u64(),\n };\n break;\n case 4:\n record = { kind: \"changeMode\", inodeId: reader.u64(), mode: reader.u32(), ctimeMs: reader.u64() };\n break;\n case 5:\n record = {\n kind: \"changeTimes\",\n inodeId: reader.u64(),\n atimeMs: reader.u64(),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n };\n break;\n case 6: {\n const operation = reader.u8();\n if (operation !== 0 && operation !== 1) throw new CorruptStoreError(\"resize operation is invalid\");\n record = {\n kind: \"resizeFile\",\n operation: operation === 0 ? \"truncate\" : \"write\",\n inodeId: reader.u64(),\n size: reader.u64(),\n allocated: readExtentRuns(reader),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n };\n break;\n }\n case 8:\n record = {\n kind: \"rename\",\n sourceParentId: reader.u64(),\n sourceName: reader.string(),\n destinationParentId: reader.u64(),\n destinationName: reader.string(),\n timestampMs: reader.u64(),\n };\n break;\n case 9:\n record = { kind: \"reserveQuarantine\", extents: readExtentRuns(reader) };\n break;\n case 10:\n record = {\n kind: \"createSymlink\",\n parentId: reader.u64(),\n name: reader.string(),\n inodeId: reader.u64(),\n mode: reader.u32(),\n atimeMs: reader.u64(),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n target: reader.symlinkTarget(),\n };\n break;\n default:\n throw new CorruptStoreError(\"transaction record type is invalid\");\n }\n reader.end();\n return record;\n}\n\nexport interface TxnFrame {\n generation: bigint;\n sequence: bigint;\n record: TxnRecord;\n}\n\nexport interface TxnFrameHeader {\n generation: bigint;\n sequence: bigint;\n payloadLength: number;\n frameBytes: number;\n}\n\nexport function txnFrameBytes(record: TxnRecord): number {\n const payloadBytes = estimateTxnPayloadBytes(record);\n if (payloadBytes > MAX_FRAME_PAYLOAD_BYTES) {\n throw new StoreLimitError(`transaction payload exceeds ${MAX_FRAME_PAYLOAD_BYTES} bytes`);\n }\n return TXN_FRAME_HEADER_BYTES + payloadBytes;\n}\n\nexport function inspectTxnFrameHeader(header: Uint8Array): TxnFrameHeader {\n if (header.byteLength !== TXN_FRAME_HEADER_BYTES) {\n throw new CorruptStoreError(\"transaction frame header has the wrong length\");\n }\n const view = new DataView(header.buffer, header.byteOffset, header.byteLength);\n requireMagic(header, FRAME_MAGIC, \"transaction frame\");\n requireZero(header, 36, 40, \"transaction frame\");\n requireZero(header, 44, 48, \"transaction frame\");\n const payloadLength = view.getUint32(32, true);\n if (payloadLength > MAX_FRAME_PAYLOAD_BYTES) {\n throw new CorruptStoreError(\"transaction payload declaration exceeds the frame limit\");\n }\n if (view.getUint32(8, true) !== FORMAT_VERSION || view.getUint32(12, true) !== LIMITS_PROFILE_VERSION) {\n throw new CorruptStoreError(\"transaction frame format is invalid\");\n }\n return {\n generation: view.getBigUint64(16, true),\n sequence: view.getBigUint64(24, true),\n payloadLength,\n frameBytes: TXN_FRAME_HEADER_BYTES + payloadLength,\n };\n}\n\nexport function encodeTxnFrame(frame: TxnFrame): Uint8Array {\n const payload = encodeTxnRecord(frame.record);\n if (payload.byteLength > MAX_FRAME_PAYLOAD_BYTES) {\n throw new StoreLimitError(`transaction payload exceeds ${MAX_FRAME_PAYLOAD_BYTES} bytes`);\n }\n const bytes = new Uint8Array(TXN_FRAME_HEADER_BYTES + payload.byteLength);\n const view = new DataView(bytes.buffer);\n bytes.set(FRAME_MAGIC, 0);\n view.setUint32(8, FORMAT_VERSION, true);\n view.setUint32(12, LIMITS_PROFILE_VERSION, true);\n view.setBigUint64(16, checkedU64(frame.generation, \"frame generation\"), true);\n view.setBigUint64(24, checkedU64(frame.sequence, \"frame sequence\"), true);\n view.setUint32(32, payload.byteLength, true);\n bytes.set(payload, TXN_FRAME_HEADER_BYTES);\n view.setUint32(FRAME_CHECKSUM_OFFSET, crc32WithZeroedRange(bytes, FRAME_CHECKSUM_OFFSET, 4), true);\n return bytes;\n}\n\nexport function decodeTxnFrame(bytes: Uint8Array): TxnFrame {\n if (bytes.byteLength < TXN_FRAME_HEADER_BYTES) throw new CorruptStoreError(\"transaction frame is truncated\");\n const inspected = inspectTxnFrameHeader(bytes.subarray(0, TXN_FRAME_HEADER_BYTES));\n if (bytes.byteLength !== inspected.frameBytes) {\n throw new CorruptStoreError(\"transaction frame length is inconsistent\");\n }\n requireChecksum(bytes, FRAME_CHECKSUM_OFFSET, \"transaction frame\");\n return {\n generation: inspected.generation,\n sequence: inspected.sequence,\n record: decodeTxnRecord(bytes.subarray(TXN_FRAME_HEADER_BYTES)),\n };\n}\n\nexport interface ActivationRecord {\n sequence: bigint;\n metadataFile: MetadataFile;\n generation: bigint;\n baseEnd: bigint;\n baseDigest: number;\n}\n\nexport function encodeActivationSlot(record: ActivationRecord): Uint8Array {\n if (record.sequence === 0n || record.generation === 0n || record.baseEnd < BigInt(METADATA_HEADER_BYTES)) {\n throw new StoreLimitError(\"activation identity values are outside the encodable domain\");\n }\n const bytes = new Uint8Array(ACTIVATION_SLOT_BYTES);\n const view = new DataView(bytes.buffer);\n bytes.set(ACTIVATION_MAGIC, 0);\n view.setUint32(8, FORMAT_VERSION, true);\n view.setUint32(12, LIMITS_PROFILE_VERSION, true);\n view.setBigUint64(16, checkedU64(record.sequence, \"activation sequence\"), true);\n view.setUint8(24, metadataFileCode(record.metadataFile));\n view.setBigUint64(32, checkedU64(record.generation, \"activation generation\"), true);\n view.setBigUint64(40, checkedU64(record.baseEnd, \"activation base end\"), true);\n if (!Number.isSafeInteger(record.baseDigest) || record.baseDigest < 0 || record.baseDigest > 0xffff_ffff) {\n throw new StoreLimitError(\"activation base digest is outside the unsigned 32-bit range\");\n }\n view.setUint32(48, record.baseDigest, true);\n view.setUint32(ACTIVATION_CHECKSUM_OFFSET, crc32WithZeroedRange(bytes, ACTIVATION_CHECKSUM_OFFSET, 4), true);\n return bytes;\n}\n\nexport function decodeActivationSlot(bytes: Uint8Array): ActivationRecord {\n if (bytes.byteLength !== ACTIVATION_SLOT_BYTES) {\n throw new CorruptStoreError(\"activation slot has the wrong length\");\n }\n requireMagic(bytes, ACTIVATION_MAGIC, \"activation slot\");\n requireZero(bytes, 25, 32, \"activation slot\");\n requireZero(bytes, 56, bytes.byteLength, \"activation slot\");\n requireChecksum(bytes, ACTIVATION_CHECKSUM_OFFSET, \"activation slot\");\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n requireCurrentIdentity(view.getUint32(8, true), view.getUint32(12, true));\n const sequence = view.getBigUint64(16, true);\n const generation = view.getBigUint64(32, true);\n const baseEnd = view.getBigUint64(40, true);\n if (sequence === 0n || generation === 0n || baseEnd < BigInt(METADATA_HEADER_BYTES)) {\n throw new CorruptStoreError(\"activation slot contains invalid identity values\");\n }\n return {\n sequence,\n metadataFile: decodeMetadataFile(view.getUint8(24)),\n generation,\n baseEnd,\n baseDigest: view.getUint32(48, true),\n };\n}\n\nexport function tryDecodeActivationSlot(bytes: Uint8Array): ActivationRecord | null {\n try {\n return decodeActivationSlot(bytes);\n } catch (cause) {\n if (cause instanceof CorruptStoreError) return null;\n throw cause;\n }\n}\n\nexport function selectActivation(leftBytes: Uint8Array, rightBytes: Uint8Array): ActivationRecord {\n return selectActivationPair(leftBytes, rightBytes).selected;\n}\n\nexport interface ActivationPairSelection {\n selected: ActivationRecord;\n other: ActivationRecord | null;\n}\n\nexport function selectActivationPair(leftBytes: Uint8Array, rightBytes: Uint8Array): ActivationPairSelection {\n const left = tryDecodeActivationSlot(leftBytes);\n const right = tryDecodeActivationSlot(rightBytes);\n if (left === null && right === null) {\n throw new CorruptStoreError(\"both activation slots are invalid\");\n }\n if (left === null) return { selected: right!, other: null };\n if (right === null) return { selected: left, other: null };\n const older = left.sequence < right.sequence ? left : right;\n const newer = older === left ? right : left;\n if (newer.sequence !== older.sequence + 1n || newer.metadataFile === older.metadataFile) {\n throw new CorruptStoreError(\"activation slots do not form one exact alternating progression\");\n }\n return { selected: newer, other: older };\n}\n\nexport function metadataBaseDigest(bytes: Uint8Array): number {\n return crc32(bytes);\n}\n",
12
+ "import { CorruptStoreError, StoreLimitError } from \"./errors\";\nimport {\n ARENA_HEADER_BYTES,\n checkedAdd,\n checkedMultiply,\n checkedSafeNumber,\n checkedU64,\n MAX_TOTAL_EXTENTS,\n validateExtentSize,\n} from \"./limits\";\nimport type { MetadataFile } from \"./state-machine\";\n\nexport const OWNED_FILE_NAMES = [\"arena.bin\", \"metadata-a.bin\", \"metadata-b.bin\", \"activation.bin\"] as const;\nexport type OwnedFileName = (typeof OWNED_FILE_NAMES)[number];\nexport type MetadataFileName = Extract<OwnedFileName, \"metadata-a.bin\" | \"metadata-b.bin\">;\n\nexport function metadataFileName(file: MetadataFile): MetadataFileName {\n return file === \"a\" ? \"metadata-a.bin\" : \"metadata-b.bin\";\n}\n\nexport interface RepackedPortEntry {\n name: string;\n kind: \"file\" | \"directory\";\n}\n\nexport interface RepackedFileHandle {\n readonly name: OwnedFileName;\n getSize(label: string): number;\n read(target: Uint8Array, at: number, label: string): number;\n write(source: Uint8Array, at: number, label: string): number;\n truncate(size: number, label: string): void;\n flush(label: string): void;\n close(): void;\n}\n\nexport interface RepackedPort {\n enumerate(label: string): Promise<readonly RepackedPortEntry[]>;\n acquire(name: OwnedFileName, label: string): Promise<RepackedFileHandle>;\n}\n\nexport class PortWriteError extends Error {\n constructor(label: string) {\n super(`${label} made no valid write progress`);\n this.name = \"PortWriteError\";\n }\n}\n\nfunction checkedRange(offset: bigint, length: number, label: string): number {\n checkedU64(offset, `${label} offset`);\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new StoreLimitError(`${label} length is invalid`);\n }\n checkedSafeNumber(checkedAdd(offset, BigInt(length), `${label} end`), `${label} end`);\n return checkedSafeNumber(offset, `${label} offset`);\n}\n\nexport function readExact(\n handle: RepackedFileHandle,\n offset: bigint,\n length: number,\n maximumLength: number,\n label: string,\n): Uint8Array {\n if (!Number.isSafeInteger(maximumLength) || maximumLength < 0 || length > maximumLength) {\n throw new StoreLimitError(`${label} length exceeds the bounded read limit`);\n }\n const start = checkedRange(offset, length, label);\n const output = new Uint8Array(length);\n let completed = 0;\n while (completed < output.byteLength) {\n const count = handle.read(output.subarray(completed), start + completed, label);\n if (!Number.isSafeInteger(count) || count <= 0 || count > output.byteLength - completed) {\n throw new CorruptStoreError(`${label} ended before the declared byte length`);\n }\n completed += count;\n }\n return output;\n}\n\nexport function writeExact(handle: RepackedFileHandle, offset: bigint, bytes: Uint8Array, label: string): void {\n const start = checkedRange(offset, bytes.byteLength, label);\n let completed = 0;\n while (completed < bytes.byteLength) {\n const count = handle.write(bytes.subarray(completed), start + completed, label);\n if (!Number.isSafeInteger(count) || count <= 0 || count > bytes.byteLength - completed) {\n throw new PortWriteError(label);\n }\n completed += count;\n }\n}\n\nexport function truncateChecked(handle: RepackedFileHandle, size: bigint, label: string): void {\n handle.truncate(checkedSafeNumber(size, `${label} size`), label);\n}\n\nexport function arenaByteOffset(extentId: bigint, extentSize: number, withinExtent = 0): bigint {\n validateExtentSize(extentSize);\n checkedU64(extentId, \"extent ID\");\n if (extentId >= BigInt(MAX_TOTAL_EXTENTS)) {\n throw new StoreLimitError(`extent ID exceeds ${MAX_TOTAL_EXTENTS - 1}`);\n }\n if (!Number.isSafeInteger(withinExtent) || withinExtent < 0 || withinExtent >= extentSize) {\n throw new StoreLimitError(\"within-extent offset is outside the extent\");\n }\n return checkedAdd(\n checkedAdd(\n BigInt(ARENA_HEADER_BYTES),\n checkedMultiply(extentId, BigInt(extentSize), \"arena offset\"),\n \"arena offset\",\n ),\n BigInt(withinExtent),\n \"arena offset\",\n );\n}\n",
13
+ "import {\n ACTIVATION_SLOT_BYTES,\n decodeArenaHeader,\n decodeMetadataBase,\n decodeTxnFrame,\n encodeActivationSlot,\n encodeArenaHeader,\n encodeMetadataBase,\n inspectMetadataBaseHeader,\n inspectTxnFrameHeader,\n METADATA_HEADER_BYTES,\n metadataBaseDigest,\n selectActivationPair,\n tryDecodeActivationSlot,\n TXN_FRAME_HEADER_BYTES,\n} from \"./codec\";\nimport type { ActivationRecord } from \"./codec\";\nimport {\n CorruptStoreError,\n ExtentSizeMismatchError,\n FsError,\n StoreLimitError,\n StoreRecreationRequiredError,\n UnexpectedStoreEntryError,\n} from \"./errors\";\nimport {\n ARENA_HEADER_BYTES,\n checkedAdd,\n checkedMultiply,\n checkedSafeNumber,\n DEFAULT_EXTENT_BYTES,\n MAX_ACTIVE_LOG_BYTES,\n MAX_ACTIVE_LOG_FRAMES,\n MAX_EXTENT_BYTES,\n MAX_METADATA_BASE_READER_BYTES,\n MIN_EXTENT_BYTES,\n validateExtentSize,\n} from \"./limits\";\nimport { metadataFileName, OWNED_FILE_NAMES, readExact, truncateChecked, writeExact } from \"./port\";\nimport type { OwnedFileName, RepackedFileHandle, RepackedPort, RepackedPortEntry } from \"./port\";\nimport { applyTxn, createInitialState, otherMetadataFile, validateState } from \"./state-machine\";\nimport type { MetadataFile, VfsState } from \"./state-machine\";\n\nexport interface OpenedMetadataStore {\n handles: Record<OwnedFileName, RepackedFileHandle>;\n state: VfsState;\n activeLogEnd: bigint;\n nextSequence: bigint;\n activeLogBytes: number;\n activeLogFrames: number;\n activationSequence: bigint;\n arenaHighWaterExtents: bigint;\n arenaSize: number;\n arenaDirty: boolean;\n activeMetadataDirty: boolean;\n}\n\nfunction validateEntries(entries: readonly RepackedPortEntry[]): void {\n for (const entry of entries) {\n if (!(OWNED_FILE_NAMES as readonly string[]).includes(entry.name) || entry.kind !== \"file\") {\n throw new UnexpectedStoreEntryError(entry.name);\n }\n }\n}\n\nfunction closeHandles(handles: readonly RepackedFileHandle[]): void {\n for (let index = handles.length - 1; index >= 0; index -= 1) {\n try {\n handles[index]!.close();\n } catch {\n // Failed-open cleanup preserves the opening error; lifecycle closes aggregate later.\n }\n }\n}\n\nasync function acquireHandles(port: RepackedPort): Promise<Record<OwnedFileName, RepackedFileHandle>> {\n validateEntries(await port.enumerate(\"store.enumerate.initial\"));\n const acquired: RepackedFileHandle[] = [];\n try {\n const activation = await port.acquire(\"activation.bin\", \"store.acquire.activation\");\n acquired.push(activation);\n validateEntries(await port.enumerate(\"store.enumerate.locked\"));\n for (const name of [\"arena.bin\", \"metadata-a.bin\", \"metadata-b.bin\"] as const) {\n acquired.push(await port.acquire(name, `store.acquire.${name}`));\n }\n return Object.fromEntries(acquired.map((handle) => [handle.name, handle])) as Record<\n OwnedFileName,\n RepackedFileHandle\n >;\n } catch (cause) {\n closeHandles(acquired);\n throw cause;\n }\n}\n\nfunction getSizes(handles: Record<OwnedFileName, RepackedFileHandle>): Record<OwnedFileName, number> {\n return Object.fromEntries(\n OWNED_FILE_NAMES.map((name) => [name, handles[name].getSize(`store.size.${name}`)]),\n ) as Record<OwnedFileName, number>;\n}\n\nfunction readSlot(handle: RepackedFileHandle, size: number, index: number): Uint8Array {\n const offset = index * ACTIVATION_SLOT_BYTES;\n if (offset >= size) return new Uint8Array();\n const length = Math.min(ACTIVATION_SLOT_BYTES, size - offset);\n return readExact(handle, BigInt(offset), length, ACTIVATION_SLOT_BYTES, `activation.read.slot-${index}`);\n}\n\nfunction isPrefix(bytes: Uint8Array, canonical: Uint8Array): boolean {\n if (bytes.byteLength > canonical.byteLength) return false;\n for (let index = 0; index < bytes.byteLength; index += 1) {\n if (bytes[index] !== canonical[index]) return false;\n }\n return true;\n}\n\nfunction readWhole(handle: RepackedFileHandle, size: number, maximum: number, label: string): Uint8Array {\n return readExact(handle, 0n, size, maximum, label);\n}\n\nfunction bootstrapExtentSize(\n arena: RepackedFileHandle,\n arenaSize: number,\n configuredExtentSize: number | undefined,\n): number {\n if (arenaSize === 0) return configuredExtentSize ?? DEFAULT_EXTENT_BYTES;\n if (arenaSize >= ARENA_HEADER_BYTES) {\n const header = readExact(arena, 0n, ARENA_HEADER_BYTES, ARENA_HEADER_BYTES, \"arena.read.bootstrap\");\n const extentSize = decodeArenaHeader(header).extentSize;\n if (arenaSize > ARENA_HEADER_BYTES) {\n throw new CorruptStoreError(\"unactivated arena contains extent payload\");\n }\n return extentSize;\n }\n const bytes = readWhole(arena, arenaSize, ARENA_HEADER_BYTES, \"arena.read.bootstrap\");\n let partialExtentSize: number | undefined;\n if (arenaSize >= 20) {\n const declared = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(16, true);\n try {\n partialExtentSize = validateExtentSize(declared);\n } catch (cause) {\n if (!(cause instanceof TypeError)) throw cause;\n partialExtentSize = undefined;\n }\n }\n // Candidate order is significance order: an ambiguous short prefix (fewer\n // than 20 bytes never fixes the extent-size field) must resolve to the\n // configured size or the creation default, never to the smallest candidate\n // that happens to share the prefix.\n const candidates = new Set<number>();\n if (configuredExtentSize !== undefined) candidates.add(configuredExtentSize);\n if (partialExtentSize !== undefined) candidates.add(partialExtentSize);\n candidates.add(DEFAULT_EXTENT_BYTES);\n if (arenaSize < 20) {\n for (let candidate = MIN_EXTENT_BYTES; candidate <= MAX_EXTENT_BYTES; candidate += ARENA_HEADER_BYTES) {\n candidates.add(candidate);\n }\n }\n const matchingExtentSize = [...candidates].find((candidate) =>\n isPrefix(bytes, encodeArenaHeader({ extentSize: candidate })),\n );\n if (matchingExtentSize === undefined) {\n throw new CorruptStoreError(\"unactivated arena is not canonical bootstrap residue\");\n }\n return partialExtentSize ?? matchingExtentSize;\n}\n\nfunction detectArenaVersion(handle: RepackedFileHandle, size: number): void {\n if (size < ARENA_HEADER_BYTES) return;\n const bytes = readExact(handle, 0n, ARENA_HEADER_BYTES, ARENA_HEADER_BYTES, \"arena.inspect.identity\");\n try {\n decodeArenaHeader(bytes);\n } catch (cause) {\n if (cause instanceof StoreRecreationRequiredError) throw cause;\n if (!(cause instanceof CorruptStoreError)) throw cause;\n }\n}\n\nfunction detectCompleteMetadataVersion(handle: RepackedFileHandle, size: number, label: string): void {\n if (size < METADATA_HEADER_BYTES) return;\n let header;\n try {\n header = inspectMetadataBaseHeader(readExact(handle, 0n, METADATA_HEADER_BYTES, METADATA_HEADER_BYTES, label));\n } catch (cause) {\n if (cause instanceof CorruptStoreError) return;\n throw cause;\n }\n if (header.baseEnd > BigInt(size)) return;\n const base = readExact(\n handle,\n 0n,\n Number(header.baseEnd),\n METADATA_HEADER_BYTES + MAX_METADATA_BASE_READER_BYTES,\n `${label}.base`,\n );\n try {\n decodeMetadataBase(base);\n } catch (cause) {\n if (cause instanceof StoreRecreationRequiredError) throw cause;\n if (!(cause instanceof CorruptStoreError)) throw cause;\n }\n}\n\nfunction classifyBootstrapResidue(\n handles: Record<OwnedFileName, RepackedFileHandle>,\n sizes: Record<OwnedFileName, number>,\n configuredExtentSize: number | undefined,\n): number {\n const extentSize = bootstrapExtentSize(handles[\"arena.bin\"], sizes[\"arena.bin\"], configuredExtentSize);\n const initialA = createInitialState(extentSize);\n const baseA = encodeMetadataBase(initialA);\n const initialB = createInitialState(extentSize);\n initialB.activeMetadataFile = \"b\";\n initialB.retainedGenerations = { a: null, b: 1n };\n const baseB = encodeMetadataBase(initialB);\n for (const [name, canonical] of [\n [\"metadata-a.bin\", baseA],\n [\"metadata-b.bin\", baseB],\n ] as const) {\n const size = sizes[name];\n detectCompleteMetadataVersion(handles[name], size, `${name}.inspect.bootstrap`);\n if (size > canonical.byteLength) {\n throw new CorruptStoreError(`${name} exceeds the empty-root bootstrap envelope`);\n }\n const bytes = readWhole(handles[name], size, canonical.byteLength, `${name}.read.bootstrap`);\n if (!isPrefix(bytes, canonical)) {\n throw new CorruptStoreError(`${name} is not canonical bootstrap residue`);\n }\n }\n if (sizes[\"activation.bin\"] > ACTIVATION_SLOT_BYTES * 2) {\n throw new CorruptStoreError(\"unactivated manifest exceeds its fixed envelope\");\n }\n const initialSlot = encodeActivationSlot({\n sequence: 1n,\n metadataFile: \"a\",\n generation: 1n,\n baseEnd: BigInt(baseA.byteLength),\n baseDigest: metadataBaseDigest(baseA),\n });\n const canonicalManifest = new Uint8Array(ACTIVATION_SLOT_BYTES * 2);\n canonicalManifest.set(initialSlot);\n const manifest = readWhole(\n handles[\"activation.bin\"],\n sizes[\"activation.bin\"],\n canonicalManifest.byteLength,\n \"activation.read.bootstrap\",\n );\n if (!isPrefix(manifest, canonicalManifest)) {\n throw new CorruptStoreError(\"manifest is not canonical bootstrap residue\");\n }\n if (\n sizes[\"arena.bin\"] === ARENA_HEADER_BYTES &&\n configuredExtentSize !== undefined &&\n configuredExtentSize !== extentSize\n ) {\n throw new ExtentSizeMismatchError(configuredExtentSize, extentSize);\n }\n return sizes[\"arena.bin\"] < ARENA_HEADER_BYTES && configuredExtentSize !== undefined\n ? configuredExtentSize\n : extentSize;\n}\n\nfunction bootstrap(handles: Record<OwnedFileName, RepackedFileHandle>, extentSize: number): OpenedMetadataStore {\n const state = createInitialState(extentSize);\n const arenaBytes = encodeArenaHeader({ extentSize });\n const baseBytes = encodeMetadataBase(state);\n const activationBytes = encodeActivationSlot({\n sequence: 1n,\n metadataFile: \"a\",\n generation: 1n,\n baseEnd: BigInt(baseBytes.byteLength),\n baseDigest: metadataBaseDigest(baseBytes),\n });\n const arena = handles[\"arena.bin\"];\n arena.truncate(0, \"bootstrap.arena.reset\");\n writeExact(arena, 0n, arenaBytes, \"bootstrap.arena.write\");\n arena.flush(\"bootstrap.arena.flush\");\n const metadataA = handles[\"metadata-a.bin\"];\n metadataA.truncate(0, \"bootstrap.metadata-a.reset\");\n writeExact(metadataA, 0n, baseBytes, \"bootstrap.metadata-a.write\");\n metadataA.flush(\"bootstrap.metadata-a.flush\");\n handles[\"metadata-b.bin\"].truncate(0, \"bootstrap.metadata-b.reset\");\n const activation = handles[\"activation.bin\"];\n activation.truncate(0, \"bootstrap.activation.reset\");\n writeExact(activation, 0n, activationBytes, \"bootstrap.activation.write\");\n activation.flush(\"bootstrap.activation.flush\");\n const decoded = decodeMetadataBase(baseBytes);\n return {\n handles,\n state: decoded.state,\n activeLogEnd: decoded.baseEnd,\n nextSequence: 1n,\n activeLogBytes: 0,\n activeLogFrames: 0,\n activationSequence: 1n,\n arenaHighWaterExtents: 0n,\n arenaSize: arenaBytes.byteLength,\n arenaDirty: false,\n activeMetadataDirty: false,\n };\n}\n\nfunction metadataHandle(handles: Record<OwnedFileName, RepackedFileHandle>, file: MetadataFile): RepackedFileHandle {\n return handles[metadataFileName(file)];\n}\n\nfunction verifyInactiveVersion(\n handles: Record<OwnedFileName, RepackedFileHandle>,\n sizes: Record<OwnedFileName, number>,\n selectedFile: MetadataFile,\n): void {\n const inactiveName = metadataFileName(otherMetadataFile(selectedFile));\n detectCompleteMetadataVersion(handles[inactiveName], sizes[inactiveName], `${inactiveName}.inspect.inactive`);\n}\n\nfunction readSelectedBase(\n handle: RepackedFileHandle,\n fileSize: number,\n selected: ActivationRecord,\n): ReturnType<typeof decodeMetadataBase> & { header: ReturnType<typeof inspectMetadataBaseHeader> } {\n if (fileSize < METADATA_HEADER_BYTES) throw new CorruptStoreError(\"selected metadata base is missing or short\");\n const headerBytes = readExact(handle, 0n, METADATA_HEADER_BYTES, METADATA_HEADER_BYTES, \"metadata.read.header\");\n const header = inspectMetadataBaseHeader(headerBytes);\n if (header.baseEnd !== selected.baseEnd || header.baseEnd > BigInt(fileSize)) {\n throw new CorruptStoreError(\"selected metadata base end does not match activation\");\n }\n const baseBytes = readExact(\n handle,\n 0n,\n Number(header.baseEnd),\n METADATA_HEADER_BYTES + MAX_METADATA_BASE_READER_BYTES,\n \"metadata.read.base\",\n );\n const decoded = decodeMetadataBase(baseBytes);\n if (\n decoded.state.activeMetadataFile !== selected.metadataFile ||\n decoded.state.generation !== selected.generation ||\n decoded.baseEnd !== selected.baseEnd ||\n decoded.baseDigest !== selected.baseDigest\n ) {\n throw new CorruptStoreError(\"selected metadata base identity does not match activation\");\n }\n return { ...decoded, header };\n}\n\nfunction requiredArenaEnd(state: VfsState): bigint {\n return checkedAdd(\n BigInt(ARENA_HEADER_BYTES),\n checkedMultiply(state.allocator.totalExtents, BigInt(state.extentSize), \"required arena bytes\"),\n \"required arena end\",\n );\n}\n\nfunction replayLog(\n handle: RepackedFileHandle,\n fileSize: number,\n state: VfsState,\n baseEnd: bigint,\n): { validEnd: bigint; nextSequence: bigint; requiredArenaEnd: bigint } {\n let cursor = checkedSafeNumber(baseEnd, \"active log start\");\n let sequence = 1n;\n let frameCount = 0;\n while (cursor < fileSize && frameCount < MAX_ACTIVE_LOG_FRAMES) {\n const logBytes = cursor - Number(baseEnd);\n const remaining = fileSize - cursor;\n if (remaining < TXN_FRAME_HEADER_BYTES || logBytes + TXN_FRAME_HEADER_BYTES > MAX_ACTIVE_LOG_BYTES) break;\n const headerBytes = readExact(\n handle,\n BigInt(cursor),\n TXN_FRAME_HEADER_BYTES,\n TXN_FRAME_HEADER_BYTES,\n \"metadata.log.read-header\",\n );\n let inspected;\n try {\n inspected = inspectTxnFrameHeader(headerBytes);\n } catch (cause) {\n if (cause instanceof CorruptStoreError) break;\n throw cause;\n }\n if (inspected.frameBytes > remaining || logBytes + inspected.frameBytes > MAX_ACTIVE_LOG_BYTES) break;\n const frameBytes = readExact(\n handle,\n BigInt(cursor),\n inspected.frameBytes,\n TXN_FRAME_HEADER_BYTES + inspected.payloadLength,\n \"metadata.log.read-frame\",\n );\n try {\n const frame = decodeTxnFrame(frameBytes);\n if (frame.generation !== state.generation || frame.sequence !== sequence) break;\n applyTxn(state, frame.record);\n } catch (cause) {\n if (cause instanceof CorruptStoreError || cause instanceof FsError || cause instanceof StoreLimitError) {\n break;\n }\n throw cause;\n }\n cursor += inspected.frameBytes;\n sequence += 1n;\n frameCount += 1;\n }\n validateState(state);\n return { validEnd: BigInt(cursor), nextSequence: sequence, requiredArenaEnd: requiredArenaEnd(state) };\n}\n\nfunction recoverActivated(\n handles: Record<OwnedFileName, RepackedFileHandle>,\n sizes: Record<OwnedFileName, number>,\n leftBytes: Uint8Array,\n rightBytes: Uint8Array,\n configuredExtentSize: number | undefined,\n): OpenedMetadataStore {\n if (sizes[\"arena.bin\"] < ARENA_HEADER_BYTES) {\n throw new CorruptStoreError(\"activated arena header is missing or short\");\n }\n const arenaHeader = decodeArenaHeader(\n readExact(handles[\"arena.bin\"], 0n, ARENA_HEADER_BYTES, ARENA_HEADER_BYTES, \"arena.read.header\"),\n );\n const selection = selectActivationPair(leftBytes, rightBytes);\n verifyInactiveVersion(handles, sizes, selection.selected.metadataFile);\n const selectedHandle = metadataHandle(handles, selection.selected.metadataFile);\n const selectedName = selectedHandle.name;\n const decoded = readSelectedBase(selectedHandle, sizes[selectedName], selection.selected);\n if (\n decoded.state.extentSize !== arenaHeader.extentSize ||\n decoded.header.limitsProfileVersion !== arenaHeader.limitsProfileVersion\n ) {\n throw new CorruptStoreError(\"arena and metadata identities disagree\");\n }\n if (selection.other !== null) {\n decoded.state.retainedGenerations[selection.other.metadataFile] = selection.other.generation;\n }\n try {\n validateState(decoded.state);\n } catch (cause) {\n if (cause instanceof StoreLimitError) {\n throw new CorruptStoreError(`activation retained-generation facts are invalid: ${cause.message}`, { cause });\n }\n throw cause;\n }\n const replayed = replayLog(selectedHandle, sizes[selectedName], decoded.state, decoded.baseEnd);\n if (configuredExtentSize !== undefined && configuredExtentSize !== arenaHeader.extentSize) {\n throw new ExtentSizeMismatchError(configuredExtentSize, arenaHeader.extentSize);\n }\n const requiredEnd = checkedSafeNumber(replayed.requiredArenaEnd, \"required arena end\");\n const arenaDirty = sizes[\"arena.bin\"] < requiredEnd;\n if (arenaDirty) {\n truncateChecked(handles[\"arena.bin\"], replayed.requiredArenaEnd, \"recovery.arena.grow\");\n }\n const activeMetadataDirty = replayed.validEnd < BigInt(sizes[selectedName]);\n if (activeMetadataDirty) {\n truncateChecked(selectedHandle, replayed.validEnd, \"recovery.metadata.discard-suffix\");\n }\n const physicalArenaExtents =\n (BigInt(Math.max(0, sizes[\"arena.bin\"] - ARENA_HEADER_BYTES)) + BigInt(arenaHeader.extentSize) - 1n) /\n BigInt(arenaHeader.extentSize);\n return {\n handles,\n state: decoded.state,\n activeLogEnd: replayed.validEnd,\n nextSequence: replayed.nextSequence,\n activeLogBytes: Number(replayed.validEnd - decoded.baseEnd),\n activeLogFrames: Number(replayed.nextSequence - 1n),\n activationSequence: selection.selected.sequence,\n arenaHighWaterExtents:\n physicalArenaExtents > decoded.state.allocator.totalExtents\n ? physicalArenaExtents\n : decoded.state.allocator.totalExtents,\n arenaSize: arenaDirty ? requiredEnd : sizes[\"arena.bin\"],\n arenaDirty,\n activeMetadataDirty,\n };\n}\n\nexport async function openMetadataStore(\n port: RepackedPort,\n options: { extentSize?: number },\n): Promise<OpenedMetadataStore> {\n const configuredExtentSize = options.extentSize;\n if (configuredExtentSize !== undefined) validateExtentSize(configuredExtentSize);\n const handles = await acquireHandles(port);\n try {\n const sizes = getSizes(handles);\n const leftBytes = readSlot(handles[\"activation.bin\"], sizes[\"activation.bin\"], 0);\n const rightBytes = readSlot(handles[\"activation.bin\"], sizes[\"activation.bin\"], 1);\n detectArenaVersion(handles[\"arena.bin\"], sizes[\"arena.bin\"]);\n detectCompleteMetadataVersion(\n handles[\"metadata-a.bin\"],\n sizes[\"metadata-a.bin\"],\n \"metadata-a.bin.inspect.identity\",\n );\n detectCompleteMetadataVersion(\n handles[\"metadata-b.bin\"],\n sizes[\"metadata-b.bin\"],\n \"metadata-b.bin.inspect.identity\",\n );\n const left = tryDecodeActivationSlot(leftBytes);\n const right = tryDecodeActivationSlot(rightBytes);\n if (sizes[\"activation.bin\"] > ACTIVATION_SLOT_BYTES * 2) {\n throw new CorruptStoreError(\"manifest exceeds its fixed envelope\");\n }\n if (left !== null || right !== null) {\n return recoverActivated(handles, sizes, leftBytes, rightBytes, configuredExtentSize);\n }\n const extentSize = classifyBootstrapResidue(handles, sizes, configuredExtentSize);\n return bootstrap(handles, extentSize);\n } catch (cause) {\n closeHandles(Object.values(handles));\n throw cause;\n }\n}\n",
14
+ "import {\n ACTIVATION_SLOT_BYTES,\n encodeActivationSlot,\n encodeTxnFrame,\n encodeValidatedMetadataBase,\n metadataBaseDigest,\n txnFrameBytes,\n} from \"./codec\";\nimport { CorruptStoreError, FS_ERRNO, FsError, StoreClosedError, StoreFailedError, StoreLimitError } from \"./errors\";\nimport {\n ARENA_HEADER_BYTES,\n checkedAdd,\n checkedMultiply,\n checkedSafeNumber,\n checkedU64,\n MAX_ACTIVE_LOG_BYTES,\n MAX_ACTIVE_LOG_FRAMES,\n MAX_EXTENTS_PER_INODE,\n MAX_METADATA_BASE_WRITER_BYTES,\n SOFT_ACTIVE_LOG_BYTES,\n SOFT_ACTIVE_LOG_FRAMES,\n} from \"./limits\";\nimport { openMetadataStore } from \"./metadata-store\";\nimport type { OpenedMetadataStore } from \"./metadata-store\";\nimport { encodedUtf8Length } from \"./path\";\nimport { arenaByteOffset, metadataFileName, PortWriteError, truncateChecked, writeExact } from \"./port\";\nimport type { RepackedFileHandle, RepackedPort } from \"./port\";\nimport {\n applyTxn,\n expandExtentRuns,\n getInodeAtPath,\n makeOrphanRecord,\n planChmod,\n planCreateFile,\n planMkdir,\n planRename,\n planReserveQuarantine,\n planResizeFile,\n planResizeFileForInode,\n planRmdir,\n planSymlink,\n planUnlink,\n planUtimes,\n prepareTxnProjection,\n projectRepackForActivation,\n resolveLinks,\n} from \"./state-machine\";\nimport type {\n ExtentRun,\n FileInode,\n Inode,\n OrphanRecord,\n PreparedTxnProjection,\n SymlinkInode,\n TxnRecord,\n} from \"./state-machine\";\n\ninterface Descriptor {\n inodeId: bigint;\n offset: bigint;\n readable: boolean;\n writable: boolean;\n append: boolean;\n orphan?: OrphanRecord;\n}\n\ninterface ParsedFlags {\n readable: boolean;\n writable: boolean;\n create: boolean;\n exclusive: boolean;\n truncate: boolean;\n append: boolean;\n}\n\ninterface WriteProgress {\n bytes: number;\n error?: unknown;\n}\n\ninterface PreparedCommit {\n readonly frame: Uint8Array | undefined;\n readonly frameBytes: number;\n readonly projection: PreparedTxnProjection;\n readonly materializedRecord: TxnRecord;\n readonly deferResize: boolean;\n readonly replacesPendingResize: boolean;\n}\n\ninterface PendingResizeCommit {\n readonly record: Extract<TxnRecord, { kind: \"resizeFile\" }>;\n readonly frameBytes: number;\n readonly sequence: bigint;\n}\n\ntype FlushKind = \"amortized\" | \"arena\" | \"metadata\" | \"zeroBarrier\" | \"manifest\";\nconst REPACK_INTERVAL_MS = 30_000;\nconst AMORTIZED_ARENA_FLUSH_BYTES = 4 * 1024 * 1024;\nconst BASE_REPACK_PRESSURE_BYTES = Math.floor(MAX_METADATA_BASE_WRITER_BYTES * 0.75);\nconst QUARANTINE_PRESSURE_EXTENTS = 64;\n\nclass ArenaGrowthQuotaError extends Error {\n override readonly cause: unknown;\n\n constructor(cause: unknown) {\n super(\"arena growth exhausted the storage quota\");\n this.name = \"ArenaGrowthQuotaError\";\n this.cause = cause;\n }\n}\n\nfunction isQuotaExceeded(cause: unknown): boolean {\n return typeof cause === \"object\" && cause !== null && \"name\" in cause && cause.name === \"QuotaExceededError\";\n}\n\nfunction mergeExtentRuns(left: readonly ExtentRun[], right: readonly ExtentRun[]): ExtentRun[] {\n const merged = left.map((run) => ({ ...run }));\n for (const run of right) {\n const last = merged.at(-1);\n if (last !== undefined && last.start + BigInt(last.count) === run.start && last.count + run.count <= 0xffff_ffff) {\n last.count += run.count;\n } else {\n merged.push({ ...run });\n }\n }\n return merged;\n}\n\nexport interface RepackedVfsOpenOptions {\n /** Creation extent size: 8 KiB–16 MiB in 8 KiB steps. Defaults to 64 KiB. */\n extentSize?: number;\n}\n\nexport interface RepackedStat {\n /**\n * `symlink` is only ever reported by `lstat` — `stat` follows the link and reports its target.\n * A link's `size` is the UTF-8 byte length of its target, exactly as POSIX `lstat` reports it.\n */\n readonly kind: \"directory\" | \"file\" | \"symlink\";\n readonly mode: number;\n readonly size: bigint;\n readonly atimeMs: bigint;\n readonly mtimeMs: bigint;\n readonly ctimeMs: bigint;\n}\n\nexport type RepackReason =\n | \"manual\"\n | \"time\"\n | \"log-bytes\"\n | \"log-frames\"\n | \"writer-limit\"\n | \"quarantine-pressure\"\n | \"quota\";\n\nexport interface RepackedVfsMetrics {\n readonly generation: bigint;\n readonly totalExtents: bigint;\n readonly availableExtents: number;\n readonly quarantineExtents: number;\n readonly quarantineBytes: bigint;\n readonly activeLogBytes: number;\n readonly activeLogFrames: number;\n readonly lastRepackReason: RepackReason | null;\n readonly lastRepackDurationMs: number | null;\n readonly repackCount: number;\n readonly pendingRepackReason: RepackReason | null;\n readonly flushes: Readonly<{\n amortized: number;\n arena: number;\n metadata: number;\n zeroBarrier: number;\n manifest: number;\n }>;\n}\n\n/**\n * The file surface of a repacked store, as a TYPE.\n *\n * `RepackedVfs` is the one-store implementation; {@link MountedRepackedVfs} is a composite of\n * several. Everything that takes a store — the sync broker above all — takes this, so a host can\n * hand it either without the two knowing about each other.\n */\nexport interface RepackedFileSystem {\n strictSync(): void;\n assertHealthy(): void;\n fail(cause: unknown): never;\n metrics(): RepackedVfsMetrics;\n repack(reason?: RepackReason): void;\n runScheduledRepack(nowMs?: number): boolean;\n /** The link-free absolute path `path` names; `follow` governs the final component only. */\n resolvePath(path: string, follow?: boolean): string;\n stat(path: string): RepackedStat;\n lstat(path: string): RepackedStat;\n symlink(target: string, path: string, nowMs: bigint): void;\n readlink(path: string): string;\n readdir(path: string): string[];\n mkdir(path: string, options: { recursive?: boolean; mode?: number; nowMs: bigint }): void;\n writeFile(\n path: string,\n data: string | Uint8Array,\n options: { encoding?: string; mode?: number; flag?: string; nowMs: bigint },\n ): void;\n readFile(path: string): Uint8Array;\n truncate(path: string, size: bigint, nowMs: bigint): void;\n open(path: string, flags?: string, mode?: number, nowMs?: bigint): number;\n fstat(fd: number): RepackedStat;\n read(fd: number, buffer: Uint8Array, offset: number, length: number, position?: bigint): number;\n write(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: bigint | undefined,\n nowMs: bigint,\n ): number;\n chmod(path: string, mode: number, nowMs: bigint): void;\n utimes(path: string, atimeMs: bigint, mtimeMs: bigint, ctimeMs: bigint): void;\n unlink(path: string, nowMs: bigint): void;\n rmdir(path: string, nowMs: bigint): void;\n rename(oldPath: string, newPath: string, nowMs: bigint): void;\n close(): void;\n close(fd: number): void;\n}\n\nexport class RepackedVfs implements RepackedFileSystem {\n readonly #store: OpenedMetadataStore;\n #status: \"open\" | \"failed\" | \"closed\" = \"open\";\n #failure: unknown;\n readonly #descriptors = new Map<number, Descriptor>();\n #nextDescriptor = 3;\n #pendingResizeCommit: PendingResizeCommit | undefined;\n #arenaSize: number | undefined;\n #arenaDirty: boolean;\n #arenaDirtyBytesSinceFlush = 0;\n #metadataDirtySinceFlush: boolean;\n #repacking = false;\n #lastRepackReason: RepackReason | null = null;\n #lastRepackDurationMs: number | null = null;\n #pendingRepackReason: RepackReason | null = null;\n #repackCount = 0;\n #lastRepackAtMs = Date.now();\n readonly #flushes = { amortized: 0, arena: 0, metadata: 0, zeroBarrier: 0, manifest: 0 };\n\n private constructor(store: OpenedMetadataStore) {\n this.#store = store;\n this.#arenaSize = store.arenaSize;\n this.#arenaDirty = store.arenaDirty;\n this.#metadataDirtySinceFlush = store.activeMetadataDirty;\n }\n\n static async open(port: RepackedPort, options: RepackedVfsOpenOptions = {}): Promise<RepackedVfs> {\n return new RepackedVfs(await openMetadataStore(port, options));\n }\n\n strictSync(): void {\n this.#assertOpen();\n try {\n if (this.#arenaDirty) this.#flush(this.#store.handles[\"arena.bin\"], \"sync.arena.flush\", \"arena\");\n this.#materializePendingResize();\n if (this.#metadataDirtySinceFlush) {\n const activeName = metadataFileName(this.#store.state.activeMetadataFile);\n this.#flush(this.#store.handles[activeName], \"sync.metadata.flush\", \"metadata\");\n }\n this.#arenaDirty = false;\n this.#arenaDirtyBytesSinceFlush = 0;\n this.#metadataDirtySinceFlush = false;\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n }\n\n assertHealthy(): void {\n this.#assertOpen();\n }\n\n fail(cause: unknown): never {\n this.#assertOpen();\n this.#poison(cause);\n throw cause;\n }\n\n cleanupFailedInit(): void {\n if (this.#status === \"closed\") return;\n this.#status = \"closed\";\n this.#descriptors.clear();\n const closeError = this.#closeHandles();\n if (closeError !== undefined) throw closeError;\n }\n\n metrics(): RepackedVfsMetrics {\n this.#assertOpen();\n return {\n generation: this.#store.state.generation,\n totalExtents: this.#store.state.allocator.totalExtents,\n availableExtents: this.#store.state.allocator.available.size,\n quarantineExtents: this.#store.state.allocator.quarantine.size,\n quarantineBytes: BigInt(this.#store.state.allocator.quarantine.size) * BigInt(this.#store.state.extentSize),\n activeLogBytes: this.#store.activeLogBytes,\n activeLogFrames: this.#store.activeLogFrames,\n lastRepackReason: this.#lastRepackReason,\n lastRepackDurationMs: this.#lastRepackDurationMs,\n repackCount: this.#repackCount,\n pendingRepackReason: this.#pendingRepackReason,\n flushes: { ...this.#flushes },\n };\n }\n\n repack(reason: RepackReason = \"manual\"): void {\n this.#assertOpen();\n if (this.#repacking) throw new Error(\"OPFS repacked VFS repack is already running\");\n checkedAdd(this.#store.state.generation, 1n, \"generation\");\n const activationSequence = checkedAdd(this.#store.activationSequence, 1n, \"activation sequence\");\n this.#repacking = true;\n const startedAt = performance.now();\n try {\n this.#materializePendingResize();\n const pinned = new Set<bigint>();\n for (const descriptor of this.#descriptors.values()) {\n if (descriptor.orphan === undefined) continue;\n for (const extentId of descriptor.orphan.extents) pinned.add(extentId);\n }\n const projected = projectRepackForActivation(this.#store.state, pinned);\n const base = encodeValidatedMetadataBase(projected);\n const activation = encodeActivationSlot({\n sequence: activationSequence,\n metadataFile: projected.activeMetadataFile,\n generation: projected.generation,\n baseEnd: BigInt(base.byteLength),\n baseDigest: metadataBaseDigest(base),\n });\n\n this.#flush(this.#store.handles[\"arena.bin\"], \"repack.arena.flush\", \"arena\");\n this.#arenaDirty = false;\n this.#arenaDirtyBytesSinceFlush = 0;\n const inactiveName = metadataFileName(projected.activeMetadataFile);\n const inactive = this.#store.handles[inactiveName];\n inactive.truncate(0, \"repack.metadata.reset\");\n writeExact(inactive, 0n, base, \"repack.metadata.write\");\n this.#flush(inactive, \"repack.metadata.flush\", \"metadata\");\n\n const activationOffset = ((activationSequence - 1n) % 2n) * BigInt(ACTIVATION_SLOT_BYTES);\n try {\n writeExact(this.#store.handles[\"activation.bin\"], activationOffset, activation, \"repack.activation.write\");\n this.#flush(this.#store.handles[\"activation.bin\"], \"repack.activation.flush\", \"manifest\");\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n\n try {\n this.#store.state = projected;\n this.#store.activeLogEnd = BigInt(base.byteLength);\n this.#store.nextSequence = 1n;\n this.#store.activeLogBytes = 0;\n this.#store.activeLogFrames = 0;\n this.#store.activationSequence = activationSequence;\n this.#metadataDirtySinceFlush = false;\n this.#lastRepackReason = reason;\n this.#pendingRepackReason = null;\n this.#repackCount += 1;\n this.#lastRepackAtMs = Date.now();\n this.#scheduleRepack();\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n\n const requiredArenaEnd = checkedAdd(\n BigInt(ARENA_HEADER_BYTES),\n checkedMultiply(projected.allocator.totalExtents, BigInt(projected.extentSize), \"arena byte length\"),\n \"arena byte length\",\n );\n try {\n if (BigInt(this.#arenaSizeChecked(\"repack.arena.size-before-trim\")) > requiredArenaEnd) {\n this.#arenaDirty = true;\n this.#truncateArena(requiredArenaEnd, \"repack.arena.trim\");\n }\n } catch {\n // The activated allocator no longer names this physical tail; recovery can trim it later.\n }\n this.#lastRepackDurationMs = performance.now() - startedAt;\n } finally {\n this.#repacking = false;\n }\n }\n\n runScheduledRepack(nowMs = Date.now()): boolean {\n this.#assertOpen();\n if (!Number.isSafeInteger(nowMs) || nowMs < 0) throw new TypeError(\"repack scheduler time is invalid\");\n this.#materializePendingResize();\n if (this.#arenaDirtyBytesSinceFlush >= AMORTIZED_ARENA_FLUSH_BYTES) {\n try {\n this.#flush(this.#store.handles[\"arena.bin\"], \"sync.arena.amortized.flush\", \"amortized\");\n this.#arenaDirty = false;\n this.#arenaDirtyBytesSinceFlush = 0;\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n }\n const reason = this.#dueRepackReason(nowMs);\n if (reason === null) return false;\n this.repack(reason);\n this.#lastRepackAtMs = nowMs;\n return true;\n }\n\n /**\n * The link-free absolute path `path` names, without touching anything. A composite VFS resolves\n * across a mount boundary with it: this store answers for the part of the path it holds, stops at\n * the first component it does not have, and carries the rest through verbatim.\n */\n resolvePath(path: string, follow = true): string {\n this.#assertOpen();\n return this.#resolve(path, follow);\n }\n\n /** Follows a symbolic link on the final component; every intermediate link is always followed. */\n stat(requestPath: string): RepackedStat {\n this.#assertOpen();\n return this.#statValue(getInodeAtPath(this.#store.state, this.#resolve(requestPath, true)));\n }\n\n /** Reports the LINK itself when the final component is one. */\n lstat(requestPath: string): RepackedStat {\n this.#assertOpen();\n return this.#statValue(getInodeAtPath(this.#store.state, this.#resolve(requestPath, false)));\n }\n\n /** Create a symbolic link at `path` pointing at the ABSOLUTE `target`. The target is not read. */\n symlink(target: string, requestPath: string, nowMs: bigint): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, false);\n this.#commit(planSymlink(this.#store.state, path, target, { nowMs }).record);\n }\n\n /** The target of the symbolic link at `path`. `EINVAL` when the path is not a link. */\n readlink(requestPath: string): string {\n this.#assertOpen();\n const path = this.#resolve(requestPath, false);\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"symlink\") throw new FsError(\"EINVAL\", \"path is not a symbolic link\", { path });\n return inode.target;\n }\n\n readdir(requestPath: string): string[] {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"directory\") throw new FsError(\"ENOTDIR\", \"path is not a directory\", { path });\n return [...inode.children.keys()].sort();\n }\n\n mkdir(requestPath: string, options: { recursive?: boolean; mode?: number; nowMs: bigint }): void {\n this.#assertOpen();\n // The final component is the directory being CREATED, so it is never followed; a link already\n // sitting there is `EEXIST`, exactly as POSIX `mkdir` reports it.\n this.#commit(planMkdir(this.#store.state, this.#resolve(requestPath, false), options).record);\n }\n\n writeFile(\n requestPath: string,\n data: string | Uint8Array,\n options: { encoding?: string; mode?: number; flag?: string; nowMs: bigint },\n ): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n const flags = this.#parseFlags(options.flag ?? \"w\");\n if (!flags.writable)\n throw new FsError(\"EBADF\", \"writeFile flags are not writable\", { operation: \"writeFile\", path });\n let bytes: Uint8Array;\n if (typeof data === \"string\") {\n this.#validateEncoding(options.encoding ?? \"utf8\", path);\n bytes = new TextEncoder().encode(data);\n } else {\n bytes = data;\n }\n checkedU64(options.nowMs, \"timestamp\");\n let existing: FileInode | undefined;\n try {\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n existing = inode;\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) throw cause;\n }\n if (existing !== undefined && flags.create && flags.exclusive) {\n throw new FsError(\"EEXIST\", \"path already exists\", { operation: \"writeFile\", path });\n }\n if (existing === undefined && !flags.create) {\n throw new FsError(\"ENOENT\", \"path does not exist\", { operation: \"writeFile\", path });\n }\n const wasExisting = existing !== undefined;\n if (bytes.byteLength === 0 && existing !== undefined && !flags.truncate) return;\n const buildPlan = () => {\n let current: FileInode | undefined;\n if (wasExisting) {\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n current = inode;\n }\n const currentStart = current !== undefined && flags.append ? current.size : 0n;\n const targetSize =\n current === undefined\n ? BigInt(bytes.byteLength)\n : flags.append\n ? checkedAdd(current.size, BigInt(bytes.byteLength), \"writeFile size\")\n : flags.truncate\n ? BigInt(bytes.byteLength)\n : current.size > BigInt(bytes.byteLength)\n ? current.size\n : BigInt(bytes.byteLength);\n const currentPlan =\n current === undefined\n ? planCreateFile(this.#store.state, path, {\n ...(options.mode === undefined ? {} : { mode: options.mode }),\n nowMs: options.nowMs,\n size: targetSize,\n })\n : planResizeFile(this.#store.state, path, targetSize, options.nowMs, \"write\");\n return {\n existing: current,\n start: currentStart,\n plan: currentPlan,\n preparedCommit: this.#preflightCommit(currentPlan.record),\n allocated: expandExtentRuns(\n currentPlan.record.kind === \"createFile\" ? currentPlan.record.extents : currentPlan.record.allocated,\n MAX_EXTENTS_PER_INODE,\n ),\n };\n };\n const prepared = this.#prepareAllocationWithQuotaRetry(buildPlan(), buildPlan);\n existing = prepared.existing;\n const { start, plan, preparedCommit, allocated } = prepared;\n if (bytes.byteLength === 0) {\n this.#commit(plan.record, preparedCommit);\n return;\n }\n const progress = this.#writeLogical(existing?.extents ?? [], start, bytes, \"arena.write-file\", allocated);\n if (progress.bytes === 0) this.#failStore(progress.error);\n const partialSize =\n existing !== undefined && !flags.truncate\n ? existing.size > checkedAdd(start, BigInt(progress.bytes), \"partial writeFile size\")\n ? existing.size\n : checkedAdd(start, BigInt(progress.bytes), \"partial writeFile size\")\n : BigInt(progress.bytes);\n const committedPlan =\n progress.bytes === bytes.byteLength\n ? plan\n : existing === undefined\n ? planCreateFile(this.#store.state, path, {\n ...(options.mode === undefined ? {} : { mode: options.mode }),\n nowMs: options.nowMs,\n size: partialSize,\n })\n : planResizeFile(this.#store.state, path, partialSize, options.nowMs, \"write\");\n if (progress.error === undefined || partialSize !== existing?.size) {\n this.#commit(committedPlan.record, committedPlan === plan ? preparedCommit : undefined);\n }\n if (progress.error !== undefined) throw progress.error;\n }\n\n readFile(requestPath: string): Uint8Array {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n const output = new Uint8Array(checkedSafeNumber(inode.size, \"file read size\"));\n this.#readLogical(inode.extents, 0n, output);\n return output;\n }\n\n truncate(requestPath: string, size: bigint, nowMs: bigint): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n let inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n if (size === inode.size) return;\n let plan = planResizeFile(this.#store.state, path, size, nowMs, \"truncate\");\n let preparedCommit = this.#preflightCommit(plan.record);\n if (size > inode.size) {\n const buildPlan = () => {\n const current = getInodeAtPath(this.#store.state, path);\n if (current.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n const currentPlan = planResizeFile(this.#store.state, path, size, nowMs, \"truncate\");\n return {\n inode: current,\n plan: currentPlan,\n preparedCommit: this.#preflightCommit(currentPlan.record),\n allocated: expandExtentRuns(currentPlan.record.allocated, MAX_EXTENTS_PER_INODE),\n arenaSizeBefore: this.#arenaSizeChecked(\"arena.size.before-extension\"),\n };\n };\n const prepared = this.#prepareAllocationWithQuotaRetry(\n {\n inode,\n plan,\n preparedCommit,\n allocated: expandExtentRuns(plan.record.allocated, MAX_EXTENTS_PER_INODE),\n arenaSizeBefore: this.#arenaSizeChecked(\"arena.size.before-extension\"),\n },\n buildPlan,\n );\n inode = prepared.inode;\n plan = prepared.plan;\n preparedCommit = prepared.preparedCommit;\n const touchedExisting = this.#zeroLogical(\n inode.extents,\n inode.size,\n size - inode.size,\n prepared.arenaSizeBefore,\n prepared.allocated,\n );\n if (touchedExisting) this.#flushPreparedArena(\"arena.gap-zero.flush\");\n }\n this.#commit(plan.record, preparedCommit);\n }\n\n open(requestPath: string, flags = \"r\", mode = 0o100666, nowMs = 0n): number {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n const parsed = this.#parseFlags(flags);\n let inode: FileInode;\n try {\n const found = getInodeAtPath(this.#store.state, path);\n if (found.kind !== \"file\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n if (parsed.exclusive && parsed.create) throw new FsError(\"EEXIST\", \"path already exists\", { path });\n inode = found;\n if (parsed.truncate) {\n this.truncate(path, 0n, nowMs);\n inode = getInodeAtPath(this.#store.state, path) as FileInode;\n }\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT || !parsed.create) throw cause;\n this.#commit(planCreateFile(this.#store.state, path, { mode, nowMs, size: 0n }).record);\n inode = getInodeAtPath(this.#store.state, path) as FileInode;\n }\n const fd = this.#nextDescriptor++;\n this.#descriptors.set(fd, {\n inodeId: inode.id,\n offset: parsed.append ? inode.size : 0n,\n readable: parsed.readable,\n writable: parsed.writable,\n append: parsed.append,\n });\n return fd;\n }\n\n fstat(fd: number): RepackedStat {\n this.#assertOpen();\n const descriptor = this.#descriptor(fd);\n const inode = descriptor.orphan ?? this.#linkedFile(descriptor.inodeId);\n return this.#statValue(inode);\n }\n\n read(fd: number, buffer: Uint8Array, offset: number, length: number, position?: bigint): number {\n this.#assertOpen();\n this.#validateBufferRange(buffer, offset, length);\n const descriptor = this.#descriptor(fd);\n if (!descriptor.readable) throw new FsError(\"EBADF\", \"descriptor is not readable\");\n const inode = descriptor.orphan ?? this.#linkedFile(descriptor.inodeId);\n const start = position ?? descriptor.offset;\n if (start < 0n) throw new FsError(\"EINVAL\", \"read position is negative\");\n const available = start >= inode.size ? 0 : Math.min(length, checkedSafeNumber(inode.size - start, \"read length\"));\n if (available > 0) this.#readLogical(inode.extents, start, buffer.subarray(offset, offset + available));\n if (position === undefined) descriptor.offset = start + BigInt(available);\n return available;\n }\n\n write(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: bigint | undefined,\n nowMs: bigint,\n ): number {\n this.#assertOpen();\n this.#validateBufferRange(buffer, offset, length);\n checkedU64(nowMs, \"timestamp\");\n const descriptor = this.#descriptor(fd);\n if (!descriptor.writable) throw new FsError(\"EBADF\", \"descriptor is not writable\");\n if (descriptor.orphan !== undefined) {\n return this.#writeOrphan(descriptor, buffer.subarray(offset, offset + length), position, nowMs);\n }\n let inode = this.#linkedFile(descriptor.inodeId);\n const start = descriptor.append ? inode.size : (position ?? descriptor.offset);\n if (start < 0n) throw new FsError(\"EINVAL\", \"write position is negative\");\n if (length === 0) return 0;\n const requestedEnd = checkedAdd(start, BigInt(length), \"write end\");\n let admittedLength = length;\n let allocated: readonly bigint[] = [];\n let plan: ReturnType<typeof planResizeFile> | undefined;\n let preparedCommit: PreparedCommit | undefined;\n if (requestedEnd > inode.size) {\n const buildPlan = () => {\n const current = this.#linkedFile(descriptor.inodeId);\n const admitted = this.#planLinkedWrite(current, start, length, nowMs);\n return {\n inode: current,\n admitted,\n allocated:\n admitted.plan === undefined ? [] : expandExtentRuns(admitted.plan.record.allocated, MAX_EXTENTS_PER_INODE),\n arenaSizeBefore: start > current.size ? this.#arenaSizeChecked(\"arena.size.before-write-extension\") : 0,\n };\n };\n const prepared = this.#prepareAllocationWithQuotaRetry(buildPlan(), buildPlan);\n inode = prepared.inode;\n plan = prepared.admitted.plan;\n preparedCommit = prepared.admitted.preparedCommit;\n admittedLength = prepared.admitted.length;\n if (plan !== undefined) {\n allocated = prepared.allocated;\n if (start > inode.size) {\n const touchedExisting = this.#zeroLogical(\n inode.extents,\n inode.size,\n start - inode.size,\n prepared.arenaSizeBefore,\n allocated,\n );\n if (touchedExisting) this.#flushPreparedArena(\"arena.gap-zero.flush\");\n }\n }\n }\n const source = buffer.subarray(offset, offset + admittedLength);\n const progress = this.#writeLogical(inode.extents, start, source, \"arena.write\", allocated);\n if (progress.bytes === 0) this.#failStore(progress.error);\n const completedEnd = checkedAdd(start, BigInt(progress.bytes), \"completed write end\");\n if (completedEnd > inode.size) {\n const committedPlan =\n plan !== undefined && completedEnd === plan.record.size\n ? plan\n : planResizeFileForInode(this.#store.state, inode, completedEnd, nowMs, \"write\");\n this.#commit(committedPlan.record, committedPlan === plan ? preparedCommit : undefined);\n }\n if (position === undefined) descriptor.offset = completedEnd;\n return progress.bytes;\n }\n\n chmod(requestPath: string, mode: number, nowMs: bigint): void {\n this.#assertOpen();\n this.#commit(planChmod(this.#store.state, this.#resolve(requestPath, true), mode, nowMs).record);\n }\n\n utimes(requestPath: string, atimeMs: bigint, mtimeMs: bigint, ctimeMs: bigint): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, true);\n this.#commit(planUtimes(this.#store.state, path, atimeMs, mtimeMs, ctimeMs).record);\n }\n\n /** Removes a file or a SYMBOLIC LINK. The final component is never followed. */\n unlink(requestPath: string, nowMs: bigint): void {\n this.#assertOpen();\n const path = this.#resolve(requestPath, false);\n const inode = getInodeAtPath(this.#store.state, path);\n if (inode.kind === \"directory\") throw new FsError(\"EISDIR\", \"path is a directory\", { path });\n const affected =\n inode.kind === \"file\"\n ? [...this.#descriptors.values()].filter(\n (descriptor) => descriptor.orphan === undefined && descriptor.inodeId === inode.id,\n )\n : [];\n const orphan = inode.kind === \"file\" && affected.length > 0 ? makeOrphanRecord(inode) : undefined;\n this.#commit(planUnlink(this.#store.state, path, nowMs).record);\n if (orphan !== undefined) for (const descriptor of affected) descriptor.orphan = orphan;\n }\n\n rmdir(requestPath: string, nowMs: bigint): void {\n this.#assertOpen();\n this.#commit(planRmdir(this.#store.state, this.#resolve(requestPath, false), nowMs).record);\n }\n\n /** Renames the entry itself: a symbolic link moves as a link, and its target is never followed. */\n rename(oldRequestPath: string, newRequestPath: string, nowMs: bigint): void {\n this.#assertOpen();\n const oldPath = this.#resolve(oldRequestPath, false);\n const newPath = this.#resolve(newRequestPath, false);\n let destination: FileInode | undefined;\n try {\n const inode = getInodeAtPath(this.#store.state, newPath);\n if (inode.kind === \"file\") destination = inode;\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) throw cause;\n }\n const affected =\n destination === undefined\n ? []\n : [...this.#descriptors.values()].filter(\n (descriptor) => descriptor.orphan === undefined && descriptor.inodeId === destination.id,\n );\n const orphan = destination !== undefined && affected.length > 0 ? makeOrphanRecord(destination) : undefined;\n this.#commit(planRename(this.#store.state, oldPath, newPath, nowMs).record);\n if (orphan !== undefined) for (const descriptor of affected) descriptor.orphan = orphan;\n }\n\n close(): void;\n close(fd: number): void;\n close(fd?: number): void {\n if (fd !== undefined) {\n this.#assertOpen();\n if (!this.#descriptors.delete(fd)) throw new FsError(\"EBADF\", \"descriptor is invalid\");\n return;\n }\n if (this.#status === \"closed\") return;\n let firstError: unknown;\n if (this.#status === \"open\") {\n try {\n this.strictSync();\n } catch (cause) {\n firstError = cause;\n }\n } else {\n firstError = new StoreFailedError(this.#failure);\n }\n this.#status = \"closed\";\n this.#descriptors.clear();\n const closeError = this.#closeHandles();\n firstError ??= closeError;\n if (firstError !== undefined) throw firstError;\n }\n\n #closeHandles(): unknown {\n let firstError: unknown;\n for (const name of [\"metadata-b.bin\", \"metadata-a.bin\", \"arena.bin\", \"activation.bin\"] as const) {\n try {\n this.#store.handles[name].close();\n } catch (cause) {\n firstError ??= cause;\n }\n }\n return firstError;\n }\n\n #prepareAllocated(extents: readonly bigint[]): void {\n if (extents.length === 0) return;\n const totalBefore = this.#store.state.allocator.totalExtents;\n const highWaterBefore = this.#store.arenaHighWaterExtents;\n const fresh = extents.filter((extentId) => extentId >= totalBefore);\n const arenaSizeBefore = this.#arenaSizeChecked(\"arena.size.before-allocation\");\n if (fresh.length > 0) {\n const last = fresh[fresh.length - 1]!;\n const requiredExtents = checkedAdd(last, 1n, \"arena extent count\");\n const requiredEnd = checkedAdd(\n BigInt(ARENA_HEADER_BYTES),\n checkedMultiply(requiredExtents, BigInt(this.#store.state.extentSize), \"arena byte length\"),\n \"arena byte length\",\n );\n if (requiredEnd > BigInt(arenaSizeBefore)) {\n this.#arenaDirty = true;\n if (requiredExtents > this.#store.arenaHighWaterExtents) {\n this.#store.arenaHighWaterExtents = requiredExtents;\n }\n try {\n this.#truncateArena(requiredEnd, \"arena.grow\");\n } catch (cause) {\n if (isQuotaExceeded(cause)) throw new ArenaGrowthQuotaError(cause);\n throw cause;\n }\n }\n }\n\n const reused = extents.filter((extentId) => extentId < totalBefore || extentId < highWaterBefore);\n if (reused.length === 0) return;\n const zeros = new Uint8Array(Math.min(this.#store.state.extentSize, 64 * 1024));\n for (const extentId of reused) {\n let within = 0;\n while (within < this.#store.state.extentSize) {\n const count = Math.min(zeros.byteLength, this.#store.state.extentSize - within);\n this.#arenaDirty = true;\n this.#writeArenaExact(\n arenaByteOffset(extentId, this.#store.state.extentSize, within),\n zeros.subarray(0, count),\n \"arena.allocation.zero\",\n );\n this.#recordArenaWrite(count);\n within += count;\n }\n }\n this.#flushPreparedArena(\"arena.allocation.flush\");\n }\n\n #readLogical(extents: readonly bigint[], position: bigint, target: Uint8Array): void {\n checkedU64(position, \"read position\");\n let completed = 0;\n while (completed < target.byteLength) {\n const logical = checkedAdd(position, BigInt(completed), \"read position\");\n const extentIndex = checkedSafeNumber(logical / BigInt(this.#store.state.extentSize), \"extent index\");\n const extentId = this.#extentAt(extents, [], extentIndex);\n if (extentId === undefined) throw new CorruptStoreError(\"file metadata does not cover its visible data\");\n const within = Number(logical % BigInt(this.#store.state.extentSize));\n const count = Math.min(target.byteLength - completed, this.#store.state.extentSize - within);\n let extentCompleted = 0;\n while (extentCompleted < count) {\n const read = this.#store.handles[\"arena.bin\"].read(\n target.subarray(completed + extentCompleted, completed + count),\n checkedSafeNumber(\n arenaByteOffset(extentId, this.#store.state.extentSize, within + extentCompleted),\n \"arena read offset\",\n ),\n \"arena.read\",\n );\n if (!Number.isSafeInteger(read) || read <= 0 || read > count - extentCompleted) {\n throw new CorruptStoreError(\"arena data ended before the visible file range\");\n }\n extentCompleted += read;\n }\n completed += count;\n }\n }\n\n #writeLogical(\n extents: readonly bigint[],\n position: bigint,\n source: Uint8Array,\n label: string,\n allocated: readonly bigint[] = [],\n ): WriteProgress {\n checkedU64(position, \"write position\");\n let completed = 0;\n while (completed < source.byteLength) {\n const logical = checkedAdd(position, BigInt(completed), \"write position\");\n const extentIndex = checkedSafeNumber(logical / BigInt(this.#store.state.extentSize), \"extent index\");\n const extentId = this.#extentAt(extents, allocated, extentIndex);\n if (extentId === undefined) throw new StoreLimitError(\"planned extents do not cover the write range\");\n const within = Number(logical % BigInt(this.#store.state.extentSize));\n const requested = Math.min(source.byteLength - completed, this.#store.state.extentSize - within);\n try {\n this.#arenaDirty = true;\n const written = this.#writeArena(\n source.subarray(completed, completed + requested),\n checkedSafeNumber(arenaByteOffset(extentId, this.#store.state.extentSize, within), \"arena write offset\"),\n label,\n );\n if (!Number.isSafeInteger(written) || written <= 0 || written > requested) {\n throw new PortWriteError(label);\n }\n this.#recordArenaWrite(written);\n completed += written;\n } catch (error) {\n return { bytes: completed, error };\n }\n }\n return { bytes: completed };\n }\n\n #zeroLogical(\n extents: readonly bigint[],\n position: bigint,\n length: bigint,\n arenaSizeBefore: number,\n allocated: readonly bigint[] = [],\n ): boolean {\n checkedU64(position, \"zero position\");\n checkedU64(length, \"zero length\");\n const zeros = new Uint8Array(64 * 1024);\n const previousEnd = BigInt(arenaSizeBefore);\n let completed = 0n;\n let touchedExisting = false;\n while (completed < length) {\n const logical = checkedAdd(position, completed, \"zero position\");\n const extentIndex = checkedSafeNumber(logical / BigInt(this.#store.state.extentSize), \"extent index\");\n const extentId = this.#extentAt(extents, allocated, extentIndex);\n if (extentId === undefined) throw new StoreLimitError(\"planned extents do not cover the zero range\");\n const within = Number(logical % BigInt(this.#store.state.extentSize));\n const remainingInExtent = this.#store.state.extentSize - within;\n const count = Math.min(\n zeros.byteLength,\n remainingInExtent,\n checkedSafeNumber(length - completed, \"remaining zero length\"),\n );\n const physical = arenaByteOffset(extentId, this.#store.state.extentSize, within);\n if (physical < previousEnd) {\n const existingCount = Math.min(count, checkedSafeNumber(previousEnd - physical, \"existing zero length\"));\n this.#arenaDirty = true;\n this.#writeArenaExact(physical, zeros.subarray(0, existingCount), \"arena.gap-zero.write\");\n this.#recordArenaWrite(existingCount);\n touchedExisting = true;\n }\n completed += BigInt(count);\n }\n return touchedExisting;\n }\n\n #extentAt(head: readonly bigint[], tail: readonly bigint[], index: number): bigint | undefined {\n return index < head.length ? head[index] : tail[index - head.length];\n }\n\n #planLinkedWrite(\n inode: FileInode,\n start: bigint,\n requestedLength: number,\n nowMs: bigint,\n ): {\n length: number;\n plan: ReturnType<typeof planResizeFile> | undefined;\n preparedCommit: PreparedCommit | undefined;\n } {\n const attempt = (\n length: number,\n ): { plan: ReturnType<typeof planResizeFile>; preparedCommit: PreparedCommit } | undefined => {\n const end = checkedAdd(start, BigInt(length), \"write end\");\n if (end <= inode.size) return undefined;\n const plan = planResizeFileForInode(this.#store.state, inode, end, nowMs, \"write\");\n return { plan, preparedCommit: this.#preflightCommit(plan.record) };\n };\n try {\n const admitted = attempt(requestedLength);\n return {\n length: requestedLength,\n plan: admitted?.plan,\n preparedCommit: admitted?.preparedCommit,\n };\n } catch (cause) {\n if (!(cause instanceof StoreLimitError)) throw cause;\n let low = 0;\n let high = requestedLength - 1;\n let admitted = 0;\n let admittedPlan: ReturnType<typeof planResizeFile> | undefined;\n let admittedCommit: PreparedCommit | undefined;\n while (low <= high) {\n const candidate = low + Math.floor((high - low) / 2);\n try {\n const candidatePlan = attempt(candidate);\n admitted = candidate;\n admittedPlan = candidatePlan?.plan;\n admittedCommit = candidatePlan?.preparedCommit;\n low = candidate + 1;\n } catch (candidateCause) {\n if (!(candidateCause instanceof StoreLimitError)) throw candidateCause;\n high = candidate - 1;\n }\n }\n if (admitted === 0) throw cause;\n return { length: admitted, plan: admittedPlan, preparedCommit: admittedCommit };\n }\n }\n\n #writeOrphan(descriptor: Descriptor, source: Uint8Array, position: bigint | undefined, nowMs: bigint): number {\n const orphan = descriptor.orphan!;\n const start = descriptor.append ? orphan.size : (position ?? descriptor.offset);\n if (start < 0n) throw new FsError(\"EINVAL\", \"write position is negative\");\n if (source.byteLength === 0) return 0;\n const buildPlan = () => {\n const admitted = this.#planOrphanWrite(orphan, start, source.byteLength);\n return {\n admitted,\n allocated:\n admitted.reservation === undefined\n ? []\n : expandExtentRuns(admitted.reservation.record.extents, MAX_EXTENTS_PER_INODE),\n arenaSizeBefore: this.#arenaSizeChecked(\"arena.size.before-orphan-extension\"),\n };\n };\n const prepared = this.#prepareAllocationWithQuotaRetry(buildPlan(), buildPlan);\n const { admitted, allocated, arenaSizeBefore } = prepared;\n if (admitted.reservation !== undefined) {\n this.#commit(admitted.reservation.record);\n orphan.extents.push(...allocated);\n }\n if (start > orphan.size) {\n const touchedExisting = this.#zeroLogical(orphan.extents, orphan.size, start - orphan.size, arenaSizeBefore);\n if (touchedExisting) this.#flushPreparedArena(\"arena.gap-zero.flush\");\n }\n const progress = this.#writeLogical(orphan.extents, start, source.subarray(0, admitted.length), \"arena.write\");\n if (progress.bytes === 0) this.#failStore(progress.error);\n const completedEnd = checkedAdd(start, BigInt(progress.bytes), \"completed orphan write end\");\n if (completedEnd > orphan.size) orphan.size = completedEnd;\n orphan.mtimeMs = nowMs;\n orphan.ctimeMs = nowMs;\n if (position === undefined) descriptor.offset = completedEnd;\n return progress.bytes;\n }\n\n #planOrphanWrite(\n orphan: OrphanRecord,\n start: bigint,\n requestedLength: number,\n ): { length: number; reservation: ReturnType<typeof planReserveQuarantine> | undefined } {\n const attempt = (length: number): ReturnType<typeof planReserveQuarantine> | undefined => {\n const end = checkedAdd(start, BigInt(length), \"orphan write end\");\n const required = this.#extentCount(end);\n const additional = Math.max(0, required - orphan.extents.length);\n if (additional === 0) return undefined;\n const reservation = planReserveQuarantine(this.#store.state, additional);\n this.#preflightCommit(reservation.record);\n return reservation;\n };\n try {\n return { length: requestedLength, reservation: attempt(requestedLength) };\n } catch (cause) {\n if (!(cause instanceof StoreLimitError)) throw cause;\n let low = 0;\n let high = requestedLength - 1;\n let admitted = 0;\n let reservation: ReturnType<typeof planReserveQuarantine> | undefined;\n while (low <= high) {\n const candidate = low + Math.floor((high - low) / 2);\n try {\n const candidateReservation = attempt(candidate);\n admitted = candidate;\n reservation = candidateReservation;\n low = candidate + 1;\n } catch (candidateCause) {\n if (!(candidateCause instanceof StoreLimitError)) throw candidateCause;\n high = candidate - 1;\n }\n }\n if (admitted === 0) throw cause;\n return { length: admitted, reservation };\n }\n }\n\n #extentCount(size: bigint): number {\n checkedU64(size, \"file size\");\n if (size === 0n) return 0;\n const count = (size + BigInt(this.#store.state.extentSize) - 1n) / BigInt(this.#store.state.extentSize);\n const result = checkedSafeNumber(count, \"file extent count\");\n if (result > MAX_EXTENTS_PER_INODE) {\n throw new StoreLimitError(`file extent count exceeds ${MAX_EXTENTS_PER_INODE}`);\n }\n return result;\n }\n\n #parseFlags(flags: string): ParsedFlags {\n const parsed: Record<string, ParsedFlags> = {\n r: { readable: true, writable: false, create: false, exclusive: false, truncate: false, append: false },\n \"r+\": { readable: true, writable: true, create: false, exclusive: false, truncate: false, append: false },\n w: { readable: false, writable: true, create: true, exclusive: false, truncate: true, append: false },\n \"w+\": { readable: true, writable: true, create: true, exclusive: false, truncate: true, append: false },\n wx: { readable: false, writable: true, create: true, exclusive: true, truncate: true, append: false },\n \"wx+\": { readable: true, writable: true, create: true, exclusive: true, truncate: true, append: false },\n a: { readable: false, writable: true, create: true, exclusive: false, truncate: false, append: true },\n \"a+\": { readable: true, writable: true, create: true, exclusive: false, truncate: false, append: true },\n ax: { readable: false, writable: true, create: true, exclusive: true, truncate: false, append: true },\n \"ax+\": { readable: true, writable: true, create: true, exclusive: true, truncate: false, append: true },\n };\n const result = parsed[flags];\n if (result === undefined) throw new FsError(\"EINVAL\", `unsupported open flags: ${flags}`);\n return result;\n }\n\n #validateEncoding(encoding: string, path: string): \"utf8\" {\n if (encoding !== \"utf8\" && encoding !== \"utf-8\") {\n throw new FsError(\"EINVAL\", `unsupported writeFile encoding: ${encoding}`, { operation: \"writeFile\", path });\n }\n return \"utf8\";\n }\n\n #flushPreparedArena(label: string): void {\n this.#flush(this.#store.handles[\"arena.bin\"], label, \"zeroBarrier\");\n this.#arenaDirty = false;\n this.#arenaDirtyBytesSinceFlush = 0;\n }\n\n #recordArenaWrite(bytes: number): void {\n if (!Number.isSafeInteger(bytes) || bytes < 0) throw new TypeError(\"arena dirty byte count is invalid\");\n this.#arenaDirtyBytesSinceFlush = Math.min(Number.MAX_SAFE_INTEGER, this.#arenaDirtyBytesSinceFlush + bytes);\n }\n\n #arenaSizeChecked(label: string): number {\n if (this.#arenaSize !== undefined) return this.#arenaSize;\n const size = this.#store.handles[\"arena.bin\"].getSize(label);\n if (!Number.isSafeInteger(size) || size < 0) throw new Error(`${label} returned an invalid arena size`);\n this.#arenaSize = size;\n return size;\n }\n\n #writeArena(source: Uint8Array, at: number, label: string): number {\n const sizeBefore = this.#arenaSize;\n this.#arenaSize = undefined;\n const written = this.#store.handles[\"arena.bin\"].write(source, at, label);\n if (sizeBefore !== undefined && Number.isSafeInteger(written) && written >= 0 && written <= source.byteLength) {\n const end = at + written;\n if (!Number.isSafeInteger(end)) return written;\n this.#arenaSize = Math.max(sizeBefore, end);\n }\n return written;\n }\n\n #writeArenaExact(at: bigint, source: Uint8Array, label: string): void {\n const sizeBefore = this.#arenaSize;\n this.#arenaSize = undefined;\n writeExact(this.#store.handles[\"arena.bin\"], at, source, label);\n if (sizeBefore !== undefined) {\n this.#arenaSize = Math.max(\n sizeBefore,\n checkedSafeNumber(checkedAdd(at, BigInt(source.byteLength), \"arena write end\"), \"arena write end\"),\n );\n }\n }\n\n #truncateArena(size: bigint, label: string): void {\n this.#arenaSize = undefined;\n truncateChecked(this.#store.handles[\"arena.bin\"], size, label);\n this.#arenaSize = checkedSafeNumber(size, \"arena truncate size\");\n }\n\n #flush(handle: RepackedFileHandle, label: string, kind: FlushKind): void {\n this.#flushes[kind] += 1;\n handle.flush(label);\n }\n\n #prepareAllocationWithQuotaRetry<T extends { allocated: readonly bigint[] }>(initial: T, retry: () => T): T {\n try {\n this.#prepareAllocated(initial.allocated);\n return initial;\n } catch (cause) {\n if (!(cause instanceof ArenaGrowthQuotaError)) throw cause;\n this.repack(\"quota\");\n this.repack(\"quota\");\n const retried = retry();\n try {\n this.#prepareAllocated(retried.allocated);\n } catch (retryCause) {\n if (retryCause instanceof ArenaGrowthQuotaError) throw retryCause.cause;\n throw retryCause;\n }\n return retried;\n }\n }\n\n #descriptor(fd: number): Descriptor {\n if (!Number.isSafeInteger(fd)) throw new FsError(\"EBADF\", \"descriptor is invalid\");\n const descriptor = this.#descriptors.get(fd);\n if (descriptor === undefined) throw new FsError(\"EBADF\", \"descriptor is invalid\");\n return descriptor;\n }\n\n /** Every path entering the store is resolved here exactly once; planners then see no links. */\n #resolve(path: string, follow: boolean): string {\n return resolveLinks(this.#store.state, path, follow);\n }\n\n #linkedFile(inodeId: bigint): FileInode {\n const inode = this.#store.state.inodes.get(inodeId);\n if (inode?.kind !== \"file\") throw new FsError(\"EBADF\", \"descriptor no longer references a file\");\n return inode;\n }\n\n #statValue(inode: Inode | OrphanRecord): RepackedStat {\n const kind = \"kind\" in inode ? inode.kind : \"file\";\n return {\n kind,\n mode: inode.mode,\n size:\n kind === \"file\"\n ? (inode as FileInode | OrphanRecord).size\n : kind === \"symlink\"\n ? BigInt(encodedUtf8Length((inode as SymlinkInode).target))\n : 0n,\n atimeMs: inode.atimeMs,\n mtimeMs: inode.mtimeMs,\n ctimeMs: inode.ctimeMs,\n };\n }\n\n #validateBufferRange(buffer: Uint8Array, offset: number, length: number): void {\n if (\n !Number.isSafeInteger(offset) ||\n !Number.isSafeInteger(length) ||\n offset < 0 ||\n length < 0 ||\n offset + length > buffer.byteLength\n ) {\n throw new FsError(\"EINVAL\", \"buffer range is invalid\");\n }\n }\n\n #preflightCommit(record: TxnRecord): PreparedCommit {\n this.#assertOpen();\n const projection = prepareTxnProjection(this.#store.state, record);\n const deferResize = this.#isDeferrableResize(record);\n const pending = this.#pendingResizeCommit;\n const replacesPendingResize =\n deferResize && pending !== undefined && record.kind === \"resizeFile\" && pending.record.inodeId === record.inodeId;\n const materializedRecord: TxnRecord = replacesPendingResize\n ? {\n ...record,\n allocated: mergeExtentRuns(pending.record.allocated, record.allocated),\n }\n : record;\n const sequence = replacesPendingResize ? pending.sequence : this.#store.nextSequence;\n const frameBytes = txnFrameBytes(materializedRecord);\n const frame = deferResize\n ? undefined\n : encodeTxnFrame({\n generation: this.#store.state.generation,\n sequence,\n record: materializedRecord,\n });\n const projectedLogBytes = replacesPendingResize\n ? this.#store.activeLogBytes - pending.frameBytes + frameBytes\n : this.#store.activeLogBytes + frameBytes;\n if (\n (!replacesPendingResize && this.#store.activeLogFrames >= MAX_ACTIVE_LOG_FRAMES) ||\n projectedLogBytes > MAX_ACTIVE_LOG_BYTES\n ) {\n throw new StoreLimitError(\"active metadata log reached its hard limit\");\n }\n return {\n frame,\n frameBytes,\n projection,\n materializedRecord,\n deferResize,\n replacesPendingResize,\n };\n }\n\n #commit(record: TxnRecord, preparedCommit?: PreparedCommit): void {\n this.#assertOpen();\n const prepared = preparedCommit ?? this.#preflightCommit(record);\n if (prepared.replacesPendingResize) {\n const pending = this.#pendingResizeCommit;\n if (pending === undefined || prepared.materializedRecord.kind !== \"resizeFile\") {\n const cause = new Error(\"pending resize preflight no longer matches live state\");\n this.#poison(cause);\n throw cause;\n }\n try {\n applyTxn(this.#store.state, record, prepared.projection);\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n this.#store.activeLogBytes += prepared.frameBytes - pending.frameBytes;\n this.#pendingResizeCommit = {\n record: prepared.materializedRecord,\n frameBytes: prepared.frameBytes,\n sequence: pending.sequence,\n };\n this.#scheduleRepack();\n return;\n }\n\n this.#materializePendingResize();\n if (prepared.deferResize && prepared.materializedRecord.kind === \"resizeFile\") {\n try {\n applyTxn(this.#store.state, record, prepared.projection);\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n this.#pendingResizeCommit = {\n record: prepared.materializedRecord,\n frameBytes: prepared.frameBytes,\n sequence: this.#store.nextSequence,\n };\n this.#store.activeLogBytes += prepared.frameBytes;\n this.#store.activeLogFrames += 1;\n this.#store.nextSequence += 1n;\n this.#scheduleRepack();\n return;\n }\n\n if (prepared.frame === undefined) {\n const cause = new Error(\"immediate commit has no encoded transaction frame\");\n this.#poison(cause);\n throw cause;\n }\n this.#appendFrame(prepared.frame);\n try {\n applyTxn(this.#store.state, record, prepared.projection);\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n this.#store.activeLogBytes += prepared.frameBytes;\n this.#store.activeLogFrames += 1;\n this.#store.nextSequence += 1n;\n this.#scheduleRepack();\n }\n\n #isDeferrableResize(record: TxnRecord): record is Extract<TxnRecord, { kind: \"resizeFile\" }> {\n if (record.kind !== \"resizeFile\" || record.operation !== \"write\") return false;\n const inode = this.#store.state.inodes.get(record.inodeId);\n return inode?.kind === \"file\" && record.size > inode.size;\n }\n\n #appendFrame(frame: Uint8Array): void {\n const activeName = metadataFileName(this.#store.state.activeMetadataFile);\n try {\n writeExact(this.#store.handles[activeName], this.#store.activeLogEnd, frame, \"metadata.log.append\");\n this.#metadataDirtySinceFlush = true;\n this.#store.activeLogEnd += BigInt(frame.byteLength);\n } catch (cause) {\n this.#failStore(cause);\n }\n }\n\n #materializePendingResize(): void {\n const pending = this.#pendingResizeCommit;\n if (pending === undefined) return;\n let frame: Uint8Array;\n try {\n frame = encodeTxnFrame({\n generation: this.#store.state.generation,\n sequence: pending.sequence,\n record: pending.record,\n });\n if (frame.byteLength !== pending.frameBytes) {\n throw new Error(\"pending resize frame length changed after preflight\");\n }\n } catch (cause) {\n this.#poison(cause);\n throw cause;\n }\n this.#appendFrame(frame);\n this.#pendingResizeCommit = undefined;\n }\n\n #scheduleRepack(): void {\n if (this.#store.activeLogBytes >= SOFT_ACTIVE_LOG_BYTES) {\n this.#pendingRepackReason = \"log-bytes\";\n } else if (this.#store.activeLogFrames >= SOFT_ACTIVE_LOG_FRAMES) {\n this.#pendingRepackReason = \"log-frames\";\n } else if (this.#store.state.basePayloadBytes >= BASE_REPACK_PRESSURE_BYTES) {\n this.#pendingRepackReason = \"writer-limit\";\n } else if (\n this.#store.state.allocator.quarantine.size >= QUARANTINE_PRESSURE_EXTENTS ||\n (this.#store.state.allocator.quarantine.size > 0 && this.#store.state.allocator.available.size === 0)\n ) {\n this.#pendingRepackReason ??= \"quarantine-pressure\";\n }\n }\n\n #dueRepackReason(nowMs: number): RepackReason | null {\n if (this.#pendingRepackReason !== null) return this.#pendingRepackReason;\n if (this.#store.activeLogBytes >= SOFT_ACTIVE_LOG_BYTES) return \"log-bytes\";\n if (this.#store.activeLogFrames >= SOFT_ACTIVE_LOG_FRAMES) return \"log-frames\";\n if (this.#store.state.basePayloadBytes >= BASE_REPACK_PRESSURE_BYTES) {\n return \"writer-limit\";\n }\n return this.#store.activeLogFrames > 0 && nowMs - this.#lastRepackAtMs >= REPACK_INTERVAL_MS ? \"time\" : null;\n }\n\n #assertOpen(): void {\n if (this.#status === \"failed\") throw new StoreFailedError(this.#failure);\n if (this.#status === \"closed\") throw new StoreClosedError();\n }\n\n #poison(cause: unknown): void {\n if (this.#status === \"open\") {\n this.#status = \"failed\";\n this.#failure = cause;\n }\n }\n\n /**\n * The poison rule for a platform write the store could not complete: an arena write that made no\n * progress (the platform threw before confirming a byte, so what the range now holds is unknown) or a\n * metadata-log append (ambiguous by construction). Continuing would build on bytes nobody can vouch\n * for, so the store poisons itself, and this call — like every later one until close — throws the\n * coded `StoreFailedError` (`code` EIO) carrying the platform's error as its cause. The code is what\n * lets an engine's errno bridge report an I/O error instead of an exception it cannot map.\n */\n #failStore(cause: unknown): never {\n this.#poison(cause);\n throw new StoreFailedError(this.#failure);\n }\n}\n",
15
15
  "import { BaseFilesystem } from \"../fs/base-filesystem\";\nimport type { FilesystemDescription, FsStats } from \"../fs/base-filesystem\";\nimport { DurabilityModeMismatchError, StoreLimitError } from \"./core/errors\";\nimport type { RepackedPort } from \"./core/port\";\nimport { RepackedVfs } from \"./core/repacked-vfs\";\nimport type { RepackedStat } from \"./core/repacked-vfs\";\n\n/** Physical durability selected once for the lifetime of a store `createOpfsPgwasm` opens. */\nexport type RepackedDurability = \"relaxed\" | \"strict\";\n\nexport interface RepackedFilesystemOptions {\n /** Creation extent size: 8 KiB–16 MiB in 8 KiB steps. Defaults to 64 KiB. */\n readonly extentSize?: number;\n /** Physical durability for this instance. Defaults to `\"relaxed\"`. */\n readonly durability?: RepackedDurability;\n}\n\nconst DESCRIPTION: FilesystemDescription = Object.freeze({ name: \"opfs-repacked\", persistent: true });\n\n/**\n * The pgwasm filesystem adapter owned by `createOpfsPgwasm`.\n *\n * Direct construction is unsupported. The factory retains this adapter so it\n * can close all four handles when host initialization or shutdown fails.\n */\nexport abstract class OpfsRepackedFS extends BaseFilesystem {\n readonly #vfs: RepackedVfs;\n readonly #durability: RepackedDurability;\n\n protected constructor(vfs: RepackedVfs, durability: RepackedDurability) {\n super();\n this.#vfs = vfs;\n this.#durability = durability;\n }\n\n /** An OPFS-repacked store: its data directory outlives the page. */\n override get description(): FilesystemDescription {\n return DESCRIPTION;\n }\n\n override async initialSyncFs(): Promise<void> {\n this.#vfs.assertHealthy();\n }\n\n override async syncToFs(relaxedDurability = false): Promise<void> {\n this.#vfs.assertHealthy();\n if (relaxedDurability) this.#vfs.fail(new DurabilityModeMismatchError());\n this.#vfs.runScheduledRepack();\n if (this.#durability === \"strict\") this.#vfs.strictSync();\n }\n\n /** Stabilize every preceding data and metadata operation in strict order. */\n strictSync(): void {\n this.#vfs.strictSync();\n }\n\n /** @internal Factory lifecycle cleanup after host initialization fails. */\n override async cleanupFailedInit(): Promise<void> {\n this.#vfs.cleanupFailedInit();\n }\n\n override async closeFs(): Promise<void> {\n this.#vfs.close();\n }\n\n chmod(path: string, mode: number): void {\n this.#vfs.chmod(hostPath(path), mode, nowMs());\n }\n\n close(fd: number): void {\n this.#vfs.close(fd);\n }\n\n fstat(fd: number): FsStats {\n return toFsStats(this.#vfs.fstat(fd));\n }\n\n lstat(path: string): FsStats {\n return toFsStats(this.#vfs.lstat(hostPath(path)));\n }\n\n mkdir(path: string, options?: { recursive?: boolean; mode?: number }): void {\n this.#vfs.mkdir(hostPath(path), {\n ...(options?.recursive === undefined ? {} : { recursive: options.recursive }),\n ...(options?.mode === undefined ? {} : { mode: options.mode }),\n nowMs: nowMs(),\n });\n }\n\n open(path: string, flags = \"r+\", mode = 0o100666): number {\n return this.#vfs.open(hostPath(path), flags, mode, nowMs());\n }\n\n readdir(path: string): string[] {\n return this.#vfs.readdir(hostPath(path));\n }\n\n read(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): number {\n return this.#vfs.read(fd, buffer, offset, length, toFileOffset(position));\n }\n\n rename(oldPath: string, newPath: string): void {\n this.#vfs.rename(hostPath(oldPath), hostPath(newPath), nowMs());\n }\n\n rmdir(path: string): void {\n this.#vfs.rmdir(hostPath(path), nowMs());\n }\n\n truncate(path: string, length: number): void {\n this.#vfs.truncate(hostPath(path), toFileOffset(length), nowMs());\n }\n\n unlink(path: string): void {\n this.#vfs.unlink(hostPath(path), nowMs());\n }\n\n utimes(path: string, atime: number, mtime: number): void {\n this.#vfs.utimes(hostPath(path), toTimestamp(atime), toTimestamp(mtime), nowMs());\n }\n\n writeFile(\n path: string,\n data: string | Uint8Array,\n options?: { encoding?: string; mode?: number; flag?: string },\n ): void {\n this.#vfs.writeFile(hostPath(path), data, {\n ...(options?.encoding === undefined ? {} : { encoding: options.encoding }),\n ...(options?.mode === undefined ? {} : { mode: options.mode }),\n ...(options?.flag === undefined ? {} : { flag: options.flag }),\n nowMs: nowMs(),\n });\n }\n\n write(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): number {\n if (buffer instanceof Uint8Array) {\n return this.#vfs.write(fd, buffer, offset, length, toFileOffset(position), nowMs());\n }\n const source = new Uint8Array(buffer as unknown as ArrayBuffer, offset, length);\n return this.#vfs.write(fd, source, 0, source.byteLength, toFileOffset(position), nowMs());\n }\n}\n\nclass ConcreteOpfsRepackedFS extends OpfsRepackedFS {\n constructor(vfs: RepackedVfs, durability: RepackedDurability) {\n super(vfs, durability);\n }\n}\n\nexport async function openOpfsRepackedFsForPort(\n port: RepackedPort,\n options: RepackedFilesystemOptions = {},\n): Promise<OpfsRepackedFS> {\n const durability = options.durability ?? \"relaxed\";\n if (durability !== \"relaxed\" && durability !== \"strict\") {\n throw new TypeError(`unsupported OPFS repacked durability: ${String(durability)}`);\n }\n const vfs = await RepackedVfs.open(port, {\n ...(options.extentSize === undefined ? {} : { extentSize: options.extentSize }),\n });\n return new ConcreteOpfsRepackedFS(vfs, durability);\n}\n\nfunction nowMs(): bigint {\n return BigInt(Date.now());\n}\n\nfunction hostPath(path: string): string {\n return path === \"\" ? \"/\" : path;\n}\n\nfunction toFileOffset(value: number): bigint {\n if (!Number.isSafeInteger(value) || value < 0) throw new TypeError(\"file offset is not a non-negative safe integer\");\n return BigInt(value);\n}\n\nfunction toTimestamp(value: number): bigint {\n // Emscripten's utime path can pass fractional milliseconds (µs-precision\n // utimensat converted to ms); floor instead of rejecting the syscall.\n const floored = Math.floor(value);\n if (!Number.isSafeInteger(floored) || floored < 0) {\n throw new TypeError(\"timestamp is not a non-negative finite millisecond value\");\n }\n return BigInt(floored);\n}\n\nfunction toFsStats(stat: RepackedStat): FsStats {\n const size = toSafeNumber(stat.size, \"file size\");\n const blksize = 4096;\n return {\n dev: 0,\n ino: 0,\n mode: stat.mode,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n size,\n blksize,\n blocks: Math.ceil(size / blksize),\n atime: toSafeNumber(stat.atimeMs, \"access time\"),\n mtime: toSafeNumber(stat.mtimeMs, \"modification time\"),\n ctime: toSafeNumber(stat.ctimeMs, \"change time\"),\n };\n}\n\nfunction toSafeNumber(value: bigint, label: string): number {\n if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new StoreLimitError(`${label} exceeds safe integer range`);\n return Number(value);\n}\n",
16
16
  "import type { PostgresBuild } from \"../build/seam\";\nimport { registerStrictSync, strictSyncOf } from \"../core/internals\";\nimport { createPgwasm } from \"../create\";\nimport { UnsupportedFeatureError } from \"../errors\";\nimport type { Extensions, Pgwasm, PgwasmOptions, PgwasmWithExtensions } from \"../interface\";\nimport { OpfsRepackedPort } from \"./opfs-port\";\nimport type { OpfsDirectoryHandle } from \"./opfs-port\";\nimport { openOpfsRepackedFsForPort } from \"./opfs-repacked-fs\";\nimport type { RepackedFilesystemOptions } from \"./opfs-repacked-fs\";\n\n/** The database options `createOpfsPgwasm` passes through: all but the ones the store owns. */\nexport type OpfsPgwasmHostOptions<E extends Extensions = Record<never, never>> = Omit<\n PgwasmOptions<E>,\n \"build\" | \"dataDir\" | \"fs\" | \"relaxedDurability\"\n>;\n\nexport interface CreateOpfsPgwasmOptions<\n E extends Extensions = Record<never, never>,\n> extends RepackedFilesystemOptions {\n /** The Postgres build to run, e.g. `cBuild` from `@pgxsinkit/pgwasm-c`. */\n readonly build: PostgresBuild;\n /** Dedicated directory owned in full by this store. */\n readonly directory: OpfsDirectoryHandle;\n /** Database options other than the store-owned `build`, `dataDir`, `fs` and `relaxedDurability`. */\n readonly pgwasm?: OpfsPgwasmHostOptions<E>;\n /**\n * Optional progress callback for the two long, otherwise-invisible steps of an OPFS-repacked create.\n * Called once per phase, in order, and only on the success path:\n *\n * - `\"store-opened\"` — the store's sync access handles are acquired and the repacked filesystem is open.\n * Everything before this is handle acquisition, which is where a create that never returns stalls.\n * - `\"pgwasm-ready\"` — the database's own boot (WASM instantiation, initdb or catalog open) has completed.\n *\n * Diagnosability only: it carries no policy, must not throw, and a create's outcome never depends on it.\n * The host uses it to stamp a boot rail, so a stalled create is attributable to a phase rather than\n * silent.\n */\n readonly onPhase?: (phase: OpfsCreatePhase) => void;\n}\n\n/** The create phases {@link CreateOpfsPgwasmOptions.onPhase} reports, in the order they occur. */\nexport type OpfsCreatePhase = \"store-opened\" | \"pgwasm-ready\";\n\n/**\n * A database on an OPFS-repacked store: a plain pgwasm database. Its one strict operation, reserved for\n * the sync layer above the store, is {@link strictSync}.\n */\nexport type OpfsPgwasm<E extends Extensions = Record<never, never>> = PgwasmWithExtensions<E>;\n\n/**\n * Construct the only supported OPFS-repacked/pgwasm pairing.\n *\n * pgwasm always awaits the filesystem sync (`relaxedDurability: false`). Physical durability is selected\n * once, here, by the store's `durability` option and is never delegated to the database option. A\n * strict sync completes successful database initialization before return. Closing the database closes\n * the store: its build releases the filesystem (`closeFs`) on every close, a failed one included.\n */\nexport async function createOpfsPgwasm<E extends Extensions = Record<never, never>>(\n options: CreateOpfsPgwasmOptions<E>,\n): Promise<OpfsPgwasm<E>> {\n assertHostOptions(options.pgwasm);\n const store = await openOpfsRepackedFsForPort(new OpfsRepackedPort(options.directory), filesystemOptions(options));\n options.onPhase?.(\"store-opened\");\n\n let pg: OpfsPgwasm<E> | undefined;\n try {\n pg = await createPgwasm<E>({\n ...options.pgwasm,\n build: options.build,\n fs: store,\n relaxedDurability: false,\n });\n registerStrictSync(pg, () => store.strictSync());\n options.onPhase?.(\"pgwasm-ready\");\n store.strictSync();\n return pg;\n } catch (cause) {\n try {\n // The database is unusable once its first strict sync failed: close it, which releases the store.\n await pg?.close();\n } catch {\n // Preserve the first cause.\n }\n try {\n await store.cleanupFailedInit();\n } catch {\n // Initialization is already unusable. Preserve its first cause after\n // cleanup has attempted every owned handle.\n }\n throw cause;\n }\n}\n\n/**\n * Stabilize every preceding data and metadata operation of a database on an OPFS-repacked store, in\n * strict order, serialized against its queries. Throws {@link UnsupportedFeatureError} for a database\n * that `createOpfsPgwasm` did not create.\n */\nexport async function strictSync(pg: Pgwasm): Promise<void> {\n const sync = strictSyncOf(pg);\n if (sync === undefined) {\n throw new UnsupportedFeatureError(\n \"strictSync needs a database on an OPFS-repacked store (created by createOpfsPgwasm).\",\n );\n }\n await pg.runExclusive(async () => {\n sync();\n });\n}\n\nfunction filesystemOptions(options: CreateOpfsPgwasmOptions<Extensions>): RepackedFilesystemOptions {\n return {\n ...(options.extentSize === undefined ? {} : { extentSize: options.extentSize }),\n ...(options.durability === undefined ? {} : { durability: options.durability }),\n };\n}\n\nfunction assertHostOptions(options: object | undefined): void {\n if (options === undefined) return;\n for (const reserved of [\"build\", \"dataDir\", \"fs\", \"relaxedDurability\"] as const) {\n if (reserved in options) {\n throw new TypeError(`pgwasm.${reserved} is owned by createOpfsPgwasm`);\n }\n }\n}\n",
17
17
  "/**\n * An in-memory `RepackedPort` with the same exclusive-ownership, volatile/durable, and fault-injection\n * behaviour as the real OPFS port. It is production source, not test support: the sync broker\n * (`../broker/`) and any engine-agnostic host need a port that works off the main thread and outside a\n * browser, and every store-level test in the repo already diffs real behaviour against it.\n */\nimport { StoreOwnedError } from \"./errors\";\nimport { OWNED_FILE_NAMES } from \"./port\";\nimport type { OwnedFileName, RepackedFileHandle, RepackedPort, RepackedPortEntry } from \"./port\";\n\nexport type MemoryOperation = \"enumerate\" | \"acquire\" | \"getSize\" | \"read\" | \"write\" | \"truncate\" | \"flush\";\ntype FaultOutcome = \"short\" | \"throw-before\" | \"throw-after\" | \"quota\";\n\nexport interface MemoryFault {\n operation: MemoryOperation;\n outcome: FaultOutcome;\n file?: string;\n label?: string;\n bytes?: number;\n occurrence?: number;\n}\n\ninterface WriteEffect {\n id: number;\n file: OwnedFileName;\n kind: \"write\";\n at: number;\n data: Uint8Array;\n}\n\ninterface TruncateEffect {\n id: number;\n file: OwnedFileName;\n kind: \"truncate\";\n size: number;\n}\n\ntype MemoryEffect = WriteEffect | TruncateEffect;\nexport type TerminationDecision = \"absent\" | \"full\" | number;\n\nexport interface MemoryEffectSummary {\n id: number;\n file: OwnedFileName;\n operation: \"write\" | \"truncate\";\n bytes: number;\n}\n\nexport interface MemoryOperationSummary {\n readonly operation: MemoryOperation;\n readonly file: OwnedFileName | undefined;\n readonly label: string;\n /**\n * Bytes this operation copied into the DURABLE image. Recorded on `flush` only, where it is the\n * deterministic stand-in for flush cost: a flush must copy the bytes written since the previous\n * flush, never the size of the file. Absent on every other operation.\n */\n readonly copiedBytes?: number;\n}\n\n/** The private, still-writable form of a record: `handleFlush` fills `copiedBytes` in after the copy. */\ninterface MemoryOperationRecord {\n readonly operation: MemoryOperation;\n readonly file: OwnedFileName | undefined;\n readonly label: string;\n copiedBytes?: number;\n}\n\nfunction clone(bytes: Uint8Array): Uint8Array {\n return bytes.slice();\n}\n\n/**\n * Replay a write onto a MATERIALIZED copy, for `terminate()`. Pure, and deliberately so: the\n * termination model rebuilds a fresh image from the durable bytes plus the effect log, and nothing in\n * it may alias the live volatile buffer.\n */\nfunction applyWrite(current: Uint8Array, at: number, source: Uint8Array): Uint8Array {\n const required = at + source.byteLength;\n const next = required <= current.byteLength ? clone(current) : new Uint8Array(required);\n if (next.byteLength > current.byteLength) next.set(current);\n next.set(source, at);\n return next;\n}\n\n/** The `terminate()` twin of `applyWrite`, and pure for the same reason. */\nfunction applyTruncate(current: Uint8Array, size: number): Uint8Array {\n if (size === current.byteLength) return clone(current);\n const next = new Uint8Array(size);\n next.set(current.subarray(0, Math.min(size, current.byteLength)));\n return next;\n}\n\n/**\n * Resize a LIVE image — the volatile file or the durable one — keeping the bytes it already holds and\n * reusing spare capacity.\n *\n * A live image is always `new Uint8Array(buffer, 0, length)`, so its backing buffer may be larger\n * than the file and `bytes.buffer.byteLength` is its capacity. That separation is what keeps this port\n * usable at real store sizes: replacing the whole array on every write and every truncate — which is\n * what the pure `apply*` helpers above do — makes each operation cost the size of the FILE rather than\n * the size of the operation, so an in-memory store grows QUADRATICALLY in the bytes written. Seeding a\n * 41 MB Postgres datadir (1,477 files, ~3,000 arena writes and growth truncates) took 98 seconds that\n * way and copied roughly 80 GB. Nothing needed those copies: the effect log holds the CALLER's source\n * bytes rather than the file's, `durableBytes()` clones on the way out, and the two images never share\n * a buffer — so both are safe to mutate in place, and the same seed takes about a second.\n *\n * Growth doubles, and any newly exposed region is zeroed: capacity left behind by an earlier truncate\n * still holds that truncated file's bytes, and a hole must read as zeros.\n */\nfunction resizeImage(current: Uint8Array, size: number): Uint8Array {\n if (size <= current.byteLength) return new Uint8Array(current.buffer, 0, size);\n if (size <= current.buffer.byteLength) {\n const grown = new Uint8Array(current.buffer, 0, size);\n grown.fill(0, current.byteLength, size);\n return grown;\n }\n const capacity = Math.max(size, current.buffer.byteLength * 2, 64);\n const grown = new Uint8Array(new ArrayBuffer(capacity), 0, size);\n grown.set(current);\n return grown;\n}\n\nfunction isOwnedFileName(name: string): name is OwnedFileName {\n return (OWNED_FILE_NAMES as readonly string[]).includes(name);\n}\n\nclass MemoryHandle implements RepackedFileHandle {\n readonly name: OwnedFileName;\n readonly #port: MemoryRepackedPort;\n readonly #epoch: number;\n #closed = false;\n\n constructor(port: MemoryRepackedPort, name: OwnedFileName, epoch: number) {\n this.#port = port;\n this.name = name;\n this.#epoch = epoch;\n }\n\n getSize(label: string): number {\n this.#assertOpen();\n return this.#port.handleGetSize(this.name, label);\n }\n\n read(target: Uint8Array, at: number, label: string): number {\n this.#assertOpen();\n return this.#port.handleRead(this.name, target, at, label);\n }\n\n write(source: Uint8Array, at: number, label: string): number {\n this.#assertOpen();\n return this.#port.handleWrite(this.name, source, at, label);\n }\n\n truncate(size: number, label: string): void {\n this.#assertOpen();\n this.#port.handleTruncate(this.name, size, label);\n }\n\n flush(label: string): void {\n this.#assertOpen();\n this.#port.handleFlush(this.name, label);\n }\n\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n if (this.#epoch === this.#port.epoch) this.#port.handleClose(this.name);\n }\n\n #assertOpen(): void {\n if (this.#closed || this.#epoch !== this.#port.epoch) {\n throw new Error(`memory handle ${this.name} is closed`);\n }\n }\n}\n\nexport class MemoryRepackedPort implements RepackedPort {\n readonly #durable = new Map<OwnedFileName, Uint8Array>();\n readonly #volatile = new Map<OwnedFileName, Uint8Array>();\n readonly #entryKinds = new Map<string, \"file\" | \"directory\">();\n readonly #open = new Set<OwnedFileName>();\n readonly #faults: MemoryFault[] = [];\n readonly #operations: MemoryOperationRecord[] = [];\n #effects: MemoryEffect[] = [];\n #nextEffectId = 1;\n #epoch = 1;\n\n get epoch(): number {\n return this.#epoch;\n }\n\n async enumerate(label: string): Promise<readonly RepackedPortEntry[]> {\n this.#recordOperation(\"enumerate\", undefined, label);\n const fault = this.#takeFault(\"enumerate\", undefined, label);\n if (fault !== undefined) throw new Error(`injected enumerate failure ${fault.outcome}`);\n return [...this.#entryKinds]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([name, kind]) => ({\n name,\n kind,\n }));\n }\n\n async acquire(name: OwnedFileName, label: string): Promise<RepackedFileHandle> {\n this.#recordOperation(\"acquire\", name, label);\n const fault = this.#takeFault(\"acquire\", name, label);\n if (fault?.outcome === \"throw-before\") throw new Error(\"injected acquire failure before effect\");\n if (this.#open.has(name)) throw new StoreOwnedError();\n if (this.#entryKinds.get(name) === \"directory\") throw new Error(`memory entry ${name} is not a file`);\n if (!this.#volatile.has(name)) {\n this.#volatile.set(name, new Uint8Array());\n this.#durable.set(name, new Uint8Array());\n this.#entryKinds.set(name, \"file\");\n }\n if (fault !== undefined) throw new Error(`injected acquire failure ${fault.outcome}`);\n this.#open.add(name);\n return new MemoryHandle(this, name, this.#epoch);\n }\n\n injectEntry(name: string, kind: \"file\" | \"directory\"): void {\n if (isOwnedFileName(name) && this.#open.has(name)) {\n throw new Error(`cannot replace acquired memory entry ${name}`);\n }\n this.#entryKinds.set(name, kind);\n if (isOwnedFileName(name)) {\n // Replacing an owned entry replaces BOTH images, so anything still pending for it describes a\n // file that no longer exists; keeping it would let a later flush or termination replay it onto\n // the replacement and break `durable + pending effects == volatile`.\n this.#effects = this.#effects.filter((effect) => effect.file !== name);\n if (kind === \"file\") {\n this.#volatile.set(name, new Uint8Array());\n this.#durable.set(name, new Uint8Array());\n } else {\n this.#volatile.delete(name);\n this.#durable.delete(name);\n }\n }\n }\n\n injectFault(fault: MemoryFault): void {\n if (fault.outcome === \"quota\" && fault.operation !== \"truncate\") {\n throw new TypeError(\"quota faults are supported only for arena growth truncates\");\n }\n if (fault.bytes !== undefined && (!Number.isSafeInteger(fault.bytes) || fault.bytes < 0)) {\n throw new TypeError(\"fault byte count must be a non-negative safe integer\");\n }\n if (fault.occurrence !== undefined && (!Number.isSafeInteger(fault.occurrence) || fault.occurrence < 0)) {\n throw new TypeError(\"fault occurrence must be a non-negative safe integer\");\n }\n this.#faults.push({ ...fault });\n }\n\n pendingEffects(): readonly MemoryEffectSummary[] {\n return this.#effects.map((effect) => ({\n id: effect.id,\n file: effect.file,\n operation: effect.kind,\n bytes: effect.kind === \"write\" ? effect.data.byteLength : effect.size,\n }));\n }\n\n openHandleCount(): number {\n return this.#open.size;\n }\n\n observedOperations(): readonly MemoryOperationSummary[] {\n return Object.freeze(this.#operations.map((operation) => Object.freeze({ ...operation })));\n }\n\n clearObservedOperations(): void {\n this.#operations.length = 0;\n }\n\n durableBytes(name: OwnedFileName): Uint8Array {\n return clone(this.#durable.get(name) ?? new Uint8Array());\n }\n\n terminate(decisions: Readonly<Record<number, TerminationDecision>> = {}): void {\n const materialized = new Map<OwnedFileName, Uint8Array>();\n for (const [name, bytes] of this.#durable) materialized.set(name, clone(bytes));\n for (const effect of this.#effects) {\n const decision = decisions[effect.id] ?? \"absent\";\n if (decision === \"absent\") continue;\n const current = materialized.get(effect.file) ?? new Uint8Array();\n if (effect.kind === \"truncate\") {\n if (decision !== \"full\") {\n throw new TypeError(\"truncate termination decisions must be absent or full\");\n }\n materialized.set(effect.file, applyTruncate(current, effect.size));\n } else {\n const bytes = decision === \"full\" ? effect.data.byteLength : decision;\n if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > effect.data.byteLength) {\n throw new TypeError(\"write termination prefix is outside the effect\");\n }\n if (bytes > 0) materialized.set(effect.file, applyWrite(current, effect.at, effect.data.subarray(0, bytes)));\n }\n }\n this.#durable.clear();\n this.#volatile.clear();\n for (const [name, bytes] of materialized) {\n this.#durable.set(name, clone(bytes));\n this.#volatile.set(name, clone(bytes));\n }\n this.#effects = [];\n this.#faults.length = 0;\n this.#open.clear();\n this.#epoch += 1;\n }\n\n handleGetSize(name: OwnedFileName, label: string): number {\n this.#recordOperation(\"getSize\", name, label);\n const fault = this.#takeFault(\"getSize\", name, label);\n if (fault !== undefined) throw new Error(`injected getSize failure ${fault.outcome}`);\n return this.#file(name).byteLength;\n }\n\n handleRead(name: OwnedFileName, target: Uint8Array, at: number, label: string): number {\n this.#validateRange(at, target.byteLength);\n this.#recordOperation(\"read\", name, label);\n const fault = this.#takeFault(\"read\", name, label);\n if (fault?.outcome === \"throw-before\" || fault?.outcome === \"throw-after\") {\n throw new Error(`injected read failure ${fault.outcome === \"throw-before\" ? \"before\" : \"after\"} effect`);\n }\n const source = this.#file(name);\n const available = Math.max(0, Math.min(target.byteLength, source.byteLength - at));\n const count = fault?.outcome === \"short\" ? Math.min(available, fault.bytes ?? 0) : available;\n target.set(source.subarray(at, at + count));\n return count;\n }\n\n handleWrite(name: OwnedFileName, source: Uint8Array, at: number, label: string): number {\n this.#validateRange(at, source.byteLength);\n this.#recordOperation(\"write\", name, label);\n const fault = this.#takeFault(\"write\", name, label);\n if (fault?.outcome === \"throw-before\") throw new Error(\"injected write failure before effect\");\n const count =\n fault?.outcome === \"short\" || fault?.outcome === \"throw-after\"\n ? Math.min(source.byteLength, fault.bytes ?? source.byteLength)\n : source.byteLength;\n if (count > 0) this.#recordWrite(name, at, source.subarray(0, count));\n if (fault?.outcome === \"throw-after\") throw new Error(\"injected write failure after effect\");\n return count;\n }\n\n handleTruncate(name: OwnedFileName, size: number, label: string): void {\n this.#validateRange(size, 0);\n this.#recordOperation(\"truncate\", name, label);\n const fault = this.#takeFault(\"truncate\", name, label);\n if (fault?.outcome === \"quota\") throw new DOMException(\"injected arena quota exhaustion\", \"QuotaExceededError\");\n if (fault?.outcome === \"throw-before\") throw new Error(\"injected truncate failure before effect\");\n this.#volatile.set(name, resizeImage(this.#file(name), size));\n this.#effects.push({ id: this.#nextEffectId++, file: name, kind: \"truncate\", size });\n if (fault?.outcome === \"throw-after\") throw new Error(\"injected truncate failure after effect\");\n }\n\n handleFlush(name: OwnedFileName, label: string): void {\n const record = this.#recordOperation(\"flush\", name, label);\n record.copiedBytes = 0;\n const fault = this.#takeFault(\"flush\", name, label);\n // A throw-before flush made nothing durable and left every effect pending, so it copies nothing.\n if (fault?.outcome === \"throw-before\") throw new Error(\"injected flush failure before effect\");\n record.copiedBytes = this.#makeDurable(name);\n if (fault?.outcome === \"throw-after\") throw new Error(\"injected flush failure after effect\");\n }\n\n handleClose(name: OwnedFileName): void {\n this.#open.delete(name);\n }\n\n #file(name: OwnedFileName): Uint8Array {\n const bytes = this.#volatile.get(name);\n if (bytes === undefined) throw new Error(`memory file ${name} was not acquired`);\n return bytes;\n }\n\n #recordWrite(name: OwnedFileName, at: number, source: Uint8Array): void {\n // The effect log owns its own copy: it is replayed against a MATERIALIZED image in `terminate()`,\n // long after the live buffer moved on.\n const data = clone(source);\n const current = this.#file(name);\n const required = at + data.byteLength;\n const target = required > current.byteLength ? resizeImage(current, required) : current;\n target.set(data, at);\n this.#volatile.set(name, target);\n this.#effects.push({ id: this.#nextEffectId++, file: name, kind: \"write\", at, data });\n }\n\n /**\n * Apply this file's pending effects onto the durable image, in order, and drop them. Returns the\n * bytes copied.\n *\n * The old implementation made a file durable by cloning the whole volatile image, so every flush\n * cost the size of the FILE. That is what the broker charges to every committing statement: a guest\n * `fd_sync` becomes a store-wide `strictSync()`, and on a seeded Postgres datadir the arena is tens\n * of MB, which showed up as a flat ~25 ms per writing statement in the browser benchmark. The effect\n * log already IS the dirty set — `durable + pending effects == volatile` for every file, at all\n * times — so replaying it costs the bytes written since the previous flush instead, and reproduces\n * the volatile image byte for byte because both sides take the same steps through `resizeImage`.\n */\n #makeDurable(name: OwnedFileName): number {\n let image = this.#durable.get(name) ?? new Uint8Array();\n const remaining: MemoryEffect[] = [];\n let copied = 0;\n for (const effect of this.#effects) {\n if (effect.file !== name) {\n remaining.push(effect);\n continue;\n }\n if (effect.kind === \"truncate\") {\n const resized = resizeImage(image, effect.size);\n // Growth past the current capacity carries the bytes already held into a new buffer; every\n // other resize is a view onto the same one. A truncate copies nothing of its own.\n if (resized.buffer !== image.buffer) copied += image.byteLength;\n image = resized;\n continue;\n }\n const required = effect.at + effect.data.byteLength;\n if (required > image.byteLength) {\n const grown = resizeImage(image, required);\n if (grown.buffer !== image.buffer) copied += image.byteLength;\n image = grown;\n }\n image.set(effect.data, effect.at);\n copied += effect.data.byteLength;\n }\n this.#durable.set(name, image);\n this.#effects = remaining;\n return copied;\n }\n\n #takeFault(operation: MemoryOperation, file: string | undefined, label: string): MemoryFault | undefined {\n const index = this.#faults.findIndex(\n (fault) =>\n fault.operation === operation &&\n (fault.file === undefined || fault.file === file) &&\n (fault.label === undefined || fault.label === label),\n );\n if (index < 0) return undefined;\n const fault = this.#faults[index]!;\n if ((fault.occurrence ?? 0) > 0) {\n this.#faults[index] = { ...fault, occurrence: fault.occurrence! - 1 };\n return undefined;\n }\n return this.#faults.splice(index, 1)[0];\n }\n\n #recordOperation(operation: MemoryOperation, file: OwnedFileName | undefined, label: string): MemoryOperationRecord {\n const record: MemoryOperationRecord = { operation, file, label };\n this.#operations.push(record);\n return record;\n }\n\n #validateRange(at: number, length: number): void {\n if (!Number.isSafeInteger(at) || !Number.isSafeInteger(length) || at < 0 || length < 0) {\n throw new RangeError(\"memory port range is invalid\");\n }\n if (!Number.isSafeInteger(at + length)) throw new RangeError(\"memory port range exceeds safe integers\");\n }\n}\n",
18
- "/**\n * `MountedRepackedVfs` — one {@link RepackedFileSystem} made of several stores, joined at path\n * prefixes.\n *\n * ## Why\n *\n * A store is a single durable object: four exclusive handles, one arena, one metadata generation.\n * That is exactly right for a datadir and exactly wrong for the parts of a datadir that must NOT be\n * durable — a Postgres temp tablespace, an ephemeral relation, a scratch area whose whole point is\n * that it never reaches the platform. A mount serves one path prefix from a SECOND store, so the\n * durable root and the volatile subtree are one tree to the guest and two stores to the host.\n *\n * ## The shape\n *\n * / -> root store (OPFS: durable)\n * /pgdata/... -> root store\n * /scratch -> mount store (memory: nothing durable)\n * /scratch/anything/... -> mount store, as \"/anything/...\"\n *\n * A mount's prefix is its root: `/scratch/a/b` reaches the mount as `/a/b`, and the prefix itself as\n * `/`. The prefix directory is also created in the ROOT store, so a `readdir` of its parent lists\n * it; every operation AT or BELOW the prefix is answered by the mount, so that root-side directory\n * is a name and nothing more.\n *\n * ## What the composite owns, and what it delegates\n *\n * - **Symlink resolution is the composite's**, because a link is the one thing that can move a path\n * from one store to another: `pg_tblspc/<oid>` lives in the root and points at `/scratch`, and\n * neither store alone can resolve it (the root would resolve it against its own placeholder\n * directory and find nothing there). The fast path is one `resolvePath` call on the store the\n * path already routes to — if that store says the path holds no link, no link exists on it at\n * all, because every entry on the path lives in that store. Only a path that really does traverse\n * a link pays the component-by-component walk.\n * - **Descriptors are the composite's.** Each store numbers its own fds from 3, so the composite\n * hands out its own numbers and remembers which store each belongs to.\n * - **`rename` across a boundary is `EXDEV`**, exactly as it is between two real filesystems: a\n * rename is a metadata move inside one store and cannot span two.\n * - **`strictSync()` skips a mount declared non-durable.** A memory-backed mount has nothing to make\n * durable, and a store-wide sync that walked it would charge the guest for flushes that cannot\n * protect anything. Durability is a property the STORAGE OWNER declares per mount; nothing here\n * infers it from the port.\n * - Everything else is a route plus a delegation.\n */\n\nimport { FS_ERRNO, FsError } from \"./errors\";\nimport { MAX_SYMLINK_HOPS } from \"./limits\";\nimport { parsePath } from \"./path\";\nimport type { RepackReason, RepackedFileSystem, RepackedStat, RepackedVfsMetrics } from \"./repacked-vfs\";\n\n/** One store served at one path prefix. */\nexport interface RepackedMount {\n /** Absolute, canonical, and never `/`: the path the mount's own root appears at. */\n readonly prefix: string;\n readonly vfs: RepackedFileSystem;\n /**\n * Whether a store-wide `strictSync()` reaches this mount. Defaults to `true`. A volatile mount\n * (memory-backed scratch) declares `false`: there is nothing to flush, and pretending otherwise\n * charges every guest `fsync` for it.\n */\n readonly durable?: boolean;\n}\n\nexport interface MountedRepackedVfsOptions {\n /** The store that answers for every path no mount claims. */\n readonly root: RepackedFileSystem;\n readonly mounts: readonly RepackedMount[];\n /** The clock used to create each mount's placeholder directory in the root. */\n readonly nowMs?: () => bigint;\n}\n\ninterface ResolvedMount {\n readonly prefix: string;\n readonly boundary: string;\n readonly vfs: RepackedFileSystem;\n readonly durable: boolean;\n}\n\ninterface Route {\n readonly fs: RepackedFileSystem;\n /** The path as the routed store sees it. */\n readonly path: string;\n /** The mount this route landed on, or `undefined` for the root store. */\n readonly mount: ResolvedMount | undefined;\n}\n\ninterface MountedDescriptor {\n readonly fs: RepackedFileSystem;\n readonly fd: number;\n}\n\nfunction joinPath(base: string, rest: readonly string[]): string {\n if (rest.length === 0) return base;\n return base === \"/\" ? `/${rest.join(\"/\")}` : `${base}/${rest.join(\"/\")}`;\n}\n\nfunction isMissing(cause: unknown): boolean {\n return cause instanceof FsError && (cause.code === FS_ERRNO.ENOENT || cause.code === FS_ERRNO.ENOTDIR);\n}\n\nexport class MountedRepackedVfs implements RepackedFileSystem {\n readonly #root: RepackedFileSystem;\n readonly #mounts: readonly ResolvedMount[];\n readonly #descriptors = new Map<number, MountedDescriptor>();\n #nextDescriptor = 3;\n\n constructor(options: MountedRepackedVfsOptions) {\n this.#root = options.root;\n const nowMs = (options.nowMs ?? (() => BigInt(Date.now())))();\n const mounts: ResolvedMount[] = [];\n for (const mount of options.mounts) {\n if (parsePath(mount.prefix).length === 0) {\n throw new FsError(\"EINVAL\", \"a mount prefix must be an absolute path below the root\", {\n path: mount.prefix,\n });\n }\n for (const existing of mounts) {\n if (\n existing.prefix === mount.prefix ||\n mount.prefix.startsWith(existing.boundary) ||\n existing.prefix.startsWith(`${mount.prefix}/`)\n ) {\n throw new FsError(\"EINVAL\", `mount prefix ${mount.prefix} overlaps ${existing.prefix}`, {\n path: mount.prefix,\n });\n }\n }\n mounts.push({\n prefix: mount.prefix,\n boundary: `${mount.prefix}/`,\n vfs: mount.vfs,\n durable: mount.durable ?? true,\n });\n }\n this.#mounts = mounts;\n // The prefix is a NAME in the root store so a listing of its parent shows it; every operation\n // at or below it is answered by the mount, so nothing is ever stored behind that name.\n for (const mount of mounts) {\n try {\n this.#root.mkdir(mount.prefix, { recursive: true, nowMs });\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.EEXIST) throw cause;\n }\n }\n }\n\n /** The mounts this composite serves, in declaration order. */\n get mounts(): readonly RepackedMount[] {\n return this.#mounts.map((mount) => ({ prefix: mount.prefix, vfs: mount.vfs, durable: mount.durable }));\n }\n\n /** The store that answers for everything no mount claims. */\n get root(): RepackedFileSystem {\n return this.#root;\n }\n\n // ---- routing and resolution ---------------------------------------------\n\n #route(path: string): Route {\n parsePath(path);\n for (const mount of this.#mounts) {\n if (path === mount.prefix) return { fs: mount.vfs, path: \"/\", mount };\n if (path.startsWith(mount.boundary)) {\n return { fs: mount.vfs, path: path.slice(mount.prefix.length), mount };\n }\n }\n return { fs: this.#root, path, mount: undefined };\n }\n\n /**\n * The link-free composite path `path` names.\n *\n * The fast path asks the routed store to resolve its own view: a store that reports the path\n * unchanged proves there is no link on it, because every entry on that path lives in that store.\n * Anything else falls through to the careful walk, which resolves one component at a time and can\n * therefore cross a boundary in either direction.\n */\n resolvePath(path: string, follow = true): string {\n const route = this.#route(path);\n if (route.fs.resolvePath(route.path, follow) === route.path) return path;\n return this.#walk(path, follow);\n }\n\n #walk(path: string, follow: boolean): string {\n let pending = parsePath(path);\n let index = 0;\n const resolved: string[] = [];\n let hops = 0;\n while (index < pending.length) {\n const candidate = joinPath(`/${resolved.join(\"/\")}`, [pending[index]!]);\n const route = this.#route(candidate);\n let stat: RepackedStat;\n try {\n stat = route.fs.lstat(route.path);\n } catch (cause) {\n if (isMissing(cause)) break;\n throw cause;\n }\n if (stat.kind === \"symlink\" && (follow || index < pending.length - 1)) {\n hops += 1;\n if (hops > MAX_SYMLINK_HOPS) {\n throw new FsError(\"ELOOP\", `path traverses more than ${MAX_SYMLINK_HOPS} symbolic links`, { path });\n }\n pending = parsePath(joinPath(route.fs.readlink(route.path), pending.slice(index + 1)));\n index = 0;\n resolved.length = 0;\n continue;\n }\n resolved.push(pending[index]!);\n index += 1;\n }\n return joinPath(`/${resolved.join(\"/\")}`, pending.slice(index));\n }\n\n /** Resolve, then route. Every path operation below starts here. */\n #at(path: string, follow: boolean): Route {\n return this.#route(this.resolvePath(path, follow));\n }\n\n #descriptor(fd: number): MountedDescriptor {\n const entry = this.#descriptors.get(fd);\n if (entry === undefined) throw new FsError(\"EBADF\", \"descriptor is invalid\");\n return entry;\n }\n\n // ---- lifecycle -----------------------------------------------------------\n\n /** Flushes the root and every mount the owner declared durable; a volatile mount is skipped. */\n strictSync(): void {\n this.#root.strictSync();\n for (const mount of this.#mounts) {\n if (mount.durable) mount.vfs.strictSync();\n }\n }\n\n assertHealthy(): void {\n this.#root.assertHealthy();\n for (const mount of this.#mounts) mount.vfs.assertHealthy();\n }\n\n fail(cause: unknown): never {\n for (const mount of this.#mounts) {\n try {\n mount.vfs.fail(cause);\n } catch {\n // Every store is poisoned with the same cause; the root's throw is the one that escapes.\n }\n }\n return this.#root.fail(cause);\n }\n\n /** The ROOT store's metrics. A mount's own are read through {@link MountedRepackedVfs.mounts}. */\n metrics(): RepackedVfsMetrics {\n return this.#root.metrics();\n }\n\n repack(reason?: RepackReason): void {\n this.#root.repack(reason);\n for (const mount of this.#mounts) mount.vfs.repack(reason);\n }\n\n runScheduledRepack(nowMs?: number): boolean {\n let repacked = this.#root.runScheduledRepack(nowMs);\n for (const mount of this.#mounts) {\n if (mount.vfs.runScheduledRepack(nowMs)) repacked = true;\n }\n return repacked;\n }\n\n close(): void;\n close(fd: number): void;\n close(fd?: number): void {\n if (fd !== undefined) {\n const entry = this.#descriptor(fd);\n this.#descriptors.delete(fd);\n entry.fs.close(entry.fd);\n return;\n }\n this.#descriptors.clear();\n let firstError: unknown;\n for (const mount of this.#mounts) {\n try {\n mount.vfs.close();\n } catch (cause) {\n firstError ??= cause;\n }\n }\n try {\n this.#root.close();\n } catch (cause) {\n firstError ??= cause;\n }\n if (firstError !== undefined) throw firstError;\n }\n\n // ---- path operations -----------------------------------------------------\n\n stat(path: string): RepackedStat {\n const route = this.#at(path, true);\n return route.fs.stat(route.path);\n }\n\n lstat(path: string): RepackedStat {\n const route = this.#at(path, false);\n return route.fs.lstat(route.path);\n }\n\n symlink(target: string, path: string, nowMs: bigint): void {\n const route = this.#at(path, false);\n route.fs.symlink(target, route.path, nowMs);\n }\n\n readlink(path: string): string {\n const route = this.#at(path, false);\n return route.fs.readlink(route.path);\n }\n\n readdir(path: string): string[] {\n const route = this.#at(path, true);\n return route.fs.readdir(route.path);\n }\n\n mkdir(path: string, options: { recursive?: boolean; mode?: number; nowMs: bigint }): void {\n const route = this.#at(path, false);\n route.fs.mkdir(route.path, options);\n }\n\n writeFile(\n path: string,\n data: string | Uint8Array,\n options: { encoding?: string; mode?: number; flag?: string; nowMs: bigint },\n ): void {\n const route = this.#at(path, true);\n route.fs.writeFile(route.path, data, options);\n }\n\n readFile(path: string): Uint8Array {\n const route = this.#at(path, true);\n return route.fs.readFile(route.path);\n }\n\n truncate(path: string, size: bigint, nowMs: bigint): void {\n const route = this.#at(path, true);\n route.fs.truncate(route.path, size, nowMs);\n }\n\n chmod(path: string, mode: number, nowMs: bigint): void {\n const route = this.#at(path, true);\n route.fs.chmod(route.path, mode, nowMs);\n }\n\n utimes(path: string, atimeMs: bigint, mtimeMs: bigint, ctimeMs: bigint): void {\n const route = this.#at(path, true);\n route.fs.utimes(route.path, atimeMs, mtimeMs, ctimeMs);\n }\n\n unlink(path: string, nowMs: bigint): void {\n const route = this.#at(path, false);\n route.fs.unlink(route.path, nowMs);\n }\n\n rmdir(path: string, nowMs: bigint): void {\n const route = this.#at(path, false);\n route.fs.rmdir(route.path, nowMs);\n }\n\n /** A rename is one store's metadata move; across a boundary it is `EXDEV`, as on any host. */\n rename(oldPath: string, newPath: string, nowMs: bigint): void {\n const source = this.#at(oldPath, false);\n const destination = this.#at(newPath, false);\n if (source.mount !== destination.mount) {\n throw new FsError(\"EXDEV\", \"rename crosses a mount boundary\", { operation: \"rename\", path: newPath });\n }\n source.fs.rename(source.path, destination.path, nowMs);\n }\n\n // ---- descriptor operations -----------------------------------------------\n\n open(path: string, flags = \"r\", mode = 0o100666, nowMs = 0n): number {\n const route = this.#at(path, true);\n const inner = route.fs.open(route.path, flags, mode, nowMs);\n const fd = this.#nextDescriptor++;\n this.#descriptors.set(fd, { fs: route.fs, fd: inner });\n return fd;\n }\n\n fstat(fd: number): RepackedStat {\n const entry = this.#descriptor(fd);\n return entry.fs.fstat(entry.fd);\n }\n\n read(fd: number, buffer: Uint8Array, offset: number, length: number, position?: bigint): number {\n const entry = this.#descriptor(fd);\n return entry.fs.read(entry.fd, buffer, offset, length, position);\n }\n\n write(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: bigint | undefined,\n nowMs: bigint,\n ): number {\n const entry = this.#descriptor(fd);\n return entry.fs.write(entry.fd, buffer, offset, length, position, nowMs);\n }\n}\n",
18
+ "/**\n * `MountedRepackedVfs` — one {@link RepackedFileSystem} made of several stores, joined at path\n * prefixes.\n *\n * ## Why\n *\n * A store is a single durable object: four exclusive handles, one arena, one metadata generation.\n * That is exactly right for a datadir and exactly wrong for the parts of a datadir that must NOT be\n * durable — a Postgres temp tablespace, an ephemeral relation, a scratch area whose whole point is\n * that it never reaches the platform. A mount serves one path prefix from a SECOND store, so the\n * durable root and the volatile subtree are one tree to the guest and two stores to the host.\n *\n * ## The shape\n *\n * / -> root store (OPFS: durable)\n * /pgdata/... -> root store\n * /scratch -> mount store (memory: nothing durable)\n * /scratch/anything/... -> mount store, as \"/anything/...\"\n *\n * A mount's prefix is its root: `/scratch/a/b` reaches the mount as `/a/b`, and the prefix itself as\n * `/`. The prefix directory is also created in the ROOT store, so a `readdir` of its parent lists\n * it; every operation AT or BELOW the prefix is answered by the mount, so that root-side directory\n * is a name and nothing more.\n *\n * ## What the composite owns, and what it delegates\n *\n * - **Symlink resolution is the composite's**, because a link is the one thing that can move a path\n * from one store to another: `pg_tblspc/<oid>` lives in the root and points at `/scratch`, and\n * neither store alone can resolve it (the root would resolve it against its own placeholder\n * directory and find nothing there). The fast path is one `resolvePath` call on the store the\n * path already routes to — if that store says the path holds no link, no link exists on it at\n * all, because every entry on the path lives in that store. Only a path that really does traverse\n * a link pays the component-by-component walk.\n * - **Descriptors are the composite's.** Each store numbers its own fds from 3, so the composite\n * hands out its own numbers and remembers which store each belongs to.\n * - **`rename` across a boundary is `EXDEV`**, exactly as it is between two real filesystems: a\n * rename is a metadata move inside one store and cannot span two.\n * - **`strictSync()` skips a mount declared non-durable.** A memory-backed mount has nothing to make\n * durable, and a store-wide sync that walked it would charge the guest for flushes that cannot\n * protect anything. Durability is a property the STORAGE OWNER declares per mount; nothing here\n * infers it from the port.\n * - Everything else is a route plus a delegation.\n */\n\nimport { FS_ERRNO, FsError } from \"./errors\";\nimport { MAX_SYMLINK_HOPS } from \"./limits\";\nimport { parsePath } from \"./path\";\nimport type { RepackedFileSystem, RepackedStat, RepackedVfsMetrics, RepackReason } from \"./repacked-vfs\";\n\n/** One store served at one path prefix. */\nexport interface RepackedMount {\n /** Absolute, canonical, and never `/`: the path the mount's own root appears at. */\n readonly prefix: string;\n readonly vfs: RepackedFileSystem;\n /**\n * Whether a store-wide `strictSync()` reaches this mount. Defaults to `true`. A volatile mount\n * (memory-backed scratch) declares `false`: there is nothing to flush, and pretending otherwise\n * charges every guest `fsync` for it.\n */\n readonly durable?: boolean;\n}\n\nexport interface MountedRepackedVfsOptions {\n /** The store that answers for every path no mount claims. */\n readonly root: RepackedFileSystem;\n readonly mounts: readonly RepackedMount[];\n /** The clock used to create each mount's placeholder directory in the root. */\n readonly nowMs?: () => bigint;\n}\n\ninterface ResolvedMount {\n readonly prefix: string;\n readonly boundary: string;\n readonly vfs: RepackedFileSystem;\n readonly durable: boolean;\n}\n\ninterface Route {\n readonly fs: RepackedFileSystem;\n /** The path as the routed store sees it. */\n readonly path: string;\n /** The mount this route landed on, or `undefined` for the root store. */\n readonly mount: ResolvedMount | undefined;\n}\n\ninterface MountedDescriptor {\n readonly fs: RepackedFileSystem;\n readonly fd: number;\n}\n\nfunction joinPath(base: string, rest: readonly string[]): string {\n if (rest.length === 0) return base;\n return base === \"/\" ? `/${rest.join(\"/\")}` : `${base}/${rest.join(\"/\")}`;\n}\n\nfunction isMissing(cause: unknown): boolean {\n return cause instanceof FsError && (cause.code === FS_ERRNO.ENOENT || cause.code === FS_ERRNO.ENOTDIR);\n}\n\nexport class MountedRepackedVfs implements RepackedFileSystem {\n readonly #root: RepackedFileSystem;\n readonly #mounts: readonly ResolvedMount[];\n readonly #descriptors = new Map<number, MountedDescriptor>();\n #nextDescriptor = 3;\n\n constructor(options: MountedRepackedVfsOptions) {\n this.#root = options.root;\n const nowMs = (options.nowMs ?? (() => BigInt(Date.now())))();\n const mounts: ResolvedMount[] = [];\n for (const mount of options.mounts) {\n if (parsePath(mount.prefix).length === 0) {\n throw new FsError(\"EINVAL\", \"a mount prefix must be an absolute path below the root\", {\n path: mount.prefix,\n });\n }\n for (const existing of mounts) {\n if (\n existing.prefix === mount.prefix ||\n mount.prefix.startsWith(existing.boundary) ||\n existing.prefix.startsWith(`${mount.prefix}/`)\n ) {\n throw new FsError(\"EINVAL\", `mount prefix ${mount.prefix} overlaps ${existing.prefix}`, {\n path: mount.prefix,\n });\n }\n }\n mounts.push({\n prefix: mount.prefix,\n boundary: `${mount.prefix}/`,\n vfs: mount.vfs,\n durable: mount.durable ?? true,\n });\n }\n this.#mounts = mounts;\n // The prefix is a NAME in the root store so a listing of its parent shows it; every operation\n // at or below it is answered by the mount, so nothing is ever stored behind that name.\n for (const mount of mounts) {\n try {\n this.#root.mkdir(mount.prefix, { recursive: true, nowMs });\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.EEXIST) throw cause;\n }\n }\n }\n\n /** The mounts this composite serves, in declaration order. */\n get mounts(): readonly RepackedMount[] {\n return this.#mounts.map((mount) => ({ prefix: mount.prefix, vfs: mount.vfs, durable: mount.durable }));\n }\n\n /** The store that answers for everything no mount claims. */\n get root(): RepackedFileSystem {\n return this.#root;\n }\n\n // ---- routing and resolution ---------------------------------------------\n\n #route(path: string): Route {\n parsePath(path);\n for (const mount of this.#mounts) {\n if (path === mount.prefix) return { fs: mount.vfs, path: \"/\", mount };\n if (path.startsWith(mount.boundary)) {\n return { fs: mount.vfs, path: path.slice(mount.prefix.length), mount };\n }\n }\n return { fs: this.#root, path, mount: undefined };\n }\n\n /**\n * The link-free composite path `path` names.\n *\n * The fast path asks the routed store to resolve its own view: a store that reports the path\n * unchanged proves there is no link on it, because every entry on that path lives in that store.\n * Anything else falls through to the careful walk, which resolves one component at a time and can\n * therefore cross a boundary in either direction.\n */\n resolvePath(path: string, follow = true): string {\n const route = this.#route(path);\n if (route.fs.resolvePath(route.path, follow) === route.path) return path;\n return this.#walk(path, follow);\n }\n\n #walk(path: string, follow: boolean): string {\n let pending = parsePath(path);\n let index = 0;\n const resolved: string[] = [];\n let hops = 0;\n while (index < pending.length) {\n const candidate = joinPath(`/${resolved.join(\"/\")}`, [pending[index]!]);\n const route = this.#route(candidate);\n let stat: RepackedStat;\n try {\n stat = route.fs.lstat(route.path);\n } catch (cause) {\n if (isMissing(cause)) break;\n throw cause;\n }\n if (stat.kind === \"symlink\" && (follow || index < pending.length - 1)) {\n hops += 1;\n if (hops > MAX_SYMLINK_HOPS) {\n throw new FsError(\"ELOOP\", `path traverses more than ${MAX_SYMLINK_HOPS} symbolic links`, { path });\n }\n pending = parsePath(joinPath(route.fs.readlink(route.path), pending.slice(index + 1)));\n index = 0;\n resolved.length = 0;\n continue;\n }\n resolved.push(pending[index]!);\n index += 1;\n }\n return joinPath(`/${resolved.join(\"/\")}`, pending.slice(index));\n }\n\n /** Resolve, then route. Every path operation below starts here. */\n #at(path: string, follow: boolean): Route {\n return this.#route(this.resolvePath(path, follow));\n }\n\n #descriptor(fd: number): MountedDescriptor {\n const entry = this.#descriptors.get(fd);\n if (entry === undefined) throw new FsError(\"EBADF\", \"descriptor is invalid\");\n return entry;\n }\n\n // ---- lifecycle -----------------------------------------------------------\n\n /** Flushes the root and every mount the owner declared durable; a volatile mount is skipped. */\n strictSync(): void {\n this.#root.strictSync();\n for (const mount of this.#mounts) {\n if (mount.durable) mount.vfs.strictSync();\n }\n }\n\n assertHealthy(): void {\n this.#root.assertHealthy();\n for (const mount of this.#mounts) mount.vfs.assertHealthy();\n }\n\n fail(cause: unknown): never {\n for (const mount of this.#mounts) {\n try {\n mount.vfs.fail(cause);\n } catch {\n // Every store is poisoned with the same cause; the root's throw is the one that escapes.\n }\n }\n return this.#root.fail(cause);\n }\n\n /** The ROOT store's metrics. A mount's own are read through {@link MountedRepackedVfs.mounts}. */\n metrics(): RepackedVfsMetrics {\n return this.#root.metrics();\n }\n\n repack(reason?: RepackReason): void {\n this.#root.repack(reason);\n for (const mount of this.#mounts) mount.vfs.repack(reason);\n }\n\n runScheduledRepack(nowMs?: number): boolean {\n let repacked = this.#root.runScheduledRepack(nowMs);\n for (const mount of this.#mounts) {\n if (mount.vfs.runScheduledRepack(nowMs)) repacked = true;\n }\n return repacked;\n }\n\n close(): void;\n close(fd: number): void;\n close(fd?: number): void {\n if (fd !== undefined) {\n const entry = this.#descriptor(fd);\n this.#descriptors.delete(fd);\n entry.fs.close(entry.fd);\n return;\n }\n this.#descriptors.clear();\n let firstError: unknown;\n for (const mount of this.#mounts) {\n try {\n mount.vfs.close();\n } catch (cause) {\n firstError ??= cause;\n }\n }\n try {\n this.#root.close();\n } catch (cause) {\n firstError ??= cause;\n }\n if (firstError !== undefined) throw firstError;\n }\n\n // ---- path operations -----------------------------------------------------\n\n stat(path: string): RepackedStat {\n const route = this.#at(path, true);\n return route.fs.stat(route.path);\n }\n\n lstat(path: string): RepackedStat {\n const route = this.#at(path, false);\n return route.fs.lstat(route.path);\n }\n\n symlink(target: string, path: string, nowMs: bigint): void {\n const route = this.#at(path, false);\n route.fs.symlink(target, route.path, nowMs);\n }\n\n readlink(path: string): string {\n const route = this.#at(path, false);\n return route.fs.readlink(route.path);\n }\n\n readdir(path: string): string[] {\n const route = this.#at(path, true);\n return route.fs.readdir(route.path);\n }\n\n mkdir(path: string, options: { recursive?: boolean; mode?: number; nowMs: bigint }): void {\n const route = this.#at(path, false);\n route.fs.mkdir(route.path, options);\n }\n\n writeFile(\n path: string,\n data: string | Uint8Array,\n options: { encoding?: string; mode?: number; flag?: string; nowMs: bigint },\n ): void {\n const route = this.#at(path, true);\n route.fs.writeFile(route.path, data, options);\n }\n\n readFile(path: string): Uint8Array {\n const route = this.#at(path, true);\n return route.fs.readFile(route.path);\n }\n\n truncate(path: string, size: bigint, nowMs: bigint): void {\n const route = this.#at(path, true);\n route.fs.truncate(route.path, size, nowMs);\n }\n\n chmod(path: string, mode: number, nowMs: bigint): void {\n const route = this.#at(path, true);\n route.fs.chmod(route.path, mode, nowMs);\n }\n\n utimes(path: string, atimeMs: bigint, mtimeMs: bigint, ctimeMs: bigint): void {\n const route = this.#at(path, true);\n route.fs.utimes(route.path, atimeMs, mtimeMs, ctimeMs);\n }\n\n unlink(path: string, nowMs: bigint): void {\n const route = this.#at(path, false);\n route.fs.unlink(route.path, nowMs);\n }\n\n rmdir(path: string, nowMs: bigint): void {\n const route = this.#at(path, false);\n route.fs.rmdir(route.path, nowMs);\n }\n\n /** A rename is one store's metadata move; across a boundary it is `EXDEV`, as on any host. */\n rename(oldPath: string, newPath: string, nowMs: bigint): void {\n const source = this.#at(oldPath, false);\n const destination = this.#at(newPath, false);\n if (source.mount !== destination.mount) {\n throw new FsError(\"EXDEV\", \"rename crosses a mount boundary\", { operation: \"rename\", path: newPath });\n }\n source.fs.rename(source.path, destination.path, nowMs);\n }\n\n // ---- descriptor operations -----------------------------------------------\n\n open(path: string, flags = \"r\", mode = 0o100666, nowMs = 0n): number {\n const route = this.#at(path, true);\n const inner = route.fs.open(route.path, flags, mode, nowMs);\n const fd = this.#nextDescriptor++;\n this.#descriptors.set(fd, { fs: route.fs, fd: inner });\n return fd;\n }\n\n fstat(fd: number): RepackedStat {\n const entry = this.#descriptor(fd);\n return entry.fs.fstat(entry.fd);\n }\n\n read(fd: number, buffer: Uint8Array, offset: number, length: number, position?: bigint): number {\n const entry = this.#descriptor(fd);\n return entry.fs.read(entry.fd, buffer, offset, length, position);\n }\n\n write(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: bigint | undefined,\n nowMs: bigint,\n ): number {\n const entry = this.#descriptor(fd);\n return entry.fs.write(entry.fd, buffer, offset, length, position, nowMs);\n }\n}\n",
19
19
  "/**\n * The FILE-backed `RepackedPort`: the same four owned files, in an ordinary directory on an ordinary\n * filesystem, opened with `node:fs`'s synchronous calls.\n *\n * It exists because the store's four files are the store — nothing about the format is OPFS's, and\n * nothing about it is a browser's. A host running under Node or Bun can therefore BUILD a store\n * (seed it, fill it, repack it) where a build step can see the bytes, hand those four files to a\n * browser, and have the browser's `OpfsRepackedPort` open them as the same store. Format identity\n * is by construction: the port answers `getSize`/`read`/`write`/`truncate`/`flush` and the layout\n * above it never learns which port it is on.\n *\n * **`node:fs` is imported LAZILY, and that is load-bearing.** This module is exported from the\n * package entry, and the package's redistribution artifact (`dist/browser-bundle.js`) is built with\n * `--target browser`, where a STATIC `import { openSync } from \"node:fs\"` is compiled to an empty\n * object — every call would then be `undefined is not a function`, in Node as well as in a browser,\n * because that one bundle is what the wasm hosts load in BOTH. A dynamic `import(\"node:fs\")` is left\n * verbatim by every target, so the same file resolves the real module under Node/Bun and rejects\n * where there is no such module. `enumerate` and `acquire` are already async, which is the whole\n * reason the seam fits: every method on the HANDLE stays synchronous, as the store requires.\n *\n * **Ownership is not exclusion.** OPFS's `createSyncAccessHandle()` is exclusive per origin, and\n * `StoreOwnedError` there means another live owner. POSIX `open` grants nothing of the kind: two\n * processes may hold the same file open and interleave writes, and no advisory lock this port could\n * take would be honoured by a process that did not take one. So the guarantee here is bounded and\n * stated — a second `acquire` of a name this port already has open raises `StoreOwnedError`, and a\n * SECOND PROCESS is the host's problem to arrange. The intended use is a single build-time owner.\n */\n// Type-only, and therefore erased before any bundler sees it — the RUNTIME import is the dynamic one\n// in `loadNodeFileSystem` below, which is the whole point of this module's shape.\nimport type * as NodeFsModule from \"node:fs\";\n\nimport { StoreOwnedError } from \"./core/errors\";\nimport type { OwnedFileName, RepackedFileHandle, RepackedPort, RepackedPortEntry } from \"./core/port\";\n\n/** The `node:fs` surface this port uses, and nothing else. Never part of an exported signature. */\ntype NodeFileSystem = Pick<\n typeof NodeFsModule,\n | \"closeSync\"\n | \"constants\"\n | \"fstatSync\"\n | \"ftruncateSync\"\n | \"fsyncSync\"\n | \"mkdirSync\"\n | \"openSync\"\n | \"readSync\"\n | \"readdirSync\"\n | \"writeSync\"\n>;\n\n/** The mode a newly created owned file takes; the process umask applies to it as it does anywhere. */\nconst CREATED_FILE_MODE = 0o666;\n\n/**\n * Resolve `node:fs`, or say why there is none.\n *\n * A bare rejected `import()` in a browser reads as \"Failed to resolve module specifier\", which names\n * neither this port nor the reason; the check in front of it is what turns that into an answer.\n */\nasync function loadNodeFileSystem(): Promise<NodeFileSystem> {\n const runtime = globalThis as { process?: { versions?: Record<string, string | undefined> } };\n if (runtime.process?.versions?.[\"node\"] === undefined) {\n throw new Error(\n \"FileRepackedPort needs node:fs and this scope has none (no process.versions.node); \" +\n \"a browser store belongs on OpfsRepackedPort\",\n );\n }\n return (await import(\"node:fs\")) as NodeFileSystem;\n}\n\nfunction joinPath(directory: string, name: string): string {\n return `${directory.replace(/\\/+$/, \"\")}/${name}`;\n}\n\nexport class FileRepackedPort implements RepackedPort {\n readonly #directory: string;\n readonly #open = new Set<OwnedFileName>();\n #fs: NodeFileSystem | undefined;\n\n /**\n * @param directory The directory this store owns in full. It is created on first use, with every\n * parent, exactly as the OPFS port's caller creates its directory handle with `create: true`.\n */\n constructor(directory: string) {\n if (directory.trim() === \"\") throw new TypeError(\"FileRepackedPort needs a directory path\");\n this.#directory = directory;\n }\n\n /** The directory this port reads and writes. Absolute or relative, exactly as it was given. */\n get directory(): string {\n return this.#directory;\n }\n\n async enumerate(_label: string): Promise<readonly RepackedPortEntry[]> {\n const fs = await this.#ready();\n // Everything that is there, not just the four names: an entry the store did not write is what\n // `UnexpectedStoreEntryError` is for, and hiding it here would open a store over a stranger's\n // directory.\n return fs.readdirSync(this.#directory, { withFileTypes: true }).map((entry) => ({\n name: entry.name,\n kind: entry.isDirectory() ? (\"directory\" as const) : (\"file\" as const),\n }));\n }\n\n async acquire(name: OwnedFileName, _label: string): Promise<RepackedFileHandle> {\n const fs = await this.#ready();\n // The bounded half of the ownership guarantee; see the file header for the half POSIX cannot give.\n if (this.#open.has(name)) throw new StoreOwnedError();\n // `r+` that creates: O_RDWR|O_CREAT, which is `openSync(path, \"r+\")`'s flags plus the create bit\n // and NOT `a+` — an append-mode fd ignores the position argument on every write, which would\n // turn the arena's random writes into a log.\n const fd = fs.openSync(\n joinPath(this.#directory, name),\n fs.constants.O_RDWR | fs.constants.O_CREAT,\n CREATED_FILE_MODE,\n );\n this.#open.add(name);\n return new FileRepackedFileHandle(fs, name, fd, () => this.#open.delete(name));\n }\n\n async #ready(): Promise<NodeFileSystem> {\n if (this.#fs === undefined) {\n const fs = await loadNodeFileSystem();\n fs.mkdirSync(this.#directory, { recursive: true });\n this.#fs = fs;\n }\n return this.#fs;\n }\n}\n\nclass FileRepackedFileHandle implements RepackedFileHandle {\n readonly name: OwnedFileName;\n readonly #fs: NodeFileSystem;\n readonly #fd: number;\n readonly #released: () => void;\n #closed = false;\n\n constructor(fs: NodeFileSystem, name: OwnedFileName, fd: number, released: () => void) {\n this.#fs = fs;\n this.name = name;\n this.#fd = fd;\n this.#released = released;\n }\n\n getSize(_label: string): number {\n this.#assertOpen();\n return this.#fs.fstatSync(this.#fd).size;\n }\n\n read(target: Uint8Array, at: number, _label: string): number {\n this.#assertOpen();\n // A read wholly past the end answers 0, which `readExact` reports as a store that ended early —\n // the same thing an OPFS access handle answers there.\n return this.#fs.readSync(this.#fd, target, 0, target.byteLength, at);\n }\n\n write(source: Uint8Array, at: number, _label: string): number {\n this.#assertOpen();\n return this.#fs.writeSync(this.#fd, source, 0, source.byteLength, at);\n }\n\n truncate(size: number, _label: string): void {\n this.#assertOpen();\n this.#fs.ftruncateSync(this.#fd, size);\n }\n\n flush(_label: string): void {\n this.#assertOpen();\n // The platform's durability boundary, not a userspace buffer drain: nothing here buffers, so\n // `fsync` is the only thing `flush` can honestly mean.\n this.#fs.fsyncSync(this.#fd);\n }\n\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n this.#released();\n this.#fs.closeSync(this.#fd);\n }\n\n #assertOpen(): void {\n if (this.#closed) throw new Error(`file handle ${this.name} is closed`);\n }\n}\n",
20
20
  "/**\n * The synchronous broker wire protocol.\n *\n * ## Why a wire protocol at all\n *\n * A repacked store is a single-owner object: it holds four exclusive file handles and one in-memory\n * metadata generation, and it is not shareable across JavaScript agents. A multi-backend engine needs\n * several worker threads to reach ONE store, and a worker running wasm parks in futexes, so it cannot\n * await a promise to get a file answered. The store therefore lives alone in a coordinator worker and\n * every other thread asks for file operations over a `SharedArrayBuffer`, blocking in `Atomics.wait`\n * until the coordinator answers. Nothing here knows about the engine, wasm, or OPFS.\n *\n * ## Topology\n *\n * One CHANNEL per client, plus one DOORBELL shared by every channel of one broker:\n *\n * client A ─ channel A ─┐\n * client B ─ channel B ─┼─→ doorbell ─→ RepackedSyncBroker (owns the RepackedVfs)\n * client C ─ channel C ─┘\n *\n * A client publishes its request into its own channel and then bumps the doorbell, so one blocking\n * server loop can wait on a single word and still service any number of clients.\n *\n * ## Channel layout\n *\n * One `SharedArrayBuffer`, `CHANNEL_HEADER_BYTES` (64) of `Int32Array` header followed by a byte\n * payload region (`DEFAULT_PAYLOAD_BYTES`, 64 KiB, chosen at channel creation):\n *\n * offset size as name\n * ------ ---- -------- ------------------------------------------------------------------\n * 0 4 int32 HEADER_STATE the word both sides `Atomics.wait` / `notify` on\n * 4 4 int32 HEADER_OPCODE `OPCODE_*`, written by the client\n * 8 4 int32 HEADER_REQUEST request bytes valid in the payload region\n * 12 4 int32 HEADER_RESPONSE response bytes valid in the payload region\n * 16 4 int32 HEADER_ERRNO 0, or the WASI preview1 errno of a file rejection\n * 20 4 int32 HEADER_RESULT_LO low 32 bits of the unsigned 64-bit result\n * 24 4 int32 HEADER_RESULT_HI high 32 bits of the unsigned 64-bit result\n * 28 4 int32 HEADER_SEQUENCE the client's monotonic request number\n * 32 4 int32 HEADER_FAULT `FAULT_*` — a transport/store failure, not a file one\n * 36 4 int32 HEADER_PAYLOAD payload capacity in bytes (written once at creation)\n * 40 24 int32[6] reserved, always zero\n * 64 … bytes payload region\n *\n * `HEADER_STATE` is the whole handshake:\n *\n * STATE_IDLE (0) ──client publishes──→ STATE_REQUEST (1) ──server answers──→ STATE_RESPONSE (2)\n * ↑ │ │\n * └─────────────client consumes─────────┼─────────────────────────────────────┘\n * └──server rejects the client──→ STATE_DETACHED (3)\n *\n * `STATE_DETACHED` is terminal: the server has closed the client's descriptors and dropped it, and\n * every later client call throws instead of blocking forever.\n *\n * ## Doorbell layout\n *\n * A small separate `SharedArrayBuffer`, `DOORBELL_BYTES` (16) of `Int32Array`:\n *\n * index name meaning\n * ----- ---------------- ----------------------------------------------------------------\n * 0 DOORBELL_TICKET incremented by any client that publishes a request; the word the\n * server's blocking loop waits on\n * 1 DOORBELL_RUNNING 1 while the server should keep looping, 0 to ask it to return\n * 2 reserved\n * 3 reserved\n *\n * The server reads `DOORBELL_TICKET` BEFORE it scans the channels and waits on that observed value,\n * so a request published during the scan makes the wait return `not-equal` immediately rather than\n * being missed.\n *\n * ## Ordering\n *\n * Nothing in the payload region is atomic, and nothing needs to be. Each side writes its payload with\n * ordinary stores and then publishes with `Atomics.store` on `HEADER_STATE`; the other side observes\n * with `Atomics.load` on the same word before touching the payload. That store/load pair is the\n * release/acquire edge, so every payload byte written before the publish is visible after the observe.\n *\n * ## Encoding\n *\n * Payloads are little-endian. Paths — and a symbolic link's TARGET, which is a path the store never\n * walks — are `u32` byte length followed by UTF-8 bytes; sizes, offsets and\n * timestamps are unsigned 64-bit (`bigint`) because a virtual file may exceed 2^53 in principle and\n * the core store speaks `bigint` throughout. Byte counts that cannot exceed the payload region stay\n * `u32`. The single numeric answer of an operation travels in the header's 64-bit result pair, not in\n * the payload, so a read reply is nothing but its bytes.\n */\n\nimport { FS_ERRNO, FsError } from \"../core/errors\";\nimport type { FsErrorName } from \"../core/errors\";\n\n/** Int32 slot indices of the channel header. */\nexport const HEADER_STATE = 0;\nexport const HEADER_OPCODE = 1;\nexport const HEADER_REQUEST = 2;\nexport const HEADER_RESPONSE = 3;\nexport const HEADER_ERRNO = 4;\nexport const HEADER_RESULT_LO = 5;\nexport const HEADER_RESULT_HI = 6;\nexport const HEADER_SEQUENCE = 7;\nexport const HEADER_FAULT = 8;\nexport const HEADER_PAYLOAD = 9;\nexport const CHANNEL_HEADER_SLOTS = 16;\nexport const CHANNEL_HEADER_BYTES = CHANNEL_HEADER_SLOTS * 4;\n\n/** `HEADER_STATE` values. */\nexport const STATE_IDLE = 0;\nexport const STATE_REQUEST = 1;\nexport const STATE_RESPONSE = 2;\nexport const STATE_DETACHED = 3;\n\n/** Int32 slot indices of the doorbell. */\nexport const DOORBELL_TICKET = 0;\nexport const DOORBELL_RUNNING = 1;\nexport const DOORBELL_SLOTS = 4;\nexport const DOORBELL_BYTES = DOORBELL_SLOTS * 4;\n\n/** The default payload region: large enough that a Postgres 8 KiB page round-trips in one request. */\nexport const DEFAULT_PAYLOAD_BYTES = 64 * 1024;\n/** A payload region below this cannot hold the fixed part of every request. */\nexport const MIN_PAYLOAD_BYTES = 1024;\n\n/**\n * `HEADER_FAULT` values. A fault is NOT a file rejection: `HEADER_ERRNO` carries those and leaves the\n * client working. A fault means the transport or the store itself failed.\n */\nexport const FAULT_NONE = 0;\n/** The client violated the protocol (unknown opcode, impossible length, truncated payload). */\nexport const FAULT_PROTOCOL = 1;\n/** The store threw something that is not an `FsError` — it is very likely poisoned. */\nexport const FAULT_STORE = 2;\n/** The server rejected or dropped the client for a reason of its own (explicit `detach`). */\nexport const FAULT_DETACHED = 3;\n\n/** Every operation the broker speaks. */\nexport const OPCODE_OPEN = 1;\nexport const OPCODE_CLOSE = 2;\nexport const OPCODE_READ = 3;\nexport const OPCODE_WRITE = 4;\nexport const OPCODE_FSYNC = 5;\nexport const OPCODE_FSTAT = 6;\nexport const OPCODE_STAT = 7;\nexport const OPCODE_LSTAT = 8;\nexport const OPCODE_READDIR = 9;\nexport const OPCODE_MKDIR = 10;\nexport const OPCODE_RMDIR = 11;\nexport const OPCODE_UNLINK = 12;\nexport const OPCODE_RENAME = 13;\nexport const OPCODE_TRUNCATE = 14;\nexport const OPCODE_SIZE = 15;\nexport const OPCODE_SYMLINK = 16;\nexport const OPCODE_READLINK = 17;\nconst MIN_OPCODE = OPCODE_OPEN;\nconst MAX_OPCODE = OPCODE_READLINK;\n\nexport function isKnownOpcode(opcode: number): boolean {\n return Number.isInteger(opcode) && opcode >= MIN_OPCODE && opcode <= MAX_OPCODE;\n}\n\n/**\n * POSIX/WASI-shaped open bits. The wire carries these, never the core's node-style flag string: a WASI\n * `path_open` maps its `oflags`/`fdflags`/`fs_rights_base` onto them directly, and the server is the\n * only place that has to know the core's string vocabulary.\n */\nexport const O_RDONLY = 0;\nexport const O_WRONLY = 1;\nexport const O_RDWR = 2;\nexport const O_ACCMODE = 3;\nexport const O_CREAT = 0o100;\nexport const O_EXCL = 0o200;\nexport const O_TRUNC = 0o1000;\nexport const O_APPEND = 0o2000;\n/**\n * Refuse to follow a symbolic link on the FINAL component. Linux's own bit value, and the wire form\n * of a WASI `path_open` whose lookup flags omit `SYMLINK_FOLLOW`.\n */\nexport const O_NOFOLLOW = 0o400000;\nconst O_KNOWN = O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC | O_APPEND | O_NOFOLLOW;\n\n/** The stat shape on the wire: `kind` + mode + size + the three timestamps. */\nexport const STAT_KIND_FILE = 0;\nexport const STAT_KIND_DIRECTORY = 1;\nexport const STAT_KIND_SYMLINK = 2;\nexport const STAT_BYTES = 1 + 4 + 8 * 4;\n\n/** A `readdir` reply that ran out of payload room reports the cursor to resume from; -1 means done. */\nexport const READDIR_DONE = -1;\n\n/**\n * How the server should satisfy one open request with the core's fixed flag-string vocabulary\n * (`r`, `r+`, `w`, `w+`, `wx`, `wx+`, `a`, `a+`, `ax`, `ax+`).\n *\n * `readable`/`writable` are the access the CLIENT asked for, which is not always what `coreFlags`\n * grants: the core has no \"create without truncating and without appending\" and no write-only\n * non-truncating mode, so those requests open a wider core descriptor and the broker enforces the\n * requested access itself on every later read/write.\n */\nexport interface OpenPlan {\n /** The core flag string to try first. */\n readonly coreFlags: string;\n /** Used only when `coreFlags` fails with ENOENT — the create-without-truncate two-step. */\n readonly fallbackFlags: string | undefined;\n /** `O_TRUNC` without `O_CREAT`: truncate the existing path to zero before opening. */\n readonly truncateFirst: boolean;\n /** No `O_CREAT`, but `coreFlags` would create: the server must prove the path exists first. */\n readonly requireExisting: boolean;\n /** The access the client asked for, enforced by the broker on top of the core descriptor. */\n readonly readable: boolean;\n readonly writable: boolean;\n /** `false` for `O_NOFOLLOW`: a final component that IS a symbolic link must answer `ELOOP`. */\n readonly follow: boolean;\n}\n\n/**\n * Translate POSIX open bits into the core's vocabulary, or reject the combination with `EINVAL`.\n *\n * Rejected because they are meaningless rather than merely unsupported: an unknown bit, `O_EXCL`\n * without `O_CREAT`, `O_TRUNC` with `O_APPEND`, and a read-only request that also creates,\n * truncates, or appends.\n */\nexport function planOpen(flags: number): OpenPlan {\n if (!Number.isInteger(flags) || flags < 0 || (flags & ~O_KNOWN) !== 0) {\n throw new FsError(\"EINVAL\", `unsupported open flags: ${flags}`);\n }\n const access = flags & O_ACCMODE;\n if (access === O_ACCMODE) throw new FsError(\"EINVAL\", \"open access mode is invalid\");\n const readable = access === O_RDONLY || access === O_RDWR;\n const writable = access === O_WRONLY || access === O_RDWR;\n const create = (flags & O_CREAT) !== 0;\n const exclusive = (flags & O_EXCL) !== 0;\n const truncate = (flags & O_TRUNC) !== 0;\n const append = (flags & O_APPEND) !== 0;\n\n if (exclusive && !create) throw new FsError(\"EINVAL\", \"O_EXCL requires O_CREAT\");\n if (truncate && append) throw new FsError(\"EINVAL\", \"O_TRUNC and O_APPEND are contradictory\");\n if (!writable && (create || truncate || append)) {\n throw new FsError(\"EINVAL\", \"O_CREAT, O_TRUNC and O_APPEND require write access\");\n }\n\n const plan = (coreFlags: string, extra: Partial<OpenPlan> = {}): OpenPlan => ({\n coreFlags,\n fallbackFlags: undefined,\n truncateFirst: false,\n requireExisting: false,\n readable,\n writable,\n follow: (flags & O_NOFOLLOW) === 0,\n ...extra,\n });\n\n // Exclusive creation can never truncate anything (the file must not exist), so `wx`/`ax` serve\n // both the with- and without-O_TRUNC spellings.\n if (exclusive) return plan(append ? (readable ? \"ax+\" : \"ax\") : readable ? \"wx+\" : \"wx\");\n if (append && create) return plan(readable ? \"a+\" : \"a\");\n if (truncate && create) return plan(readable ? \"w+\" : \"w\");\n // No O_CREAT past this point: every core append flag creates, so the server proves existence first.\n if (append) return plan(readable ? \"a+\" : \"a\", { requireExisting: true });\n if (truncate) return plan(\"r+\", { truncateFirst: true });\n // Create-without-truncate: reuse the file if it is there, otherwise create it empty. `r+` is wider\n // than a write-only request asked for, which is why `writable`/`readable` are carried separately.\n if (create) return plan(\"r+\", { fallbackFlags: \"w+\" });\n return plan(readable && !writable ? \"r\" : \"r+\");\n}\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: true });\n\n/** Thrown when a payload cannot hold what a caller is trying to put in it. */\nexport class PayloadOverflowError extends Error {\n constructor(needed: number, capacity: number) {\n super(`broker payload needs ${needed} bytes but the channel region holds ${capacity}`);\n this.name = \"PayloadOverflowError\";\n }\n}\n\n/** Thrown when a payload does not decode — always a protocol violation by the peer that wrote it. */\nexport class PayloadDecodeError extends Error {\n constructor(message: string) {\n super(`broker payload is malformed: ${message}`);\n this.name = \"PayloadDecodeError\";\n }\n}\n\n/** Sequential little-endian writer over a channel's payload region. */\nexport class PayloadWriter {\n readonly #view: DataView;\n readonly #bytes: Uint8Array;\n #cursor = 0;\n\n constructor(payload: Uint8Array) {\n this.#bytes = payload;\n this.#view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);\n }\n\n get length(): number {\n return this.#cursor;\n }\n\n get remaining(): number {\n return this.#bytes.byteLength - this.#cursor;\n }\n\n u8(value: number): void {\n this.#view.setUint8(this.#reserve(1), value);\n }\n\n u32(value: number): void {\n this.#view.setUint32(this.#reserve(4), value, true);\n }\n\n i32(value: number): void {\n this.#view.setInt32(this.#reserve(4), value, true);\n }\n\n u64(value: bigint): void {\n this.#view.setBigUint64(this.#reserve(8), value, true);\n }\n\n bytes(source: Uint8Array): void {\n this.#bytes.set(source, this.#reserve(source.byteLength));\n }\n\n string(value: string): void {\n const encoded = textEncoder.encode(value);\n this.u32(encoded.byteLength);\n this.bytes(encoded);\n }\n\n /**\n * Discard everything written after `to`, backing out a field that did not fit. A `string` reserves\n * its length prefix before its bytes, so a name that overflows can leave four bytes behind.\n */\n rewind(to: number): void {\n if (!Number.isSafeInteger(to) || to < 0 || to > this.#cursor) {\n throw new RangeError(\"the payload rewind target is outside what has been written\");\n }\n this.#cursor = to;\n }\n\n /**\n * A mutable view over `count` bytes already written at `at` — for a counter that has to be reserved\n * before its value is known (a `readdir` page fills until the payload runs out).\n */\n patch(at: number, count: number): DataView {\n if (!Number.isSafeInteger(at) || !Number.isSafeInteger(count) || at < 0 || count < 0 || at + count > this.#cursor) {\n throw new RangeError(\"the payload patch range is outside what has been written\");\n }\n return new DataView(this.#bytes.buffer, this.#bytes.byteOffset + at, count);\n }\n\n #reserve(count: number): number {\n if (count > this.remaining) throw new PayloadOverflowError(this.#cursor + count, this.#bytes.byteLength);\n const at = this.#cursor;\n this.#cursor += count;\n return at;\n }\n}\n\n/** Sequential little-endian reader over a channel's payload region. */\nexport class PayloadReader {\n readonly #view: DataView;\n readonly #bytes: Uint8Array;\n #cursor = 0;\n\n constructor(payload: Uint8Array, length: number) {\n if (!Number.isSafeInteger(length) || length < 0 || length > payload.byteLength) {\n throw new PayloadDecodeError(`declared length ${length} is outside the payload region`);\n }\n this.#bytes = payload.subarray(0, length);\n this.#view = new DataView(payload.buffer, payload.byteOffset, length);\n }\n\n get remaining(): number {\n return this.#bytes.byteLength - this.#cursor;\n }\n\n u8(): number {\n return this.#view.getUint8(this.#take(1));\n }\n\n u32(): number {\n return this.#view.getUint32(this.#take(4), true);\n }\n\n i32(): number {\n return this.#view.getInt32(this.#take(4), true);\n }\n\n u64(): bigint {\n return this.#view.getBigUint64(this.#take(8), true);\n }\n\n bytes(count: number): Uint8Array {\n return this.#bytes.subarray(this.#take(count), this.#cursor);\n }\n\n string(): string {\n const length = this.u32();\n // `.slice()`, not the `.subarray()` `bytes()` hands out: a payload region lives in a\n // `SharedArrayBuffer`, and Chrome REFUSES a shared-backed view to `TextDecoder.decode()`\n // (\"The provided ArrayBufferView value must not be shared\" — the same `[AllowShared]` rule\n // that bites `crypto.getRandomValues`). Node accepts it, so a browser is the only place this\n // shows up, and it shows up as the SERVER rejecting every path-carrying request as malformed\n // and detaching the client. Paths are short; the copy costs nothing.\n const raw = this.bytes(length);\n try {\n return textDecoder.decode(raw.slice());\n } catch (cause) {\n throw new PayloadDecodeError(`a string is not valid UTF-8: ${String(cause)}`);\n }\n }\n\n #take(count: number): number {\n if (!Number.isSafeInteger(count) || count < 0) throw new PayloadDecodeError(`length ${count} is invalid`);\n if (count > this.remaining) throw new PayloadDecodeError(\"the payload ended mid-field\");\n const at = this.#cursor;\n this.#cursor += count;\n return at;\n }\n}\n\n/** Split an unsigned 64-bit result into the header's low/high `int32` pair. */\nexport function splitResult(value: bigint): { readonly lo: number; readonly hi: number } {\n if (value < 0n || value > 0xffff_ffff_ffff_ffffn) {\n throw new RangeError(`broker result ${value} is outside the unsigned 64-bit range`);\n }\n return { lo: Number(value & 0xffff_ffffn) | 0, hi: Number(value >> 32n) | 0 };\n}\n\n/** Rejoin the header's low/high `int32` pair into an unsigned 64-bit result. */\nexport function joinResult(lo: number, hi: number): bigint {\n return (BigInt(hi >>> 0) << 32n) | BigInt(lo >>> 0);\n}\n\n/** The stat shape both sides exchange; `bigint` everywhere the core is `bigint`. */\nexport interface BrokerStat {\n /** `symlink` only ever comes back from `lstat`; `size` is then the target's UTF-8 byte length. */\n readonly kind: \"directory\" | \"file\" | \"symlink\";\n readonly mode: number;\n readonly size: bigint;\n readonly atimeMs: bigint;\n readonly mtimeMs: bigint;\n readonly ctimeMs: bigint;\n}\n\nexport function writeStat(writer: PayloadWriter, stat: BrokerStat): void {\n writer.u8(\n stat.kind === \"directory\" ? STAT_KIND_DIRECTORY : stat.kind === \"symlink\" ? STAT_KIND_SYMLINK : STAT_KIND_FILE,\n );\n writer.u32(stat.mode);\n writer.u64(stat.size);\n writer.u64(stat.atimeMs);\n writer.u64(stat.mtimeMs);\n writer.u64(stat.ctimeMs);\n}\n\nexport function readStat(reader: PayloadReader): BrokerStat {\n const code = reader.u8();\n const kind = code === STAT_KIND_DIRECTORY ? \"directory\" : code === STAT_KIND_SYMLINK ? \"symlink\" : \"file\";\n return {\n kind,\n mode: reader.u32(),\n size: reader.u64(),\n atimeMs: reader.u64(),\n mtimeMs: reader.u64(),\n ctimeMs: reader.u64(),\n };\n}\n\n/** A channel's two shared buffers, in the form that survives `postMessage`. */\nexport interface RepackedChannelTransfer {\n readonly id: number;\n readonly channel: SharedArrayBuffer;\n readonly doorbell: SharedArrayBuffer;\n}\n\n/**\n * The shared word one blocking server loop waits on. Both sides hold the same buffer; a client only\n * ever rings it, and only the host that created it may ask the loop to stop.\n */\nexport class RepackedDoorbell {\n readonly buffer: SharedArrayBuffer;\n readonly #slots: Int32Array;\n\n private constructor(buffer: SharedArrayBuffer) {\n if (buffer.byteLength < DOORBELL_BYTES) {\n throw new RangeError(`a broker doorbell needs at least ${DOORBELL_BYTES} bytes`);\n }\n this.buffer = buffer;\n this.#slots = new Int32Array(buffer, 0, DOORBELL_SLOTS);\n }\n\n static create(): RepackedDoorbell {\n const doorbell = new RepackedDoorbell(new SharedArrayBuffer(DOORBELL_BYTES));\n Atomics.store(doorbell.#slots, DOORBELL_RUNNING, 1);\n return doorbell;\n }\n\n /** Rebuild the doorbell around a buffer that arrived over `postMessage`. */\n static attach(buffer: SharedArrayBuffer): RepackedDoorbell {\n return new RepackedDoorbell(buffer);\n }\n\n /** The value a server must observe BEFORE it scans, so a concurrent request cannot be missed. */\n ticket(): number {\n return Atomics.load(this.#slots, DOORBELL_TICKET);\n }\n\n /** Announce that some channel now holds a request. */\n ring(): void {\n Atomics.add(this.#slots, DOORBELL_TICKET, 1);\n Atomics.notify(this.#slots, DOORBELL_TICKET);\n }\n\n running(): boolean {\n return Atomics.load(this.#slots, DOORBELL_RUNNING) === 1;\n }\n\n /**\n * Ask a blocking `serveForever()` to return. This is the only way to stop it from another thread:\n * once inside the loop the server never reaches its own event loop, so `postMessage` cannot reach it.\n */\n requestStop(): void {\n Atomics.store(this.#slots, DOORBELL_RUNNING, 0);\n this.ring();\n }\n\n /** Undo a `requestStop()` so the same doorbell can drive another loop. */\n resume(): void {\n Atomics.store(this.#slots, DOORBELL_RUNNING, 1);\n }\n\n /** Block until the ticket leaves `observed`, or the timeout elapses. */\n wait(observed: number, timeoutMs: number): \"ok\" | \"not-equal\" | \"timed-out\" {\n return Atomics.wait(this.#slots, DOORBELL_TICKET, observed, timeoutMs);\n }\n\n /** The non-blocking form, for a host that must not park its thread. */\n waitAsync(observed: number, timeoutMs: number): Promise<\"ok\" | \"not-equal\" | \"timed-out\"> {\n const result = Atomics.waitAsync(this.#slots, DOORBELL_TICKET, observed, timeoutMs);\n return result.async ? result.value : Promise.resolve(result.value);\n }\n}\n\n/**\n * One client's request/response channel. Both the client and the server hold an instance over the\n * same `SharedArrayBuffer`; neither owns the memory, and nothing but the header words is atomic.\n */\nexport class RepackedChannel {\n readonly id: number;\n readonly buffer: SharedArrayBuffer;\n readonly doorbell: RepackedDoorbell;\n readonly header: Int32Array;\n readonly payload: Uint8Array;\n\n private constructor(id: number, buffer: SharedArrayBuffer, doorbell: RepackedDoorbell) {\n this.id = id;\n this.buffer = buffer;\n this.doorbell = doorbell;\n this.header = new Int32Array(buffer, 0, CHANNEL_HEADER_SLOTS);\n this.payload = new Uint8Array(buffer, CHANNEL_HEADER_BYTES);\n }\n\n static create(options: { id: number; doorbell: RepackedDoorbell; payloadBytes?: number }): RepackedChannel {\n const payloadBytes = options.payloadBytes ?? DEFAULT_PAYLOAD_BYTES;\n if (!Number.isSafeInteger(payloadBytes) || payloadBytes < MIN_PAYLOAD_BYTES) {\n throw new RangeError(`a broker channel payload must be at least ${MIN_PAYLOAD_BYTES} bytes`);\n }\n if (!Number.isSafeInteger(options.id) || options.id < 0) {\n throw new RangeError(\"a broker channel id must be a non-negative safe integer\");\n }\n const channel = new RepackedChannel(\n options.id,\n new SharedArrayBuffer(CHANNEL_HEADER_BYTES + payloadBytes),\n options.doorbell,\n );\n Atomics.store(channel.header, HEADER_PAYLOAD, payloadBytes);\n Atomics.store(channel.header, HEADER_STATE, STATE_IDLE);\n return channel;\n }\n\n /** Rebuild a channel around buffers that arrived over `postMessage`. */\n static attach(transfer: RepackedChannelTransfer): RepackedChannel {\n const doorbell = RepackedDoorbell.attach(transfer.doorbell);\n if (transfer.channel.byteLength < CHANNEL_HEADER_BYTES + MIN_PAYLOAD_BYTES) {\n throw new RangeError(\"the broker channel buffer is too small to be a channel\");\n }\n const channel = new RepackedChannel(transfer.id, transfer.channel, doorbell);\n const declared = Atomics.load(channel.header, HEADER_PAYLOAD);\n if (declared !== channel.payload.byteLength) {\n throw new RangeError(`the broker channel declares ${declared} payload bytes but carries a different region`);\n }\n return channel;\n }\n\n /** The shape to hand to `postMessage`. */\n transfer(): RepackedChannelTransfer {\n return { id: this.id, channel: this.buffer, doorbell: this.doorbell.buffer };\n }\n\n get payloadBytes(): number {\n return this.payload.byteLength;\n }\n\n state(): number {\n return Atomics.load(this.header, HEADER_STATE);\n }\n}\n\n/** The errno of a rejection, or `undefined` when it is not a plain file rejection. */\nexport function errnoOf(cause: unknown): number | undefined {\n return cause instanceof FsError ? cause.code : undefined;\n}\n\n/** The core error name behind a wire errno, or `undefined` for a code the core never produces. */\nexport function fsErrorNameOf(code: number): FsErrorName | undefined {\n for (const name of Object.keys(FS_ERRNO) as FsErrorName[]) {\n if (FS_ERRNO[name] === code) return name;\n }\n return undefined;\n}\n\n/** Readable form of a wire errno, for a message. */\nexport function errnoName(code: number): string {\n return fsErrorNameOf(code) ?? `errno ${code}`;\n}\n",
21
- "/**\n * `RepackedSyncBroker` — the single owner of one `RepackedVfs`, answering synchronous file requests\n * that arrive over `SharedArrayBuffer` channels.\n *\n * The broker is meant to be the only thing on its thread. A backend running wasm parks in futexes and\n * cannot await anything, so it publishes a request and blocks; the broker must therefore never block on\n * a promise between reading a request and writing its answer. Every handler here is synchronous, and\n * the store's own API is synchronous end to end.\n *\n * Three loop shapes are offered:\n *\n * - `serveForever()` parks the thread in `Atomics.wait` between requests. It is the shape for a\n * dedicated coordinator worker, and while it runs the thread never reaches its event loop — so\n * `postMessage` cannot reach it and every channel must be attached BEFORE entering it. Ask it to\n * return with `doorbell.requestStop()` from any thread holding the doorbell.\n * - `serve()` is the same loop built on `Atomics.waitAsync`, for a host that must keep its event loop\n * alive. Channels may be attached and detached at any time.\n * - `serveOnce()` scans every attached channel once and returns without waiting, for a host that\n * drives its own loop.\n *\n * Failure separation is the point of the class. A file rejection (`FsError`) becomes an errno in the\n * reply header and nothing else happens. A store failure becomes `FAULT_STORE` in the reply, and the\n * loop keeps running because every later request will fail the same way and the client decides what to\n * do. A protocol violation detaches only the offending client, with a logged reason.\n */\n\nimport { FS_ERRNO, FsError } from \"../core/errors\";\nimport type { RepackedFileSystem, RepackedStat } from \"../core/repacked-vfs\";\nimport {\n FAULT_DETACHED,\n FAULT_NONE,\n FAULT_PROTOCOL,\n FAULT_STORE,\n HEADER_ERRNO,\n HEADER_FAULT,\n HEADER_OPCODE,\n HEADER_REQUEST,\n HEADER_RESPONSE,\n HEADER_RESULT_HI,\n HEADER_RESULT_LO,\n HEADER_STATE,\n OPCODE_CLOSE,\n OPCODE_FSTAT,\n OPCODE_FSYNC,\n OPCODE_LSTAT,\n OPCODE_MKDIR,\n OPCODE_OPEN,\n OPCODE_READ,\n OPCODE_READDIR,\n OPCODE_READLINK,\n OPCODE_RENAME,\n OPCODE_RMDIR,\n OPCODE_SIZE,\n OPCODE_STAT,\n OPCODE_SYMLINK,\n OPCODE_TRUNCATE,\n OPCODE_UNLINK,\n OPCODE_WRITE,\n PayloadDecodeError,\n PayloadOverflowError,\n PayloadReader,\n PayloadWriter,\n READDIR_DONE,\n STATE_DETACHED,\n STATE_REQUEST,\n STATE_RESPONSE,\n isKnownOpcode,\n planOpen,\n splitResult,\n writeStat,\n} from \"./protocol\";\nimport type { RepackedChannel, RepackedDoorbell } from \"./protocol\";\n\n/** A descriptor the broker opened on behalf of one client. */\ninterface BrokerFd {\n /** The core's descriptor number. */\n readonly fd: number;\n /** The access the CLIENT asked for, which may be narrower than what the core descriptor grants. */\n readonly readable: boolean;\n readonly writable: boolean;\n}\n\ninterface AttachedClient {\n readonly channel: RepackedChannel;\n readonly fds: Map<number, BrokerFd>;\n}\n\n/** What a handler produced: an errno-only rejection, or a result plus optional response bytes. */\ninterface Answer {\n readonly errno: number;\n readonly result: bigint;\n readonly responseBytes: number;\n}\n\nconst OK: Answer = { errno: 0, result: 0n, responseBytes: 0 };\n\nfunction ok(result: bigint | number = 0n, responseBytes = 0): Answer {\n return { errno: 0, result: typeof result === \"bigint\" ? result : BigInt(result), responseBytes };\n}\n\n/** A client's request could not be understood; the client is detached, the loop survives. */\nclass ProtocolViolation extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ProtocolViolation\";\n }\n}\n\nexport interface RepackedSyncBrokerOptions {\n /**\n * The store this broker owns. Nothing else may hold it. A `RepackedVfs` is the one-store form; a\n * `MountedRepackedVfs` serves several stores as one tree, and the broker cannot tell them apart.\n */\n readonly vfs: RepackedFileSystem;\n /** The shared doorbell every attached channel rings. */\n readonly doorbell: RepackedDoorbell;\n /** The timestamp the broker supplies to every core call. Defaults to the wall clock. */\n readonly now?: () => bigint;\n /** Where a detach reason goes. Defaults to `console.warn`. */\n readonly log?: (message: string) => void;\n /**\n * How long one blocking iteration parks before re-scanning anyway. Defaults to 250 ms. The protocol\n * has no missed-wakeup window — the server observes the doorbell ticket BEFORE it scans, so a\n * request published during the scan makes the wait return `not-equal` at once — so this is purely a\n * heartbeat: it costs four idle wakeups a second and turns any future slip into a latency blip\n * instead of a permanently parked backend. `Infinity` makes the loop a pure park.\n */\n readonly pollIntervalMs?: number;\n}\n\nexport class RepackedSyncBroker {\n readonly doorbell: RepackedDoorbell;\n readonly #vfs: RepackedFileSystem;\n readonly #now: () => bigint;\n readonly #log: (message: string) => void;\n readonly #pollIntervalMs: number;\n readonly #clients = new Map<number, AttachedClient>();\n #serving = false;\n\n constructor(options: RepackedSyncBrokerOptions) {\n this.#vfs = options.vfs;\n this.doorbell = options.doorbell;\n this.#now = options.now ?? (() => BigInt(Date.now()));\n this.#log = options.log ?? ((message) => console.warn(message));\n this.#pollIntervalMs = options.pollIntervalMs ?? 250;\n }\n\n /** Channel ids the broker currently serves. */\n attachedIds(): number[] {\n return [...this.#clients.keys()].sort((left, right) => left - right);\n }\n\n /** Descriptors the broker currently holds for one client — the leak check after a detach. */\n openFdCount(channelId?: number): number {\n if (channelId === undefined) {\n let total = 0;\n for (const client of this.#clients.values()) total += client.fds.size;\n return total;\n }\n return this.#clients.get(channelId)?.fds.size ?? 0;\n }\n\n attach(channel: RepackedChannel): void {\n if (this.#clients.has(channel.id)) throw new Error(`broker channel ${channel.id} is already attached`);\n if (channel.doorbell.buffer !== this.doorbell.buffer) {\n throw new Error(`broker channel ${channel.id} rings a different doorbell`);\n }\n this.#clients.set(channel.id, { channel, fds: new Map() });\n }\n\n /**\n * Drop a client and close every descriptor it still holds. A backend that dies mid-query never leaks\n * a descriptor into the store, and the store's exclusive handles are released the moment the LAST\n * owner goes away rather than whenever a stale fd happens to be noticed.\n */\n detach(channel: RepackedChannel | number, reason = \"detached by the host\"): void {\n this.#detach(typeof channel === \"number\" ? channel : channel.id, reason, FAULT_DETACHED);\n }\n\n #detach(id: number, reason: string, fault: number): void {\n const client = this.#clients.get(id);\n if (client === undefined) return;\n this.#clients.delete(id);\n this.#releaseFds(client);\n const header = client.channel.header;\n Atomics.store(header, HEADER_FAULT, fault);\n Atomics.store(header, HEADER_ERRNO, 0);\n Atomics.store(header, HEADER_RESPONSE, 0);\n Atomics.store(header, HEADER_STATE, STATE_DETACHED);\n Atomics.notify(header, HEADER_STATE);\n this.#log(`repacked broker detached channel ${id}: ${reason}`);\n }\n\n /** Detach every client, closing all descriptors. The store itself is NOT closed. */\n detachAll(reason = \"broker shutting down\"): void {\n for (const id of this.attachedIds()) this.detach(id, reason);\n }\n\n /**\n * Scan every attached channel once and answer whatever is pending. Never blocks, never throws for a\n * file or store error. Returns how many requests were answered.\n */\n serveOnce(): number {\n let served = 0;\n for (const client of [...this.#clients.values()]) {\n if (Atomics.load(client.channel.header, HEADER_STATE) !== STATE_REQUEST) continue;\n this.#answer(client);\n served += 1;\n }\n return served;\n }\n\n /**\n * The blocking coordinator loop. Parks the thread in `Atomics.wait` on the doorbell between\n * requests, so this thread's event loop never runs: attach every channel before calling it, and stop\n * it with `doorbell.requestStop()` from another thread.\n */\n serveForever(): void {\n this.#enterLoop();\n try {\n while (this.doorbell.running()) {\n const observed = this.doorbell.ticket();\n if (this.serveOnce() > 0) continue;\n this.doorbell.wait(observed, this.#pollIntervalMs);\n }\n } finally {\n this.#serving = false;\n }\n }\n\n /**\n * The same loop on `Atomics.waitAsync`, for a host that must not park its thread — the tab's main\n * thread, or a worker that also has to receive `postMessage`. Channels may be attached and detached\n * while it runs. Resolves when `doorbell.requestStop()` is called.\n */\n async serve(): Promise<void> {\n this.#enterLoop();\n try {\n while (this.doorbell.running()) {\n const observed = this.doorbell.ticket();\n if (this.serveOnce() > 0) continue;\n await this.doorbell.waitAsync(observed, this.#pollIntervalMs);\n }\n } finally {\n this.#serving = false;\n }\n }\n\n #enterLoop(): void {\n if (this.#serving) throw new Error(\"the repacked broker is already serving\");\n this.#serving = true;\n }\n\n #releaseFds(client: AttachedClient): void {\n for (const entry of client.fds.values()) {\n try {\n this.#vfs.close(entry.fd);\n } catch {\n // A descriptor the store already dropped (or a poisoned store) must not stop the release of\n // the rest — the client is going away either way.\n }\n }\n client.fds.clear();\n }\n\n /** Read one pending request, run it, and publish the reply. Never throws. */\n #answer(client: AttachedClient): void {\n const header = client.channel.header;\n const opcode = Atomics.load(header, HEADER_OPCODE);\n const requestBytes = Atomics.load(header, HEADER_REQUEST);\n let fault = FAULT_NONE;\n let answer = OK;\n try {\n if (!isKnownOpcode(opcode)) throw new ProtocolViolation(`unknown opcode ${opcode}`);\n if (requestBytes < 0 || requestBytes > client.channel.payloadBytes) {\n throw new ProtocolViolation(`request length ${requestBytes} is outside the payload region`);\n }\n const reader = new PayloadReader(client.channel.payload, requestBytes);\n const writer = new PayloadWriter(client.channel.payload);\n answer = this.#dispatch(client, opcode, reader, writer);\n } catch (cause) {\n if (cause instanceof ProtocolViolation || cause instanceof PayloadDecodeError) {\n // Only the offending client goes; every other backend keeps its descriptors and its store.\n this.#detach(client.channel.id, cause.message, FAULT_PROTOCOL);\n return;\n }\n if (cause instanceof FsError) {\n answer = { errno: cause.code, result: 0n, responseBytes: 0 };\n } else {\n // Everything else — a poisoned store, a limit, a corrupt store, or a reply that did not fit\n // the client's own channel — is not a file rejection and not this client's fault. Report it\n // as a fault and keep the loop alive; a poisoned store answers every later request the same\n // way, and the client decides whether to give up.\n fault = FAULT_STORE;\n answer = this.#faultAnswer(client, cause);\n }\n }\n const { lo, hi } = splitResult(answer.result);\n Atomics.store(header, HEADER_ERRNO, answer.errno);\n Atomics.store(header, HEADER_RESULT_LO, lo);\n Atomics.store(header, HEADER_RESULT_HI, hi);\n Atomics.store(header, HEADER_RESPONSE, answer.responseBytes);\n Atomics.store(header, HEADER_FAULT, fault);\n Atomics.store(header, HEADER_STATE, STATE_RESPONSE);\n Atomics.notify(header, HEADER_STATE);\n }\n\n /** Put a fault message in the payload, truncating rather than overflowing a small channel. */\n #faultAnswer(client: AttachedClient, cause: unknown): Answer {\n const message = cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);\n const writer = new PayloadWriter(client.channel.payload);\n const room = client.channel.payloadBytes - 4;\n try {\n writer.string(message.length > room ? message.slice(0, Math.max(0, room)) : message);\n } catch {\n return { errno: 0, result: 0n, responseBytes: 0 };\n }\n return { errno: 0, result: 0n, responseBytes: writer.length };\n }\n\n #dispatch(client: AttachedClient, opcode: number, reader: PayloadReader, writer: PayloadWriter): Answer {\n switch (opcode) {\n case OPCODE_OPEN:\n return this.#open(client, reader);\n case OPCODE_CLOSE:\n return this.#close(client, reader);\n case OPCODE_READ:\n return this.#read(client, reader);\n case OPCODE_WRITE:\n return this.#write(client, reader);\n case OPCODE_FSYNC:\n return this.#fsync(client, reader);\n case OPCODE_FSTAT:\n return this.#stat(writer, this.#vfs.fstat(this.#fd(client, reader.u32()).fd));\n case OPCODE_STAT:\n return this.#stat(writer, this.#vfs.stat(reader.string()));\n case OPCODE_LSTAT:\n return this.#stat(writer, this.#vfs.lstat(reader.string()));\n case OPCODE_READDIR:\n return this.#readdir(reader, writer);\n case OPCODE_MKDIR:\n return this.#mkdir(reader);\n case OPCODE_RMDIR:\n this.#vfs.rmdir(reader.string(), this.#now());\n return OK;\n case OPCODE_UNLINK:\n this.#vfs.unlink(reader.string(), this.#now());\n return OK;\n case OPCODE_RENAME: {\n const oldPath = reader.string();\n this.#vfs.rename(oldPath, reader.string(), this.#now());\n return OK;\n }\n case OPCODE_TRUNCATE: {\n const path = reader.string();\n this.#vfs.truncate(path, reader.u64(), this.#now());\n return OK;\n }\n case OPCODE_SIZE:\n return this.#size(reader);\n case OPCODE_SYMLINK: {\n const target = reader.string();\n this.#vfs.symlink(target, reader.string(), this.#now());\n return OK;\n }\n case OPCODE_READLINK:\n return this.#readlink(reader, writer);\n default:\n throw new ProtocolViolation(`unhandled opcode ${opcode}`);\n }\n }\n\n #open(client: AttachedClient, reader: PayloadReader): Answer {\n const path = reader.string();\n const flags = reader.u32();\n const mode = reader.u32();\n const plan = planOpen(flags);\n const nowMs = this.#now();\n // `O_NOFOLLOW`: the core always follows a final link, so the refusal is proved here first. A\n // path that does not exist is not a link, and `O_CREAT` must still be free to create it.\n if (!plan.follow) {\n try {\n if (this.#vfs.lstat(path).kind === \"symlink\") {\n throw new FsError(\"ELOOP\", \"path is a symbolic link and O_NOFOLLOW was requested\", { path });\n }\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) throw cause;\n }\n }\n if (plan.requireExisting) this.#vfs.lstat(path);\n if (plan.truncateFirst) this.#vfs.truncate(path, 0n, nowMs);\n let fd: number;\n try {\n fd = this.#vfs.open(path, plan.coreFlags, mode, nowMs);\n } catch (cause) {\n if (plan.fallbackFlags === undefined || !(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) {\n throw cause;\n }\n fd = this.#vfs.open(path, plan.fallbackFlags, mode, nowMs);\n }\n client.fds.set(fd, { fd, readable: plan.readable, writable: plan.writable });\n return ok(fd);\n }\n\n #close(client: AttachedClient, reader: PayloadReader): Answer {\n const entry = this.#fd(client, reader.u32());\n this.#vfs.close(entry.fd);\n client.fds.delete(entry.fd);\n return OK;\n }\n\n #read(client: AttachedClient, reader: PayloadReader): Answer {\n const entry = this.#fd(client, reader.u32());\n if (!entry.readable) throw new FsError(\"EBADF\", \"descriptor was not opened for reading\");\n const hasPosition = reader.u8() === 1;\n const position = reader.u64();\n const length = reader.u32();\n if (length > client.channel.payloadBytes) {\n throw new ProtocolViolation(`read length ${length} exceeds the payload region`);\n }\n const target = client.channel.payload.subarray(0, length);\n const count = hasPosition\n ? this.#vfs.read(entry.fd, target, 0, length, position)\n : this.#vfs.read(entry.fd, target, 0, length);\n return ok(count, count);\n }\n\n #write(client: AttachedClient, reader: PayloadReader): Answer {\n const entry = this.#fd(client, reader.u32());\n if (!entry.writable) throw new FsError(\"EBADF\", \"descriptor was not opened for writing\");\n const hasPosition = reader.u8() === 1;\n const position = reader.u64();\n const length = reader.u32();\n const source = reader.bytes(length);\n const count = this.#vfs.write(entry.fd, source, 0, length, hasPosition ? position : undefined, this.#now());\n return ok(count);\n }\n\n /**\n * `fsync` is store-wide. The core's only durability primitive is `strictSync()`, which flushes the\n * arena and then the active metadata log, so a successful `fsync` promises that EVERY byte written\n * through this broker by ANY client before the call returned is recoverable — not just this\n * descriptor's. WASI `fd_sync` and `fd_datasync` both map to it; the fd is carried only so the call\n * still fails with `EBADF` on a descriptor the client does not own, exactly as `fd_sync` must.\n */\n #fsync(client: AttachedClient, reader: PayloadReader): Answer {\n if (reader.u8() === 1) this.#fd(client, reader.u32());\n this.#vfs.strictSync();\n return OK;\n }\n\n #stat(writer: PayloadWriter, stat: RepackedStat): Answer {\n writeStat(writer, stat);\n return ok(stat.size, writer.length);\n }\n\n /**\n * One page of a directory listing. The cursor is an index into the store's own sorted listing, which\n * the store recomputes on every call — so, exactly as POSIX `readdir` allows, a listing spread over\n * several pages is not an atomic snapshot of the directory.\n */\n #readdir(reader: PayloadReader, writer: PayloadWriter): Answer {\n const path = reader.string();\n const cursor = reader.u32();\n const names = this.#vfs.readdir(path);\n if (cursor > names.length) throw new ProtocolViolation(`readdir cursor ${cursor} is past the listing`);\n // Reserve the two counters written after the entries are known to fit.\n const countAt = writer.length;\n writer.u32(0);\n writer.i32(READDIR_DONE);\n let emitted = 0;\n let next = READDIR_DONE;\n for (let index = cursor; index < names.length; index += 1) {\n const before = writer.length;\n try {\n writer.string(names[index]!);\n } catch (cause) {\n if (!(cause instanceof PayloadOverflowError)) throw cause;\n writer.rewind(before);\n if (emitted === 0) throw cause; // one name alone cannot fit: the channel is too small\n next = index;\n break;\n }\n emitted += 1;\n }\n const counters = writer.patch(countAt, 8);\n counters.setUint32(0, emitted, true);\n counters.setInt32(4, next, true);\n return ok(emitted, writer.length);\n }\n\n #mkdir(reader: PayloadReader): Answer {\n const path = reader.string();\n const recursive = reader.u8() === 1;\n const mode = reader.u32();\n this.#vfs.mkdir(path, { recursive, mode, nowMs: this.#now() });\n return OK;\n }\n\n /** The target of one symbolic link. The result is the target's byte length; the payload is it. */\n #readlink(reader: PayloadReader, writer: PayloadWriter): Answer {\n writer.string(this.#vfs.readlink(reader.string()));\n return ok(writer.length, writer.length);\n }\n\n #size(reader: PayloadReader): Answer {\n const stat = this.#vfs.stat(reader.string());\n if (stat.kind !== \"file\") throw new FsError(\"EISDIR\", \"size is a file query\");\n return ok(stat.size);\n }\n\n /**\n * Resolve a descriptor the CLIENT owns. A descriptor that belongs to another client is `EBADF`, not\n * a protocol violation: fd numbers are per-store, so a client guessing one is an ordinary bad-fd\n * mistake and never a reason to reach into another backend's files.\n */\n #fd(client: AttachedClient, fd: number): BrokerFd {\n const entry = client.fds.get(fd);\n if (entry === undefined) throw new FsError(\"EBADF\", `descriptor ${fd} is not owned by this client`);\n return entry;\n }\n}\n",
22
- "/**\n * `RepackedSyncClient` — the backend side of the synchronous broker.\n *\n * Every method blocks the calling thread in `Atomics.wait` until the coordinator answers, which is the\n * whole point: a thread running wasm parks in futexes and can never observe a promise, so the file\n * layer under it has to be synchronous. Nothing here is async, and nothing here knows about wasm.\n *\n * ## What throws and what does not\n *\n * A FILE rejection is data: every method returns `{ errno }` (0 on success) with whatever else the\n * operation produced. Callers map the errno straight into their own ABI — the values are WASI preview1\n * errno numbers already.\n *\n * A TRANSPORT failure throws, because there is no answer to return: the server detached this client,\n * the client sent something the server refused, the server never replied inside the timeout, or the\n * store itself failed. Those are `RepackedBrokerTransportError` and `RepackedBrokerStoreError`.\n *\n * ## Mapping onto WASI preview1\n *\n * The method set is shaped so a preview1 adapter is a straight translation, with no state of its own\n * beyond the preopen table:\n *\n * path_open → open(path, flags, mode) (flags are the POSIX bits, see protocol)\n * fd_close → close(fd)\n * fd_read → read(fd, length) (no position: the store's own cursor)\n * fd_pread → read(fd, length, position)\n * fd_write → write(fd, bytes)\n * fd_pwrite → write(fd, bytes, position)\n * fd_seek → resolved by the caller; the store's cursor moves on cursor reads/writes\n * fd_sync / fd_datasync → fsync(fd) (store-wide; see the server's note)\n * fd_filestat_get → fstat(fd)\n * path_filestat_get → stat(path) / lstat(path)\n * fd_readdir → readdir(path) or readdirPage(path, cursor) for the cookie form\n * path_create_directory → mkdir(path)\n * path_remove_directory → rmdir(path)\n * path_unlink_file → unlink(path)\n * path_rename → rename(oldPath, newPath)\n * path_symlink → symlink(target, path) (targets are ABSOLUTE; see the core)\n * path_readlink → readlink(path)\n * fd_filestat_set_size → truncate(path, size) — the core resizes by PATH only, so the adapter\n * keeps the path it opened each fd with and resolves it here\n *\n * Reads and writes larger than the channel's payload region are split transparently; a caller never\n * has to know the channel size.\n */\n\nimport { FsError } from \"../core/errors\";\nimport {\n FAULT_NONE,\n FAULT_PROTOCOL,\n FAULT_STORE,\n HEADER_ERRNO,\n HEADER_FAULT,\n HEADER_OPCODE,\n HEADER_REQUEST,\n HEADER_RESPONSE,\n HEADER_RESULT_HI,\n HEADER_RESULT_LO,\n HEADER_SEQUENCE,\n HEADER_STATE,\n OPCODE_CLOSE,\n OPCODE_FSTAT,\n OPCODE_FSYNC,\n OPCODE_LSTAT,\n OPCODE_MKDIR,\n OPCODE_OPEN,\n OPCODE_READ,\n OPCODE_READDIR,\n OPCODE_READLINK,\n OPCODE_RENAME,\n OPCODE_RMDIR,\n OPCODE_SIZE,\n OPCODE_STAT,\n OPCODE_SYMLINK,\n OPCODE_TRUNCATE,\n OPCODE_UNLINK,\n OPCODE_WRITE,\n PayloadReader,\n PayloadWriter,\n READDIR_DONE,\n STATE_DETACHED,\n STATE_IDLE,\n STATE_REQUEST,\n STATE_RESPONSE,\n errnoName,\n fsErrorNameOf,\n joinResult,\n readStat,\n} from \"./protocol\";\nimport type { BrokerStat, RepackedChannel } from \"./protocol\";\n\n/** The transport failed: there is no answer, and this client can no longer make progress. */\nexport class RepackedBrokerTransportError extends Error {\n readonly brokerCode: \"detached\" | \"protocol\" | \"timeout\";\n\n constructor(brokerCode: \"detached\" | \"protocol\" | \"timeout\", message: string) {\n super(message);\n this.name = \"RepackedBrokerTransportError\";\n this.brokerCode = brokerCode;\n }\n}\n\n/** The store behind the broker failed. Not a file rejection, and not this client's mistake. */\nexport class RepackedBrokerStoreError extends Error {\n readonly brokerCode = \"store\";\n\n constructor(message: string) {\n super(`the repacked store behind the broker failed: ${message}`);\n this.name = \"RepackedBrokerStoreError\";\n }\n}\n\n/** Every result carries an errno; 0 means the operation succeeded. */\nexport interface BrokerResult {\n readonly errno: number;\n}\n\nexport interface BrokerOpenResult extends BrokerResult {\n readonly fd: number;\n}\n\nexport interface BrokerCountResult extends BrokerResult {\n /** Bytes actually transferred. Short of the request means end-of-file (read) or a store limit (write). */\n readonly count: number;\n}\n\nexport interface BrokerReadResult extends BrokerCountResult {\n readonly bytes: Uint8Array;\n}\n\nexport interface BrokerStatResult extends BrokerResult {\n readonly stat: BrokerStat | undefined;\n}\n\nexport interface BrokerSizeResult extends BrokerResult {\n readonly size: bigint;\n}\n\nexport interface BrokerReaddirResult extends BrokerResult {\n readonly entries: readonly string[];\n}\n\nexport interface BrokerReadlinkResult extends BrokerResult {\n /** The link's target, or `undefined` when the call was rejected. */\n readonly target: string | undefined;\n}\n\nexport interface BrokerReaddirPageResult extends BrokerReaddirResult {\n /** The cursor to resume from, or `undefined` when the listing is complete. */\n readonly nextCursor: number | undefined;\n}\n\nexport interface RepackedSyncClientOptions {\n /**\n * How long one request may go unanswered before the client gives up and throws. A dead coordinator\n * would otherwise park this thread forever, which is worse than a loud failure. Pass `Infinity` for\n * a host that genuinely prefers to wait.\n */\n readonly requestTimeoutMs?: number;\n}\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** The fixed bytes a read/write request spends before its data: fd + hasPosition + position + length. */\nconst TRANSFER_OVERHEAD_BYTES = 4 + 1 + 8 + 4;\n\nexport class RepackedSyncClient {\n readonly channel: RepackedChannel;\n readonly #timeoutMs: number;\n readonly #reply: Uint8Array;\n #sequence = 0;\n\n constructor(channel: RepackedChannel, options: RepackedSyncClientOptions = {}) {\n this.channel = channel;\n this.#timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n // A scratch copy of the reply region: the payload is shared memory the server reuses on the very\n // next request, so nothing handed to a caller may point into it.\n this.#reply = new Uint8Array(channel.payloadBytes);\n }\n\n /** The largest single read or write that fits one request. Reads/writes above it are chunked. */\n get maxTransferBytes(): number {\n return this.channel.payloadBytes - TRANSFER_OVERHEAD_BYTES;\n }\n\n open(path: string, flags: number, mode = 0o100666): BrokerOpenResult {\n const reply = this.#call(OPCODE_OPEN, (writer) => {\n writer.string(path);\n writer.u32(flags);\n writer.u32(mode);\n });\n return { errno: reply.errno, fd: reply.errno === 0 ? Number(reply.result) : -1 };\n }\n\n close(fd: number): BrokerResult {\n return { errno: this.#call(OPCODE_CLOSE, (writer) => writer.u32(fd)).errno };\n }\n\n /**\n * Read up to `length` bytes. With no `position` the store's own descriptor cursor is used and\n * advances; with a `position` the cursor is untouched (`fd_pread`). A result shorter than `length`\n * means end-of-file, never a partial transport.\n */\n read(fd: number, length: number, position?: bigint): BrokerReadResult {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new RangeError(\"a broker read length must be a non-negative safe integer\");\n }\n const output = new Uint8Array(length);\n let filled = 0;\n let errno = 0;\n while (filled < length) {\n const want = Math.min(length - filled, this.maxTransferBytes);\n const at = position === undefined ? undefined : position + BigInt(filled);\n const reply = this.#call(OPCODE_READ, (writer) => {\n writer.u32(fd);\n writer.u8(at === undefined ? 0 : 1);\n writer.u64(at ?? 0n);\n writer.u32(want);\n });\n if (reply.errno !== 0) {\n errno = reply.errno;\n break;\n }\n output.set(reply.bytes, filled);\n filled += reply.bytes.byteLength;\n if (reply.bytes.byteLength < want) break; // end-of-file\n }\n // A rejection part-way through still reports what already transferred, as a short read does.\n return { errno, count: filled, bytes: output.subarray(0, filled) };\n }\n\n /**\n * Write `bytes`. With no `position` the store's own descriptor cursor is used and advances; with a\n * `position` the cursor is untouched (`fd_pwrite`). A descriptor opened with `O_APPEND` always\n * writes at end-of-file and ignores `position`, exactly as POSIX requires.\n */\n write(fd: number, bytes: Uint8Array, position?: bigint): BrokerCountResult {\n let written = 0;\n let errno = 0;\n while (written < bytes.byteLength) {\n const chunk = bytes.subarray(written, written + Math.min(bytes.byteLength - written, this.maxTransferBytes));\n const at = position === undefined ? undefined : position + BigInt(written);\n const reply = this.#call(OPCODE_WRITE, (writer) => {\n writer.u32(fd);\n writer.u8(at === undefined ? 0 : 1);\n writer.u64(at ?? 0n);\n writer.u32(chunk.byteLength);\n writer.bytes(chunk);\n });\n if (reply.errno !== 0) {\n errno = reply.errno;\n break;\n }\n const count = Number(reply.result);\n written += count;\n if (count < chunk.byteLength) break; // the store admitted less than asked; stop rather than spin\n }\n return { errno, count: written };\n }\n\n /**\n * Flush the store. Durability is STORE-WIDE, not per-descriptor: on success every byte written\n * through this broker by any client before the call returned is recoverable. `fd` is validated so\n * the call still rejects a descriptor this client does not own.\n */\n fsync(fd?: number): BrokerResult {\n return {\n errno: this.#call(OPCODE_FSYNC, (writer) => {\n writer.u8(fd === undefined ? 0 : 1);\n writer.u32(fd ?? 0);\n }).errno,\n };\n }\n\n fstat(fd: number): BrokerStatResult {\n return this.#statCall(OPCODE_FSTAT, (writer) => writer.u32(fd));\n }\n\n stat(path: string): BrokerStatResult {\n return this.#statCall(OPCODE_STAT, (writer) => writer.string(path));\n }\n\n /** Reports the LINK itself when the final component is one; `stat` follows it instead. */\n lstat(path: string): BrokerStatResult {\n return this.#statCall(OPCODE_LSTAT, (writer) => writer.string(path));\n }\n\n /**\n * Create a symbolic link at `path` pointing at `target`. Targets are ABSOLUTE — the store refuses\n * a relative one with `EINVAL` rather than reinterpreting it against the link's directory.\n */\n symlink(target: string, path: string): BrokerResult {\n return {\n errno: this.#call(OPCODE_SYMLINK, (writer) => {\n writer.string(target);\n writer.string(path);\n }).errno,\n };\n }\n\n /** The target of the symbolic link at `path`. `EINVAL` when the path is not a link. */\n readlink(path: string): BrokerReadlinkResult {\n const reply = this.#call(OPCODE_READLINK, (writer) => writer.string(path));\n if (reply.errno !== 0) return { errno: reply.errno, target: undefined };\n return { errno: 0, target: new PayloadReader(reply.bytes, reply.bytes.byteLength).string() };\n }\n\n /** The complete listing, paged transparently over as many requests as the channel needs. */\n readdir(path: string): BrokerReaddirResult {\n const entries: string[] = [];\n let cursor: number | undefined = 0;\n while (cursor !== undefined) {\n const page: BrokerReaddirPageResult = this.readdirPage(path, cursor);\n if (page.errno !== 0) return { errno: page.errno, entries: [] };\n entries.push(...page.entries);\n cursor = page.nextCursor;\n }\n return { errno: 0, entries };\n }\n\n /**\n * One page of a listing, for a caller that owns its own cookie (WASI `fd_readdir`). The cursor is an\n * index into the store's sorted listing, recomputed per call — a paged listing is therefore not an\n * atomic snapshot, which is exactly what POSIX `readdir` allows.\n */\n readdirPage(path: string, cursor = 0): BrokerReaddirPageResult {\n const reply = this.#call(OPCODE_READDIR, (writer) => {\n writer.string(path);\n writer.u32(cursor);\n });\n if (reply.errno !== 0) return { errno: reply.errno, entries: [], nextCursor: undefined };\n const reader = new PayloadReader(reply.bytes, reply.bytes.byteLength);\n const count = reader.u32();\n const next = reader.i32();\n const entries: string[] = [];\n for (let index = 0; index < count; index += 1) entries.push(reader.string());\n return { errno: 0, entries, nextCursor: next === READDIR_DONE ? undefined : next };\n }\n\n mkdir(path: string, options: { recursive?: boolean; mode?: number } = {}): BrokerResult {\n return {\n errno: this.#call(OPCODE_MKDIR, (writer) => {\n writer.string(path);\n writer.u8(options.recursive === true ? 1 : 0);\n writer.u32(options.mode ?? 0o40777);\n }).errno,\n };\n }\n\n rmdir(path: string): BrokerResult {\n return { errno: this.#call(OPCODE_RMDIR, (writer) => writer.string(path)).errno };\n }\n\n unlink(path: string): BrokerResult {\n return { errno: this.#call(OPCODE_UNLINK, (writer) => writer.string(path)).errno };\n }\n\n rename(oldPath: string, newPath: string): BrokerResult {\n return {\n errno: this.#call(OPCODE_RENAME, (writer) => {\n writer.string(oldPath);\n writer.string(newPath);\n }).errno,\n };\n }\n\n /**\n * Resize by PATH. The core store has no resize-by-descriptor, so a WASI `fd_filestat_set_size`\n * adapter keeps the path each fd was opened with and calls this. Nothing is lost by that: the store\n * has no hard links, and a descriptor whose path was unlinked meanwhile is an orphan the core keeps\n * readable but no longer resizes.\n */\n truncate(path: string, size: bigint): BrokerResult {\n return {\n errno: this.#call(OPCODE_TRUNCATE, (writer) => {\n writer.string(path);\n writer.u64(size);\n }).errno,\n };\n }\n\n /** The size of one file, without the rest of a stat. `EISDIR` for a directory. */\n size(path: string): BrokerSizeResult {\n const reply = this.#call(OPCODE_SIZE, (writer) => writer.string(path));\n return { errno: reply.errno, size: reply.errno === 0 ? reply.result : 0n };\n }\n\n #statCall(opcode: number, encode: (writer: PayloadWriter) => void): BrokerStatResult {\n const reply = this.#call(opcode, encode);\n if (reply.errno !== 0) return { errno: reply.errno, stat: undefined };\n return { errno: 0, stat: readStat(new PayloadReader(reply.bytes, reply.bytes.byteLength)) };\n }\n\n /**\n * Publish one request, ring the doorbell, and park until the server answers. The returned `bytes`\n * are a private copy: the shared payload is reused by the next request.\n */\n #call(\n opcode: number,\n encode: (writer: PayloadWriter) => void,\n ): { readonly errno: number; readonly result: bigint; readonly bytes: Uint8Array } {\n const header = this.channel.header;\n const state = Atomics.load(header, HEADER_STATE);\n if (state === STATE_DETACHED) {\n throw new RepackedBrokerTransportError(\"detached\", \"the repacked broker detached this client\");\n }\n if (state === STATE_REQUEST) {\n throw new RepackedBrokerTransportError(\"protocol\", \"a repacked broker request is already in flight\");\n }\n const writer = new PayloadWriter(this.channel.payload);\n encode(writer);\n this.#sequence = (this.#sequence + 1) | 0;\n Atomics.store(header, HEADER_SEQUENCE, this.#sequence);\n Atomics.store(header, HEADER_OPCODE, opcode);\n Atomics.store(header, HEADER_REQUEST, writer.length);\n Atomics.store(header, HEADER_RESPONSE, 0);\n Atomics.store(header, HEADER_ERRNO, 0);\n Atomics.store(header, HEADER_FAULT, FAULT_NONE);\n // Publishing the state is the release edge for every payload byte written above; the doorbell is\n // the only wakeup path, so nothing waits on this word from the server side.\n Atomics.store(header, HEADER_STATE, STATE_REQUEST);\n this.channel.doorbell.ring();\n\n while (Atomics.load(header, HEADER_STATE) === STATE_REQUEST) {\n const outcome = Atomics.wait(header, HEADER_STATE, STATE_REQUEST, this.#timeoutMs);\n if (outcome === \"timed-out\" && Atomics.load(header, HEADER_STATE) === STATE_REQUEST) {\n throw new RepackedBrokerTransportError(\n \"timeout\",\n `the repacked broker did not answer opcode ${opcode} within ${this.#timeoutMs} ms`,\n );\n }\n }\n\n const responseBytes = Atomics.load(header, HEADER_RESPONSE);\n const fault = Atomics.load(header, HEADER_FAULT);\n const errno = Atomics.load(header, HEADER_ERRNO);\n const result = joinResult(Atomics.load(header, HEADER_RESULT_LO), Atomics.load(header, HEADER_RESULT_HI));\n let bytes: Uint8Array = new Uint8Array();\n if (responseBytes > 0 && responseBytes <= this.channel.payloadBytes) {\n this.#reply.set(this.channel.payload.subarray(0, responseBytes));\n bytes = this.#reply.subarray(0, responseBytes);\n }\n if (Atomics.load(header, HEADER_STATE) === STATE_DETACHED) {\n throw new RepackedBrokerTransportError(\n fault === FAULT_PROTOCOL ? \"protocol\" : \"detached\",\n fault === FAULT_PROTOCOL\n ? `the repacked broker rejected opcode ${opcode} as a protocol violation and detached this client`\n : \"the repacked broker detached this client\",\n );\n }\n if (Atomics.load(header, HEADER_STATE) !== STATE_RESPONSE) {\n throw new RepackedBrokerTransportError(\"protocol\", \"the repacked broker left the channel in an unknown state\");\n }\n Atomics.store(header, HEADER_STATE, STATE_IDLE);\n if (fault === FAULT_STORE) throw new RepackedBrokerStoreError(this.#faultMessage(bytes));\n if (fault !== FAULT_NONE) {\n throw new RepackedBrokerTransportError(\"protocol\", `the repacked broker reported fault ${fault}`);\n }\n return { errno, result, bytes };\n }\n\n #faultMessage(bytes: Uint8Array): string {\n if (bytes.byteLength === 0) return \"no detail was reported\";\n try {\n return new PayloadReader(bytes, bytes.byteLength).string();\n } catch {\n return \"the fault detail was malformed\";\n }\n }\n}\n\n/**\n * Turn a broker result into the throw the core store would have produced, for a caller that prefers\n * exceptions to errnos. The rebuilt `FsError` carries the same numeric `code` the broker reported.\n */\nexport function throwOnErrno(result: BrokerResult, operation: string, path?: string): void {\n if (result.errno === 0) return;\n const name = fsErrorNameOf(result.errno);\n const detail = `${operation} failed with ${errnoName(result.errno)}`;\n if (name === undefined) throw new RepackedBrokerTransportError(\"protocol\", `${detail} (unknown to the core)`);\n throw new FsError(name, detail, path === undefined ? { operation } : { operation, path });\n}\n",
21
+ "/**\n * `RepackedSyncBroker` — the single owner of one `RepackedVfs`, answering synchronous file requests\n * that arrive over `SharedArrayBuffer` channels.\n *\n * The broker is meant to be the only thing on its thread. A backend running wasm parks in futexes and\n * cannot await anything, so it publishes a request and blocks; the broker must therefore never block on\n * a promise between reading a request and writing its answer. Every handler here is synchronous, and\n * the store's own API is synchronous end to end.\n *\n * Three loop shapes are offered:\n *\n * - `serveForever()` parks the thread in `Atomics.wait` between requests. It is the shape for a\n * dedicated coordinator worker, and while it runs the thread never reaches its event loop — so\n * `postMessage` cannot reach it and every channel must be attached BEFORE entering it. Ask it to\n * return with `doorbell.requestStop()` from any thread holding the doorbell.\n * - `serve()` is the same loop built on `Atomics.waitAsync`, for a host that must keep its event loop\n * alive. Channels may be attached and detached at any time.\n * - `serveOnce()` scans every attached channel once and returns without waiting, for a host that\n * drives its own loop.\n *\n * Failure separation is the point of the class. A file rejection (`FsError`) becomes an errno in the\n * reply header and nothing else happens. A store failure becomes `FAULT_STORE` in the reply, and the\n * loop keeps running because every later request will fail the same way and the client decides what to\n * do. A protocol violation detaches only the offending client, with a logged reason.\n */\n\nimport { FS_ERRNO, FsError } from \"../core/errors\";\nimport type { RepackedFileSystem, RepackedStat } from \"../core/repacked-vfs\";\nimport {\n FAULT_DETACHED,\n FAULT_NONE,\n FAULT_PROTOCOL,\n FAULT_STORE,\n HEADER_ERRNO,\n HEADER_FAULT,\n HEADER_OPCODE,\n HEADER_REQUEST,\n HEADER_RESPONSE,\n HEADER_RESULT_HI,\n HEADER_RESULT_LO,\n HEADER_STATE,\n isKnownOpcode,\n OPCODE_CLOSE,\n OPCODE_FSTAT,\n OPCODE_FSYNC,\n OPCODE_LSTAT,\n OPCODE_MKDIR,\n OPCODE_OPEN,\n OPCODE_READ,\n OPCODE_READDIR,\n OPCODE_READLINK,\n OPCODE_RENAME,\n OPCODE_RMDIR,\n OPCODE_SIZE,\n OPCODE_STAT,\n OPCODE_SYMLINK,\n OPCODE_TRUNCATE,\n OPCODE_UNLINK,\n OPCODE_WRITE,\n PayloadDecodeError,\n PayloadOverflowError,\n PayloadReader,\n PayloadWriter,\n planOpen,\n READDIR_DONE,\n splitResult,\n STATE_DETACHED,\n STATE_REQUEST,\n STATE_RESPONSE,\n writeStat,\n} from \"./protocol\";\nimport type { RepackedChannel, RepackedDoorbell } from \"./protocol\";\n\n/** A descriptor the broker opened on behalf of one client. */\ninterface BrokerFd {\n /** The core's descriptor number. */\n readonly fd: number;\n /** The access the CLIENT asked for, which may be narrower than what the core descriptor grants. */\n readonly readable: boolean;\n readonly writable: boolean;\n}\n\ninterface AttachedClient {\n readonly channel: RepackedChannel;\n readonly fds: Map<number, BrokerFd>;\n}\n\n/** What a handler produced: an errno-only rejection, or a result plus optional response bytes. */\ninterface Answer {\n readonly errno: number;\n readonly result: bigint;\n readonly responseBytes: number;\n}\n\nconst OK: Answer = { errno: 0, result: 0n, responseBytes: 0 };\n\nfunction ok(result: bigint | number = 0n, responseBytes = 0): Answer {\n return { errno: 0, result: typeof result === \"bigint\" ? result : BigInt(result), responseBytes };\n}\n\n/** A client's request could not be understood; the client is detached, the loop survives. */\nclass ProtocolViolation extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ProtocolViolation\";\n }\n}\n\nexport interface RepackedSyncBrokerOptions {\n /**\n * The store this broker owns. Nothing else may hold it. A `RepackedVfs` is the one-store form; a\n * `MountedRepackedVfs` serves several stores as one tree, and the broker cannot tell them apart.\n */\n readonly vfs: RepackedFileSystem;\n /** The shared doorbell every attached channel rings. */\n readonly doorbell: RepackedDoorbell;\n /** The timestamp the broker supplies to every core call. Defaults to the wall clock. */\n readonly now?: () => bigint;\n /** Where a detach reason goes. Defaults to `console.warn`. */\n readonly log?: (message: string) => void;\n /**\n * How long one blocking iteration parks before re-scanning anyway. Defaults to 250 ms. The protocol\n * has no missed-wakeup window — the server observes the doorbell ticket BEFORE it scans, so a\n * request published during the scan makes the wait return `not-equal` at once — so this is purely a\n * heartbeat: it costs four idle wakeups a second and turns any future slip into a latency blip\n * instead of a permanently parked backend. `Infinity` makes the loop a pure park.\n */\n readonly pollIntervalMs?: number;\n}\n\nexport class RepackedSyncBroker {\n readonly doorbell: RepackedDoorbell;\n readonly #vfs: RepackedFileSystem;\n readonly #now: () => bigint;\n readonly #log: (message: string) => void;\n readonly #pollIntervalMs: number;\n readonly #clients = new Map<number, AttachedClient>();\n #serving = false;\n\n constructor(options: RepackedSyncBrokerOptions) {\n this.#vfs = options.vfs;\n this.doorbell = options.doorbell;\n this.#now = options.now ?? (() => BigInt(Date.now()));\n this.#log = options.log ?? ((message) => console.warn(message));\n this.#pollIntervalMs = options.pollIntervalMs ?? 250;\n }\n\n /** Channel ids the broker currently serves. */\n attachedIds(): number[] {\n return [...this.#clients.keys()].sort((left, right) => left - right);\n }\n\n /** Descriptors the broker currently holds for one client — the leak check after a detach. */\n openFdCount(channelId?: number): number {\n if (channelId === undefined) {\n let total = 0;\n for (const client of this.#clients.values()) total += client.fds.size;\n return total;\n }\n return this.#clients.get(channelId)?.fds.size ?? 0;\n }\n\n attach(channel: RepackedChannel): void {\n if (this.#clients.has(channel.id)) throw new Error(`broker channel ${channel.id} is already attached`);\n if (channel.doorbell.buffer !== this.doorbell.buffer) {\n throw new Error(`broker channel ${channel.id} rings a different doorbell`);\n }\n this.#clients.set(channel.id, { channel, fds: new Map() });\n }\n\n /**\n * Drop a client and close every descriptor it still holds. A backend that dies mid-query never leaks\n * a descriptor into the store, and the store's exclusive handles are released the moment the LAST\n * owner goes away rather than whenever a stale fd happens to be noticed.\n */\n detach(channel: RepackedChannel | number, reason = \"detached by the host\"): void {\n this.#detach(typeof channel === \"number\" ? channel : channel.id, reason, FAULT_DETACHED);\n }\n\n #detach(id: number, reason: string, fault: number): void {\n const client = this.#clients.get(id);\n if (client === undefined) return;\n this.#clients.delete(id);\n this.#releaseFds(client);\n const header = client.channel.header;\n Atomics.store(header, HEADER_FAULT, fault);\n Atomics.store(header, HEADER_ERRNO, 0);\n Atomics.store(header, HEADER_RESPONSE, 0);\n Atomics.store(header, HEADER_STATE, STATE_DETACHED);\n Atomics.notify(header, HEADER_STATE);\n this.#log(`repacked broker detached channel ${id}: ${reason}`);\n }\n\n /** Detach every client, closing all descriptors. The store itself is NOT closed. */\n detachAll(reason = \"broker shutting down\"): void {\n for (const id of this.attachedIds()) this.detach(id, reason);\n }\n\n /**\n * Scan every attached channel once and answer whatever is pending. Never blocks, never throws for a\n * file or store error. Returns how many requests were answered.\n */\n serveOnce(): number {\n let served = 0;\n for (const client of [...this.#clients.values()]) {\n if (Atomics.load(client.channel.header, HEADER_STATE) !== STATE_REQUEST) continue;\n this.#answer(client);\n served += 1;\n }\n return served;\n }\n\n /**\n * The blocking coordinator loop. Parks the thread in `Atomics.wait` on the doorbell between\n * requests, so this thread's event loop never runs: attach every channel before calling it, and stop\n * it with `doorbell.requestStop()` from another thread.\n */\n serveForever(): void {\n this.#enterLoop();\n try {\n while (this.doorbell.running()) {\n const observed = this.doorbell.ticket();\n if (this.serveOnce() > 0) continue;\n this.doorbell.wait(observed, this.#pollIntervalMs);\n }\n } finally {\n this.#serving = false;\n }\n }\n\n /**\n * The same loop on `Atomics.waitAsync`, for a host that must not park its thread — the tab's main\n * thread, or a worker that also has to receive `postMessage`. Channels may be attached and detached\n * while it runs. Resolves when `doorbell.requestStop()` is called.\n */\n async serve(): Promise<void> {\n this.#enterLoop();\n try {\n while (this.doorbell.running()) {\n const observed = this.doorbell.ticket();\n if (this.serveOnce() > 0) continue;\n await this.doorbell.waitAsync(observed, this.#pollIntervalMs);\n }\n } finally {\n this.#serving = false;\n }\n }\n\n #enterLoop(): void {\n if (this.#serving) throw new Error(\"the repacked broker is already serving\");\n this.#serving = true;\n }\n\n #releaseFds(client: AttachedClient): void {\n for (const entry of client.fds.values()) {\n try {\n this.#vfs.close(entry.fd);\n } catch {\n // A descriptor the store already dropped (or a poisoned store) must not stop the release of\n // the rest — the client is going away either way.\n }\n }\n client.fds.clear();\n }\n\n /** Read one pending request, run it, and publish the reply. Never throws. */\n #answer(client: AttachedClient): void {\n const header = client.channel.header;\n const opcode = Atomics.load(header, HEADER_OPCODE);\n const requestBytes = Atomics.load(header, HEADER_REQUEST);\n let fault = FAULT_NONE;\n let answer = OK;\n try {\n if (!isKnownOpcode(opcode)) throw new ProtocolViolation(`unknown opcode ${opcode}`);\n if (requestBytes < 0 || requestBytes > client.channel.payloadBytes) {\n throw new ProtocolViolation(`request length ${requestBytes} is outside the payload region`);\n }\n const reader = new PayloadReader(client.channel.payload, requestBytes);\n const writer = new PayloadWriter(client.channel.payload);\n answer = this.#dispatch(client, opcode, reader, writer);\n } catch (cause) {\n if (cause instanceof ProtocolViolation || cause instanceof PayloadDecodeError) {\n // Only the offending client goes; every other backend keeps its descriptors and its store.\n this.#detach(client.channel.id, cause.message, FAULT_PROTOCOL);\n return;\n }\n if (cause instanceof FsError) {\n answer = { errno: cause.code, result: 0n, responseBytes: 0 };\n } else {\n // Everything else — a poisoned store, a limit, a corrupt store, or a reply that did not fit\n // the client's own channel — is not a file rejection and not this client's fault. Report it\n // as a fault and keep the loop alive; a poisoned store answers every later request the same\n // way, and the client decides whether to give up.\n fault = FAULT_STORE;\n answer = this.#faultAnswer(client, cause);\n }\n }\n const { lo, hi } = splitResult(answer.result);\n Atomics.store(header, HEADER_ERRNO, answer.errno);\n Atomics.store(header, HEADER_RESULT_LO, lo);\n Atomics.store(header, HEADER_RESULT_HI, hi);\n Atomics.store(header, HEADER_RESPONSE, answer.responseBytes);\n Atomics.store(header, HEADER_FAULT, fault);\n Atomics.store(header, HEADER_STATE, STATE_RESPONSE);\n Atomics.notify(header, HEADER_STATE);\n }\n\n /** Put a fault message in the payload, truncating rather than overflowing a small channel. */\n #faultAnswer(client: AttachedClient, cause: unknown): Answer {\n const message = cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);\n const writer = new PayloadWriter(client.channel.payload);\n const room = client.channel.payloadBytes - 4;\n try {\n writer.string(message.length > room ? message.slice(0, Math.max(0, room)) : message);\n } catch {\n return { errno: 0, result: 0n, responseBytes: 0 };\n }\n return { errno: 0, result: 0n, responseBytes: writer.length };\n }\n\n #dispatch(client: AttachedClient, opcode: number, reader: PayloadReader, writer: PayloadWriter): Answer {\n switch (opcode) {\n case OPCODE_OPEN:\n return this.#open(client, reader);\n case OPCODE_CLOSE:\n return this.#close(client, reader);\n case OPCODE_READ:\n return this.#read(client, reader);\n case OPCODE_WRITE:\n return this.#write(client, reader);\n case OPCODE_FSYNC:\n return this.#fsync(client, reader);\n case OPCODE_FSTAT:\n return this.#stat(writer, this.#vfs.fstat(this.#fd(client, reader.u32()).fd));\n case OPCODE_STAT:\n return this.#stat(writer, this.#vfs.stat(reader.string()));\n case OPCODE_LSTAT:\n return this.#stat(writer, this.#vfs.lstat(reader.string()));\n case OPCODE_READDIR:\n return this.#readdir(reader, writer);\n case OPCODE_MKDIR:\n return this.#mkdir(reader);\n case OPCODE_RMDIR:\n this.#vfs.rmdir(reader.string(), this.#now());\n return OK;\n case OPCODE_UNLINK:\n this.#vfs.unlink(reader.string(), this.#now());\n return OK;\n case OPCODE_RENAME: {\n const oldPath = reader.string();\n this.#vfs.rename(oldPath, reader.string(), this.#now());\n return OK;\n }\n case OPCODE_TRUNCATE: {\n const path = reader.string();\n this.#vfs.truncate(path, reader.u64(), this.#now());\n return OK;\n }\n case OPCODE_SIZE:\n return this.#size(reader);\n case OPCODE_SYMLINK: {\n const target = reader.string();\n this.#vfs.symlink(target, reader.string(), this.#now());\n return OK;\n }\n case OPCODE_READLINK:\n return this.#readlink(reader, writer);\n default:\n throw new ProtocolViolation(`unhandled opcode ${opcode}`);\n }\n }\n\n #open(client: AttachedClient, reader: PayloadReader): Answer {\n const path = reader.string();\n const flags = reader.u32();\n const mode = reader.u32();\n const plan = planOpen(flags);\n const nowMs = this.#now();\n // `O_NOFOLLOW`: the core always follows a final link, so the refusal is proved here first. A\n // path that does not exist is not a link, and `O_CREAT` must still be free to create it.\n if (!plan.follow) {\n try {\n if (this.#vfs.lstat(path).kind === \"symlink\") {\n throw new FsError(\"ELOOP\", \"path is a symbolic link and O_NOFOLLOW was requested\", { path });\n }\n } catch (cause) {\n if (!(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) throw cause;\n }\n }\n if (plan.requireExisting) this.#vfs.lstat(path);\n if (plan.truncateFirst) this.#vfs.truncate(path, 0n, nowMs);\n let fd: number;\n try {\n fd = this.#vfs.open(path, plan.coreFlags, mode, nowMs);\n } catch (cause) {\n if (plan.fallbackFlags === undefined || !(cause instanceof FsError) || cause.code !== FS_ERRNO.ENOENT) {\n throw cause;\n }\n fd = this.#vfs.open(path, plan.fallbackFlags, mode, nowMs);\n }\n client.fds.set(fd, { fd, readable: plan.readable, writable: plan.writable });\n return ok(fd);\n }\n\n #close(client: AttachedClient, reader: PayloadReader): Answer {\n const entry = this.#fd(client, reader.u32());\n this.#vfs.close(entry.fd);\n client.fds.delete(entry.fd);\n return OK;\n }\n\n #read(client: AttachedClient, reader: PayloadReader): Answer {\n const entry = this.#fd(client, reader.u32());\n if (!entry.readable) throw new FsError(\"EBADF\", \"descriptor was not opened for reading\");\n const hasPosition = reader.u8() === 1;\n const position = reader.u64();\n const length = reader.u32();\n if (length > client.channel.payloadBytes) {\n throw new ProtocolViolation(`read length ${length} exceeds the payload region`);\n }\n const target = client.channel.payload.subarray(0, length);\n const count = hasPosition\n ? this.#vfs.read(entry.fd, target, 0, length, position)\n : this.#vfs.read(entry.fd, target, 0, length);\n return ok(count, count);\n }\n\n #write(client: AttachedClient, reader: PayloadReader): Answer {\n const entry = this.#fd(client, reader.u32());\n if (!entry.writable) throw new FsError(\"EBADF\", \"descriptor was not opened for writing\");\n const hasPosition = reader.u8() === 1;\n const position = reader.u64();\n const length = reader.u32();\n const source = reader.bytes(length);\n const count = this.#vfs.write(entry.fd, source, 0, length, hasPosition ? position : undefined, this.#now());\n return ok(count);\n }\n\n /**\n * `fsync` is store-wide. The core's only durability primitive is `strictSync()`, which flushes the\n * arena and then the active metadata log, so a successful `fsync` promises that EVERY byte written\n * through this broker by ANY client before the call returned is recoverable — not just this\n * descriptor's. WASI `fd_sync` and `fd_datasync` both map to it; the fd is carried only so the call\n * still fails with `EBADF` on a descriptor the client does not own, exactly as `fd_sync` must.\n */\n #fsync(client: AttachedClient, reader: PayloadReader): Answer {\n if (reader.u8() === 1) this.#fd(client, reader.u32());\n this.#vfs.strictSync();\n return OK;\n }\n\n #stat(writer: PayloadWriter, stat: RepackedStat): Answer {\n writeStat(writer, stat);\n return ok(stat.size, writer.length);\n }\n\n /**\n * One page of a directory listing. The cursor is an index into the store's own sorted listing, which\n * the store recomputes on every call — so, exactly as POSIX `readdir` allows, a listing spread over\n * several pages is not an atomic snapshot of the directory.\n */\n #readdir(reader: PayloadReader, writer: PayloadWriter): Answer {\n const path = reader.string();\n const cursor = reader.u32();\n const names = this.#vfs.readdir(path);\n if (cursor > names.length) throw new ProtocolViolation(`readdir cursor ${cursor} is past the listing`);\n // Reserve the two counters written after the entries are known to fit.\n const countAt = writer.length;\n writer.u32(0);\n writer.i32(READDIR_DONE);\n let emitted = 0;\n let next = READDIR_DONE;\n for (let index = cursor; index < names.length; index += 1) {\n const before = writer.length;\n try {\n writer.string(names[index]!);\n } catch (cause) {\n if (!(cause instanceof PayloadOverflowError)) throw cause;\n writer.rewind(before);\n if (emitted === 0) throw cause; // one name alone cannot fit: the channel is too small\n next = index;\n break;\n }\n emitted += 1;\n }\n const counters = writer.patch(countAt, 8);\n counters.setUint32(0, emitted, true);\n counters.setInt32(4, next, true);\n return ok(emitted, writer.length);\n }\n\n #mkdir(reader: PayloadReader): Answer {\n const path = reader.string();\n const recursive = reader.u8() === 1;\n const mode = reader.u32();\n this.#vfs.mkdir(path, { recursive, mode, nowMs: this.#now() });\n return OK;\n }\n\n /** The target of one symbolic link. The result is the target's byte length; the payload is it. */\n #readlink(reader: PayloadReader, writer: PayloadWriter): Answer {\n writer.string(this.#vfs.readlink(reader.string()));\n return ok(writer.length, writer.length);\n }\n\n #size(reader: PayloadReader): Answer {\n const stat = this.#vfs.stat(reader.string());\n if (stat.kind !== \"file\") throw new FsError(\"EISDIR\", \"size is a file query\");\n return ok(stat.size);\n }\n\n /**\n * Resolve a descriptor the CLIENT owns. A descriptor that belongs to another client is `EBADF`, not\n * a protocol violation: fd numbers are per-store, so a client guessing one is an ordinary bad-fd\n * mistake and never a reason to reach into another backend's files.\n */\n #fd(client: AttachedClient, fd: number): BrokerFd {\n const entry = client.fds.get(fd);\n if (entry === undefined) throw new FsError(\"EBADF\", `descriptor ${fd} is not owned by this client`);\n return entry;\n }\n}\n",
22
+ "/**\n * `RepackedSyncClient` — the backend side of the synchronous broker.\n *\n * Every method blocks the calling thread in `Atomics.wait` until the coordinator answers, which is the\n * whole point: a thread running wasm parks in futexes and can never observe a promise, so the file\n * layer under it has to be synchronous. Nothing here is async, and nothing here knows about wasm.\n *\n * ## What throws and what does not\n *\n * A FILE rejection is data: every method returns `{ errno }` (0 on success) with whatever else the\n * operation produced. Callers map the errno straight into their own ABI — the values are WASI preview1\n * errno numbers already.\n *\n * A TRANSPORT failure throws, because there is no answer to return: the server detached this client,\n * the client sent something the server refused, the server never replied inside the timeout, or the\n * store itself failed. Those are `RepackedBrokerTransportError` and `RepackedBrokerStoreError`.\n *\n * ## Mapping onto WASI preview1\n *\n * The method set is shaped so a preview1 adapter is a straight translation, with no state of its own\n * beyond the preopen table:\n *\n * path_open → open(path, flags, mode) (flags are the POSIX bits, see protocol)\n * fd_close → close(fd)\n * fd_read → read(fd, length) (no position: the store's own cursor)\n * fd_pread → read(fd, length, position)\n * fd_write → write(fd, bytes)\n * fd_pwrite → write(fd, bytes, position)\n * fd_seek → resolved by the caller; the store's cursor moves on cursor reads/writes\n * fd_sync / fd_datasync → fsync(fd) (store-wide; see the server's note)\n * fd_filestat_get → fstat(fd)\n * path_filestat_get → stat(path) / lstat(path)\n * fd_readdir → readdir(path) or readdirPage(path, cursor) for the cookie form\n * path_create_directory → mkdir(path)\n * path_remove_directory → rmdir(path)\n * path_unlink_file → unlink(path)\n * path_rename → rename(oldPath, newPath)\n * path_symlink → symlink(target, path) (targets are ABSOLUTE; see the core)\n * path_readlink → readlink(path)\n * fd_filestat_set_size → truncate(path, size) — the core resizes by PATH only, so the adapter\n * keeps the path it opened each fd with and resolves it here\n *\n * Reads and writes larger than the channel's payload region are split transparently; a caller never\n * has to know the channel size.\n */\n\nimport { FsError } from \"../core/errors\";\nimport {\n errnoName,\n FAULT_NONE,\n FAULT_PROTOCOL,\n FAULT_STORE,\n fsErrorNameOf,\n HEADER_ERRNO,\n HEADER_FAULT,\n HEADER_OPCODE,\n HEADER_REQUEST,\n HEADER_RESPONSE,\n HEADER_RESULT_HI,\n HEADER_RESULT_LO,\n HEADER_SEQUENCE,\n HEADER_STATE,\n joinResult,\n OPCODE_CLOSE,\n OPCODE_FSTAT,\n OPCODE_FSYNC,\n OPCODE_LSTAT,\n OPCODE_MKDIR,\n OPCODE_OPEN,\n OPCODE_READ,\n OPCODE_READDIR,\n OPCODE_READLINK,\n OPCODE_RENAME,\n OPCODE_RMDIR,\n OPCODE_SIZE,\n OPCODE_STAT,\n OPCODE_SYMLINK,\n OPCODE_TRUNCATE,\n OPCODE_UNLINK,\n OPCODE_WRITE,\n PayloadReader,\n PayloadWriter,\n READDIR_DONE,\n readStat,\n STATE_DETACHED,\n STATE_IDLE,\n STATE_REQUEST,\n STATE_RESPONSE,\n} from \"./protocol\";\nimport type { BrokerStat, RepackedChannel } from \"./protocol\";\n\n/** The transport failed: there is no answer, and this client can no longer make progress. */\nexport class RepackedBrokerTransportError extends Error {\n readonly brokerCode: \"detached\" | \"protocol\" | \"timeout\";\n\n constructor(brokerCode: \"detached\" | \"protocol\" | \"timeout\", message: string) {\n super(message);\n this.name = \"RepackedBrokerTransportError\";\n this.brokerCode = brokerCode;\n }\n}\n\n/** The store behind the broker failed. Not a file rejection, and not this client's mistake. */\nexport class RepackedBrokerStoreError extends Error {\n readonly brokerCode = \"store\";\n\n constructor(message: string) {\n super(`the repacked store behind the broker failed: ${message}`);\n this.name = \"RepackedBrokerStoreError\";\n }\n}\n\n/** Every result carries an errno; 0 means the operation succeeded. */\nexport interface BrokerResult {\n readonly errno: number;\n}\n\nexport interface BrokerOpenResult extends BrokerResult {\n readonly fd: number;\n}\n\nexport interface BrokerCountResult extends BrokerResult {\n /** Bytes actually transferred. Short of the request means end-of-file (read) or a store limit (write). */\n readonly count: number;\n}\n\nexport interface BrokerReadResult extends BrokerCountResult {\n readonly bytes: Uint8Array;\n}\n\nexport interface BrokerStatResult extends BrokerResult {\n readonly stat: BrokerStat | undefined;\n}\n\nexport interface BrokerSizeResult extends BrokerResult {\n readonly size: bigint;\n}\n\nexport interface BrokerReaddirResult extends BrokerResult {\n readonly entries: readonly string[];\n}\n\nexport interface BrokerReadlinkResult extends BrokerResult {\n /** The link's target, or `undefined` when the call was rejected. */\n readonly target: string | undefined;\n}\n\nexport interface BrokerReaddirPageResult extends BrokerReaddirResult {\n /** The cursor to resume from, or `undefined` when the listing is complete. */\n readonly nextCursor: number | undefined;\n}\n\nexport interface RepackedSyncClientOptions {\n /**\n * How long one request may go unanswered before the client gives up and throws. A dead coordinator\n * would otherwise park this thread forever, which is worse than a loud failure. Pass `Infinity` for\n * a host that genuinely prefers to wait.\n */\n readonly requestTimeoutMs?: number;\n}\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** The fixed bytes a read/write request spends before its data: fd + hasPosition + position + length. */\nconst TRANSFER_OVERHEAD_BYTES = 4 + 1 + 8 + 4;\n\nexport class RepackedSyncClient {\n readonly channel: RepackedChannel;\n readonly #timeoutMs: number;\n readonly #reply: Uint8Array;\n #sequence = 0;\n\n constructor(channel: RepackedChannel, options: RepackedSyncClientOptions = {}) {\n this.channel = channel;\n this.#timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n // A scratch copy of the reply region: the payload is shared memory the server reuses on the very\n // next request, so nothing handed to a caller may point into it.\n this.#reply = new Uint8Array(channel.payloadBytes);\n }\n\n /** The largest single read or write that fits one request. Reads/writes above it are chunked. */\n get maxTransferBytes(): number {\n return this.channel.payloadBytes - TRANSFER_OVERHEAD_BYTES;\n }\n\n open(path: string, flags: number, mode = 0o100666): BrokerOpenResult {\n const reply = this.#call(OPCODE_OPEN, (writer) => {\n writer.string(path);\n writer.u32(flags);\n writer.u32(mode);\n });\n return { errno: reply.errno, fd: reply.errno === 0 ? Number(reply.result) : -1 };\n }\n\n close(fd: number): BrokerResult {\n return { errno: this.#call(OPCODE_CLOSE, (writer) => writer.u32(fd)).errno };\n }\n\n /**\n * Read up to `length` bytes. With no `position` the store's own descriptor cursor is used and\n * advances; with a `position` the cursor is untouched (`fd_pread`). A result shorter than `length`\n * means end-of-file, never a partial transport.\n */\n read(fd: number, length: number, position?: bigint): BrokerReadResult {\n if (!Number.isSafeInteger(length) || length < 0) {\n throw new RangeError(\"a broker read length must be a non-negative safe integer\");\n }\n const output = new Uint8Array(length);\n let filled = 0;\n let errno = 0;\n while (filled < length) {\n const want = Math.min(length - filled, this.maxTransferBytes);\n const at = position === undefined ? undefined : position + BigInt(filled);\n const reply = this.#call(OPCODE_READ, (writer) => {\n writer.u32(fd);\n writer.u8(at === undefined ? 0 : 1);\n writer.u64(at ?? 0n);\n writer.u32(want);\n });\n if (reply.errno !== 0) {\n errno = reply.errno;\n break;\n }\n output.set(reply.bytes, filled);\n filled += reply.bytes.byteLength;\n if (reply.bytes.byteLength < want) break; // end-of-file\n }\n // A rejection part-way through still reports what already transferred, as a short read does.\n return { errno, count: filled, bytes: output.subarray(0, filled) };\n }\n\n /**\n * Write `bytes`. With no `position` the store's own descriptor cursor is used and advances; with a\n * `position` the cursor is untouched (`fd_pwrite`). A descriptor opened with `O_APPEND` always\n * writes at end-of-file and ignores `position`, exactly as POSIX requires.\n */\n write(fd: number, bytes: Uint8Array, position?: bigint): BrokerCountResult {\n let written = 0;\n let errno = 0;\n while (written < bytes.byteLength) {\n const chunk = bytes.subarray(written, written + Math.min(bytes.byteLength - written, this.maxTransferBytes));\n const at = position === undefined ? undefined : position + BigInt(written);\n const reply = this.#call(OPCODE_WRITE, (writer) => {\n writer.u32(fd);\n writer.u8(at === undefined ? 0 : 1);\n writer.u64(at ?? 0n);\n writer.u32(chunk.byteLength);\n writer.bytes(chunk);\n });\n if (reply.errno !== 0) {\n errno = reply.errno;\n break;\n }\n const count = Number(reply.result);\n written += count;\n if (count < chunk.byteLength) break; // the store admitted less than asked; stop rather than spin\n }\n return { errno, count: written };\n }\n\n /**\n * Flush the store. Durability is STORE-WIDE, not per-descriptor: on success every byte written\n * through this broker by any client before the call returned is recoverable. `fd` is validated so\n * the call still rejects a descriptor this client does not own.\n */\n fsync(fd?: number): BrokerResult {\n return {\n errno: this.#call(OPCODE_FSYNC, (writer) => {\n writer.u8(fd === undefined ? 0 : 1);\n writer.u32(fd ?? 0);\n }).errno,\n };\n }\n\n fstat(fd: number): BrokerStatResult {\n return this.#statCall(OPCODE_FSTAT, (writer) => writer.u32(fd));\n }\n\n stat(path: string): BrokerStatResult {\n return this.#statCall(OPCODE_STAT, (writer) => writer.string(path));\n }\n\n /** Reports the LINK itself when the final component is one; `stat` follows it instead. */\n lstat(path: string): BrokerStatResult {\n return this.#statCall(OPCODE_LSTAT, (writer) => writer.string(path));\n }\n\n /**\n * Create a symbolic link at `path` pointing at `target`. Targets are ABSOLUTE — the store refuses\n * a relative one with `EINVAL` rather than reinterpreting it against the link's directory.\n */\n symlink(target: string, path: string): BrokerResult {\n return {\n errno: this.#call(OPCODE_SYMLINK, (writer) => {\n writer.string(target);\n writer.string(path);\n }).errno,\n };\n }\n\n /** The target of the symbolic link at `path`. `EINVAL` when the path is not a link. */\n readlink(path: string): BrokerReadlinkResult {\n const reply = this.#call(OPCODE_READLINK, (writer) => writer.string(path));\n if (reply.errno !== 0) return { errno: reply.errno, target: undefined };\n return { errno: 0, target: new PayloadReader(reply.bytes, reply.bytes.byteLength).string() };\n }\n\n /** The complete listing, paged transparently over as many requests as the channel needs. */\n readdir(path: string): BrokerReaddirResult {\n const entries: string[] = [];\n let cursor: number | undefined = 0;\n while (cursor !== undefined) {\n const page: BrokerReaddirPageResult = this.readdirPage(path, cursor);\n if (page.errno !== 0) return { errno: page.errno, entries: [] };\n entries.push(...page.entries);\n cursor = page.nextCursor;\n }\n return { errno: 0, entries };\n }\n\n /**\n * One page of a listing, for a caller that owns its own cookie (WASI `fd_readdir`). The cursor is an\n * index into the store's sorted listing, recomputed per call — a paged listing is therefore not an\n * atomic snapshot, which is exactly what POSIX `readdir` allows.\n */\n readdirPage(path: string, cursor = 0): BrokerReaddirPageResult {\n const reply = this.#call(OPCODE_READDIR, (writer) => {\n writer.string(path);\n writer.u32(cursor);\n });\n if (reply.errno !== 0) return { errno: reply.errno, entries: [], nextCursor: undefined };\n const reader = new PayloadReader(reply.bytes, reply.bytes.byteLength);\n const count = reader.u32();\n const next = reader.i32();\n const entries: string[] = [];\n for (let index = 0; index < count; index += 1) entries.push(reader.string());\n return { errno: 0, entries, nextCursor: next === READDIR_DONE ? undefined : next };\n }\n\n mkdir(path: string, options: { recursive?: boolean; mode?: number } = {}): BrokerResult {\n return {\n errno: this.#call(OPCODE_MKDIR, (writer) => {\n writer.string(path);\n writer.u8(options.recursive === true ? 1 : 0);\n writer.u32(options.mode ?? 0o40777);\n }).errno,\n };\n }\n\n rmdir(path: string): BrokerResult {\n return { errno: this.#call(OPCODE_RMDIR, (writer) => writer.string(path)).errno };\n }\n\n unlink(path: string): BrokerResult {\n return { errno: this.#call(OPCODE_UNLINK, (writer) => writer.string(path)).errno };\n }\n\n rename(oldPath: string, newPath: string): BrokerResult {\n return {\n errno: this.#call(OPCODE_RENAME, (writer) => {\n writer.string(oldPath);\n writer.string(newPath);\n }).errno,\n };\n }\n\n /**\n * Resize by PATH. The core store has no resize-by-descriptor, so a WASI `fd_filestat_set_size`\n * adapter keeps the path each fd was opened with and calls this. Nothing is lost by that: the store\n * has no hard links, and a descriptor whose path was unlinked meanwhile is an orphan the core keeps\n * readable but no longer resizes.\n */\n truncate(path: string, size: bigint): BrokerResult {\n return {\n errno: this.#call(OPCODE_TRUNCATE, (writer) => {\n writer.string(path);\n writer.u64(size);\n }).errno,\n };\n }\n\n /** The size of one file, without the rest of a stat. `EISDIR` for a directory. */\n size(path: string): BrokerSizeResult {\n const reply = this.#call(OPCODE_SIZE, (writer) => writer.string(path));\n return { errno: reply.errno, size: reply.errno === 0 ? reply.result : 0n };\n }\n\n #statCall(opcode: number, encode: (writer: PayloadWriter) => void): BrokerStatResult {\n const reply = this.#call(opcode, encode);\n if (reply.errno !== 0) return { errno: reply.errno, stat: undefined };\n return { errno: 0, stat: readStat(new PayloadReader(reply.bytes, reply.bytes.byteLength)) };\n }\n\n /**\n * Publish one request, ring the doorbell, and park until the server answers. The returned `bytes`\n * are a private copy: the shared payload is reused by the next request.\n */\n #call(\n opcode: number,\n encode: (writer: PayloadWriter) => void,\n ): { readonly errno: number; readonly result: bigint; readonly bytes: Uint8Array } {\n const header = this.channel.header;\n const state = Atomics.load(header, HEADER_STATE);\n if (state === STATE_DETACHED) {\n throw new RepackedBrokerTransportError(\"detached\", \"the repacked broker detached this client\");\n }\n if (state === STATE_REQUEST) {\n throw new RepackedBrokerTransportError(\"protocol\", \"a repacked broker request is already in flight\");\n }\n const writer = new PayloadWriter(this.channel.payload);\n encode(writer);\n this.#sequence = (this.#sequence + 1) | 0;\n Atomics.store(header, HEADER_SEQUENCE, this.#sequence);\n Atomics.store(header, HEADER_OPCODE, opcode);\n Atomics.store(header, HEADER_REQUEST, writer.length);\n Atomics.store(header, HEADER_RESPONSE, 0);\n Atomics.store(header, HEADER_ERRNO, 0);\n Atomics.store(header, HEADER_FAULT, FAULT_NONE);\n // Publishing the state is the release edge for every payload byte written above; the doorbell is\n // the only wakeup path, so nothing waits on this word from the server side.\n Atomics.store(header, HEADER_STATE, STATE_REQUEST);\n this.channel.doorbell.ring();\n\n while (Atomics.load(header, HEADER_STATE) === STATE_REQUEST) {\n const outcome = Atomics.wait(header, HEADER_STATE, STATE_REQUEST, this.#timeoutMs);\n if (outcome === \"timed-out\" && Atomics.load(header, HEADER_STATE) === STATE_REQUEST) {\n throw new RepackedBrokerTransportError(\n \"timeout\",\n `the repacked broker did not answer opcode ${opcode} within ${this.#timeoutMs} ms`,\n );\n }\n }\n\n const responseBytes = Atomics.load(header, HEADER_RESPONSE);\n const fault = Atomics.load(header, HEADER_FAULT);\n const errno = Atomics.load(header, HEADER_ERRNO);\n const result = joinResult(Atomics.load(header, HEADER_RESULT_LO), Atomics.load(header, HEADER_RESULT_HI));\n let bytes: Uint8Array = new Uint8Array();\n if (responseBytes > 0 && responseBytes <= this.channel.payloadBytes) {\n this.#reply.set(this.channel.payload.subarray(0, responseBytes));\n bytes = this.#reply.subarray(0, responseBytes);\n }\n if (Atomics.load(header, HEADER_STATE) === STATE_DETACHED) {\n throw new RepackedBrokerTransportError(\n fault === FAULT_PROTOCOL ? \"protocol\" : \"detached\",\n fault === FAULT_PROTOCOL\n ? `the repacked broker rejected opcode ${opcode} as a protocol violation and detached this client`\n : \"the repacked broker detached this client\",\n );\n }\n if (Atomics.load(header, HEADER_STATE) !== STATE_RESPONSE) {\n throw new RepackedBrokerTransportError(\"protocol\", \"the repacked broker left the channel in an unknown state\");\n }\n Atomics.store(header, HEADER_STATE, STATE_IDLE);\n if (fault === FAULT_STORE) throw new RepackedBrokerStoreError(this.#faultMessage(bytes));\n if (fault !== FAULT_NONE) {\n throw new RepackedBrokerTransportError(\"protocol\", `the repacked broker reported fault ${fault}`);\n }\n return { errno, result, bytes };\n }\n\n #faultMessage(bytes: Uint8Array): string {\n if (bytes.byteLength === 0) return \"no detail was reported\";\n try {\n return new PayloadReader(bytes, bytes.byteLength).string();\n } catch {\n return \"the fault detail was malformed\";\n }\n }\n}\n\n/**\n * Turn a broker result into the throw the core store would have produced, for a caller that prefers\n * exceptions to errnos. The rebuilt `FsError` carries the same numeric `code` the broker reported.\n */\nexport function throwOnErrno(result: BrokerResult, operation: string, path?: string): void {\n if (result.errno === 0) return;\n const name = fsErrorNameOf(result.errno);\n const detail = `${operation} failed with ${errnoName(result.errno)}`;\n if (name === undefined) throw new RepackedBrokerTransportError(\"protocol\", `${detail} (unknown to the core)`);\n throw new FsError(name, detail, path === undefined ? { operation } : { operation, path });\n}\n",
23
23
  "/**\n * A WASI preview1 FILESYSTEM adapter over `RepackedSyncClient`.\n *\n * ## Why this file exists\n *\n * The broker gives a futex-parked thread synchronous access to ONE repacked store. A wasm engine does\n * not speak that API — it speaks `wasi_snapshot_preview1`, thirty-odd i32-returning imports over its\n * own linear memory. This module is the seam: every WASI file call a guest makes is translated into a\n * broker request, and the errno the broker already speaks (the protocol's numbers ARE WASI preview1\n * errnos) is handed straight back. Nothing here knows about pgwasm, OPFS, or any particular engine —\n * it needs a client, a way to reach the guest's memory, and nothing else.\n *\n * ## What it owns and what it refuses to touch\n *\n * The adapter owns fd `preopenFd` (3 by default — the \"/\" preopen) and every fd at or above `fdBase`\n * (4 by default). It NEVER touches fds 0–2: a host keeps its own stdin/stdout/stderr, and\n * {@link WasiPreview1Fs.compose} builds the merged import object that routes each call to whichever\n * side owns the fd. `owns()` is public so a host can make that decision itself.\n *\n * ## The fd table\n *\n * One entry per open descriptor, keyed by the WASI fd the guest sees:\n *\n * { fd, path, isDir, clientFd, offset, fdflags, rightsBase, rightsInheriting, readable, writable }\n *\n * - `path` is the normalized absolute path the fd was opened with. It is kept for the whole life of\n * the descriptor because the store resizes by PATH, not by descriptor: `fd_filestat_set_size` and\n * `fd_allocate` resolve through it.\n * - `clientFd` is the broker's descriptor for a FILE. A DIRECTORY has none: the store cannot open a\n * directory at all (its `open` answers `EISDIR`), so a directory fd is adapter-local — a remembered\n * path plus a listing snapshot — and is still usable for `fd_readdir`, `fd_filestat_get`, `fd_sync`\n * and as a dirfd for every path operation.\n * - `offset` is tracked HERE, not in the store. Every read and write the adapter issues carries an\n * explicit position (the store's `pread`/`pwrite` form), so the store's own cursor is never used and\n * `fd_seek`/`fd_tell` are exact even though several threads share one store.\n *\n * ## The mapping, decision by decision\n *\n * - **rights → access.** `RIGHTS_FD_READ` grants read, `RIGHTS_FD_WRITE` grants write; a request that\n * asks for neither is read-only. That access is enforced by the BROKER (per its own fd) and again\n * here, because a POSIX `open(O_RDONLY|O_CREAT)` has to open the store descriptor wider than the\n * guest asked for — see below.\n * - **oflags → POSIX bits.** `CREAT`→`O_CREAT`, `EXCL`→`O_EXCL`, `TRUNC`→`O_TRUNC`, and the access\n * mode from the rights. `planOpen` (server side) rejects `O_CREAT`/`O_TRUNC` without write access,\n * so a create/truncate request always adds write to the POSIX access mode while the adapter keeps\n * the NARROWER access the rights asked for and rejects a later `fd_write` with `ENOTCAPABLE`.\n * - **`O_DIRECTORY` and directories.** With `DIRECTORY` set the adapter never calls `open` (that would\n * create a file); it stats and builds a directory fd. Without it, `open` is attempted and an\n * `EISDIR` answer is recognised as \"this is a directory\" and turned into a directory fd too — which\n * costs nothing on the common file path.\n * - **`O_APPEND` is emulated here, never passed to the broker.** An append write resolves end-of-file\n * with `fstat` and then `pwrite`s there, so the adapter's own offset stays exact and\n * `fd_fdstat_set_flags` can turn `APPEND` on and off on a descriptor that was not opened with it.\n * - **`fd_seek`.** `SET`/`CUR` are pure arithmetic on the adapter's offset; `END` resolves the size\n * with `fstat` on the broker fd (never `size(path)`, which would race a rename).\n * - **`fd_readdir` cookies.** A cookie is an index into a listing SNAPSHOT taken on cookie 0, exactly\n * as a POSIX `readdir` may. The snapshot is built out of `readdirPage` calls, and it exists for a\n * protocol reason as much as a semantic one: the broker treats a cursor past the end of the listing\n * as a protocol violation and DETACHES the client, so a stale cookie from a directory that shrank\n * must never reach it. A cookie past the snapshot's end reports zero bytes used — end of directory.\n * - **truncate by path.** `fd_filestat_set_size` and `fd_allocate` call `truncate(path, size)` with\n * the descriptor's remembered path. The store has no hard links, so nothing is lost.\n * - **`fd_sync`/`fd_datasync`.** Both map to the broker's `fsync`, whose durability is STORE-WIDE: on\n * success every byte written through the broker by ANY client before the call returned is\n * recoverable. That is stronger than `fd_sync` promises, never weaker.\n * - **symlinks.** The store HAS them, and `SYMLINK_FOLLOW` therefore means something everywhere it\n * appears: `path_filestat_get` picks `stat` or `lstat`, and a `path_open` without it sends\n * `O_NOFOLLOW` so a final component that IS a link answers `ELOOP` instead of opening its target.\n * `path_unlink_file` removes the LINK, never the target — that is the core's `unlink`, not\n * something added here. `path_symlink` writes a link and `path_readlink` reads one back, both\n * verbatim: the store takes ABSOLUTE targets only (see `validateSymlinkTarget`), so a relative\n * target is `EINVAL` rather than being silently reinterpreted, and an absolute one is a STORE\n * path — which is the same thing as a guest path whenever the preopen is the store root, the\n * default and the only arrangement a datadir uses. `path_link` remains `ENOTSUP`: the store has\n * no hard links.\n * - **`fd_advise`** is a no-op success. **`fd_filestat_set_times`/`path_filestat_set_times`** answer\n * `ENOTSUP`: the broker exposes no `utimes` opcode, and inventing an adapter-local timestamp would\n * make two threads on ONE store disagree about a file's mtime, which is exactly what this whole\n * arrangement exists to prevent.\n *\n * ## Failure discipline\n *\n * Every exported function is wrapped so that a JS exception can never leave it. A throw out of a WASI\n * import unwinds through the guest's nounwind frames and surfaces as a bare `RuntimeError:\n * unreachable` with no attribution at all; instead the wrapper reports `EIO` and hands the cause to\n * `onError` with the call name. A transport failure (the coordinator died, the client was detached) is\n * therefore an `EIO` the guest can act on rather than an abort it cannot.\n */\n\nimport type { RepackedSyncClient } from \"../broker/client\";\nimport { O_CREAT, O_EXCL, O_NOFOLLOW, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY } from \"../broker/protocol\";\nimport type { BrokerStat } from \"../broker/protocol\";\n\n/**\n * WASI preview1 errno numbers. A superset of the store's own `FS_ERRNO` (whose values already ARE\n * these numbers); the extra codes are ones a filesystem ADAPTER has to answer and the store core\n * never produces, so they live here rather than widening the core's error vocabulary.\n */\nexport const WASI_ERRNO = {\n SUCCESS: 0,\n ACCES: 2,\n BADF: 8,\n EXIST: 20,\n INVAL: 28,\n IO: 29,\n ISDIR: 31,\n LOOP: 32,\n NOENT: 44,\n NOSYS: 52,\n NOTDIR: 54,\n NOTEMPTY: 55,\n NOTSUP: 58,\n OVERFLOW: 61,\n PERM: 63,\n SPIPE: 70,\n NOTCAPABLE: 76,\n} as const;\n\n/** WASI preview1 filetypes. */\nexport const WASI_FILETYPE = {\n UNKNOWN: 0,\n BLOCK_DEVICE: 1,\n CHARACTER_DEVICE: 2,\n DIRECTORY: 3,\n REGULAR_FILE: 4,\n SOCKET_DGRAM: 5,\n SOCKET_STREAM: 6,\n SYMBOLIC_LINK: 7,\n} as const;\n\n/** `path_open` oflags. */\nexport const OFLAGS_CREAT = 1;\nexport const OFLAGS_DIRECTORY = 2;\nexport const OFLAGS_EXCL = 4;\nexport const OFLAGS_TRUNC = 8;\n\n/** `fdflags`, on `path_open` and `fd_fdstat_set_flags`. */\nexport const FDFLAGS_APPEND = 1;\nexport const FDFLAGS_DSYNC = 2;\nexport const FDFLAGS_NONBLOCK = 4;\nexport const FDFLAGS_RSYNC = 8;\nexport const FDFLAGS_SYNC = 16;\n\n/** `lookupflags`, on every path operation that could follow a symlink. */\nexport const LOOKUPFLAGS_SYMLINK_FOLLOW = 1;\n\n/** The two rights the adapter reads; the rest are carried through untouched. */\nexport const RIGHTS_FD_READ = 1n << 1n;\nexport const RIGHTS_FD_WRITE = 1n << 6n;\n/** What a preopen advertises when the host asked for nothing narrower. */\nexport const RIGHTS_ALL = 0xffff_ffff_ffff_ffffn;\n\n/** `fd_seek` whence values. */\nexport const WHENCE_SET = 0;\nexport const WHENCE_CUR = 1;\nexport const WHENCE_END = 2;\n\n/** `filestat` is 64 bytes; `dirent` is 24 bytes plus the name. */\nconst FILESTAT_BYTES = 64;\nconst DIRENT_HEADER_BYTES = 24;\n/** What `stat` reports for a directory — the store has no directory size, and `0` confuses callers. */\nconst DIRECTORY_SIZE = 4096n;\nconst NS_PER_MS = 1_000_000n;\n\n/** One open descriptor the adapter owns. */\ninterface AdapterFd {\n readonly fd: number;\n /** The normalized absolute path this fd was opened with; the store resizes by path only. */\n path: string;\n readonly isDir: boolean;\n /** The broker's descriptor — `undefined` for a directory, which the store cannot open. */\n readonly clientFd: number | undefined;\n /** The adapter's own cursor. Every transfer carries an explicit position, so this is authoritative. */\n offset: bigint;\n fdflags: number;\n rightsBase: bigint;\n rightsInheriting: bigint;\n readonly readable: boolean;\n readonly writable: boolean;\n /** The listing snapshot a `fd_readdir` cookie indexes into, taken on cookie 0. */\n listing: DirentSnapshot | undefined;\n}\n\ninterface DirentSnapshot {\n readonly names: readonly string[];\n /** Lazily filled per emitted entry: a `d_type` costs one `lstat`, so only emitted names pay it. */\n readonly filetypes: Map<string, number>;\n}\n\nexport interface WasiPreview1FsOptions {\n /** The synchronous broker client this adapter turns WASI calls into. */\n readonly client: RepackedSyncClient;\n /**\n * The guest's linear memory, resolved on EVERY call. A shared wasm memory grows underneath the host\n * and any cached `Uint8Array`/`DataView` goes stale (or detaches outright, for a non-shared one), so\n * nothing here holds a view across a call.\n */\n readonly memory: () => ArrayBuffer | SharedArrayBuffer;\n /** The fd the guest sees the preopened directory as. Defaults to 3, the WASI convention. */\n readonly preopenFd?: number;\n /** The directory that preopen names. Defaults to the store root. */\n readonly preopenPath?: string;\n /** The first fd the adapter hands out, and the bottom of the range it claims. Defaults to 4. */\n readonly fdBase?: number;\n /** The adapter's clock, in milliseconds. Defaults to the wall clock; used for diagnostics. */\n readonly now?: () => bigint;\n /** Where a JS exception that escaped a WASI call is reported. Defaults to `console.error`. */\n readonly onError?: (call: string, cause: unknown) => void;\n}\n\n/** The `wasi_snapshot_preview1` filesystem surface, with the ABI's exact signatures. */\nexport interface WasiPreview1FsFunctions {\n fd_prestat_get(fd: number, resultPtr: number): number;\n fd_prestat_dir_name(fd: number, pathPtr: number, pathLen: number): number;\n fd_close(fd: number): number;\n fd_read(fd: number, iovsPtr: number, iovsLen: number, nreadPtr: number): number;\n fd_pread(fd: number, iovsPtr: number, iovsLen: number, offset: bigint, nreadPtr: number): number;\n fd_write(fd: number, iovsPtr: number, iovsLen: number, nwrittenPtr: number): number;\n fd_pwrite(fd: number, iovsPtr: number, iovsLen: number, offset: bigint, nwrittenPtr: number): number;\n fd_seek(fd: number, offset: bigint, whence: number, resultPtr: number): number;\n fd_tell(fd: number, resultPtr: number): number;\n fd_fdstat_get(fd: number, resultPtr: number): number;\n fd_fdstat_set_flags(fd: number, fdflags: number): number;\n fd_fdstat_set_rights(fd: number, rightsBase: bigint, rightsInheriting: bigint): number;\n fd_filestat_get(fd: number, resultPtr: number): number;\n fd_filestat_set_size(fd: number, size: bigint): number;\n fd_filestat_set_times(fd: number, atim: bigint, mtim: bigint, fstflags: number): number;\n fd_readdir(fd: number, bufPtr: number, bufLen: number, cookie: bigint, bufusedPtr: number): number;\n fd_sync(fd: number): number;\n fd_datasync(fd: number): number;\n fd_allocate(fd: number, offset: bigint, length: bigint): number;\n fd_advise(fd: number, offset: bigint, length: bigint, advice: number): number;\n path_open(\n dirfd: number,\n dirflags: number,\n pathPtr: number,\n pathLen: number,\n oflags: number,\n rightsBase: bigint,\n rightsInheriting: bigint,\n fdflags: number,\n resultPtr: number,\n ): number;\n path_filestat_get(dirfd: number, flags: number, pathPtr: number, pathLen: number, resultPtr: number): number;\n path_filestat_set_times(\n dirfd: number,\n flags: number,\n pathPtr: number,\n pathLen: number,\n atim: bigint,\n mtim: bigint,\n fstflags: number,\n ): number;\n path_create_directory(dirfd: number, pathPtr: number, pathLen: number): number;\n path_remove_directory(dirfd: number, pathPtr: number, pathLen: number): number;\n path_unlink_file(dirfd: number, pathPtr: number, pathLen: number): number;\n path_rename(dirfd: number, oldPtr: number, oldLen: number, newDirfd: number, newPtr: number, newLen: number): number;\n path_readlink(\n dirfd: number,\n pathPtr: number,\n pathLen: number,\n bufPtr: number,\n bufLen: number,\n bufusedPtr: number,\n ): number;\n path_symlink(oldPtr: number, oldLen: number, dirfd: number, newPtr: number, newLen: number): number;\n path_link(\n oldDirfd: number,\n oldFlags: number,\n oldPtr: number,\n oldLen: number,\n newDirfd: number,\n newPtr: number,\n newLen: number,\n ): number;\n}\n\n/** The adapter: the WASI surface plus the three composition/lifecycle helpers a host needs. */\nexport interface WasiPreview1Fs extends WasiPreview1FsFunctions {\n /** Whether this adapter answers for `fd`: the preopen, or anything at or above `fdBase`. */\n owns(fd: number): boolean;\n /** How many descriptors the adapter currently holds, preopen excluded. */\n openFdCount(): number;\n /**\n * A merged `wasi_snapshot_preview1` object: every filesystem call goes to the adapter when the fd\n * (or the dirfd, for a path operation) is adapter-owned and to `base` otherwise. Everything in\n * `base` that is not a filesystem call — `args_get`, `clock_time_get`, `poll_oneoff`, `proc_exit`,\n * `random_get`, `sched_yield`, the socket stubs — is carried through untouched, as are `base`'s own\n * fd 0/1/2 handlers.\n */\n compose(base: Readonly<Record<string, unknown>>): Record<string, unknown>;\n /**\n * Close every descriptor, returning how many were released. The call a thread makes on its way out:\n * without it the coordinator holds the thread's store descriptors until the whole channel detaches.\n */\n closeAll(): number;\n}\n\n/** Every filesystem import name, mapped to the argument index carrying the fd or dirfd. */\nconst FD_ARGUMENT_INDEX: Readonly<Record<keyof WasiPreview1FsFunctions, number>> = {\n fd_prestat_get: 0,\n fd_prestat_dir_name: 0,\n fd_close: 0,\n fd_read: 0,\n fd_pread: 0,\n fd_write: 0,\n fd_pwrite: 0,\n fd_seek: 0,\n fd_tell: 0,\n fd_fdstat_get: 0,\n fd_fdstat_set_flags: 0,\n fd_fdstat_set_rights: 0,\n fd_filestat_get: 0,\n fd_filestat_set_size: 0,\n fd_filestat_set_times: 0,\n fd_readdir: 0,\n fd_sync: 0,\n fd_datasync: 0,\n fd_allocate: 0,\n fd_advise: 0,\n path_open: 0,\n path_filestat_get: 0,\n path_filestat_set_times: 0,\n path_create_directory: 0,\n path_remove_directory: 0,\n path_unlink_file: 0,\n path_rename: 0,\n path_readlink: 0,\n // The only call whose directory argument is not first: `path_symlink(old_path, old_len, fd, …)`.\n path_symlink: 2,\n path_link: 0,\n};\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: false });\n\n/**\n * Canonicalize a guest path the way the store demands: absolute, no `.`/`..`, no empty or repeated\n * separator, no trailing slash. Deliberately lenient in the same places a WASI host has to be —\n * wasi-libc hands preopen-RELATIVE paths, but an absolute one is accepted too, and a trailing NUL from\n * a fixed-size buffer is stripped rather than rejected.\n */\nexport function normalizeWasiPath(path: string): string {\n let value = path.replace(/\\0+$/u, \"\");\n if (value === \"\" || value === \".\") return \"/\";\n if (!value.startsWith(\"/\")) value = `/${value}`;\n const parts: string[] = [];\n for (const segment of value.split(\"/\")) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") {\n parts.pop();\n continue;\n }\n parts.push(segment);\n }\n return `/${parts.join(\"/\")}`;\n}\n\n/**\n * A stable synthetic inode number for a path. The store has no inode numbers on the wire, and a WASI\n * `filestat`/`dirent` must carry one; a 64-bit FNV-1a of the path is stable for as long as the path\n * is, never zero, and never collides in practice within one datadir.\n */\nfunction inodeOf(path: string): bigint {\n let hash = 0xcbf2_9ce4_8422_2325n;\n const bytes = textEncoder.encode(path);\n for (const byte of bytes) {\n hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x1000_0000_01b3n);\n }\n return hash === 0n ? 1n : hash;\n}\n\nfunction toBigInt(value: bigint | number): bigint {\n return typeof value === \"bigint\" ? value : BigInt(Math.trunc(value));\n}\n\nexport function createWasiPreview1Fs(options: WasiPreview1FsOptions): WasiPreview1Fs {\n const client = options.client;\n const preopenFd = options.preopenFd ?? 3;\n const preopenPath = normalizeWasiPath(options.preopenPath ?? \"/\");\n const fdBase = options.fdBase ?? preopenFd + 1;\n const now = options.now ?? (() => BigInt(Date.now()));\n const onError =\n options.onError ??\n ((call: string, cause: unknown) => {\n const detail = cause instanceof Error ? (cause.stack ?? `${cause.name}: ${cause.message}`) : String(cause);\n console.error(`[wasi-preview1 ${call} @${now()}] ${detail}`);\n });\n\n if (!Number.isSafeInteger(preopenFd) || preopenFd < 3) {\n throw new RangeError(\"a WASI preopen fd must be a safe integer of at least 3 (0-2 are stdio)\");\n }\n if (!Number.isSafeInteger(fdBase) || fdBase <= preopenFd) {\n throw new RangeError(\"the WASI adapter fd base must be a safe integer above the preopen fd\");\n }\n\n const table = new Map<number, AdapterFd>();\n let nextFd = fdBase;\n\n const preopenEntry = (): AdapterFd => ({\n fd: preopenFd,\n path: preopenPath,\n isDir: true,\n clientFd: undefined,\n offset: 0n,\n fdflags: 0,\n rightsBase: RIGHTS_ALL,\n rightsInheriting: RIGHTS_ALL,\n readable: true,\n writable: false,\n listing: undefined,\n });\n table.set(preopenFd, preopenEntry());\n\n // ---- memory access -------------------------------------------------------\n // Re-derived per call, never cached: the guest memory is shared and grows underneath us.\n const bytes = (): Uint8Array => new Uint8Array(options.memory());\n const view = (): DataView => new DataView(options.memory());\n\n function readGuestString(ptr: number, length: number): string {\n // `.slice()`, not `.subarray()`: TextDecoder refuses a SharedArrayBuffer-backed view in Chrome\n // (the [AllowShared] rule). Paths are short, so the copy costs nothing.\n return textDecoder.decode(bytes().slice(ptr, ptr + length));\n }\n\n function* iovecs(ptr: number, count: number): Generator<{ ptr: number; len: number }> {\n const data = view();\n for (let index = 0; index < count; index += 1) {\n const base = ptr + index * 8;\n yield { ptr: data.getUint32(base, true), len: data.getUint32(base + 4, true) };\n }\n }\n\n // ---- fd table ------------------------------------------------------------\n function owns(fd: number): boolean {\n return fd === preopenFd || (Number.isSafeInteger(fd) && fd >= fdBase);\n }\n\n function entryOf(fd: number): AdapterFd | undefined {\n return table.get(fd);\n }\n\n function allocate(entry: Omit<AdapterFd, \"fd\">): number {\n const fd = nextFd;\n nextFd += 1;\n table.set(fd, { ...entry, fd });\n return fd;\n }\n\n function resolve(dirfd: number, ptr: number, length: number): string | undefined {\n const dir = entryOf(dirfd);\n if (dir === undefined || !dir.isDir) return undefined;\n const relative = readGuestString(ptr, length);\n if (relative.startsWith(\"/\")) return normalizeWasiPath(relative);\n return normalizeWasiPath(dir.path === \"/\" ? `/${relative}` : `${dir.path}/${relative}`);\n }\n\n // ---- stat ----------------------------------------------------------------\n function filetypeOf(kind: BrokerStat[\"kind\"]): number {\n if (kind === \"directory\") return WASI_FILETYPE.DIRECTORY;\n return kind === \"symlink\" ? WASI_FILETYPE.SYMBOLIC_LINK : WASI_FILETYPE.REGULAR_FILE;\n }\n\n function writeFilestat(ptr: number, path: string, stat: BrokerStat): void {\n // Zero first: the struct has padding the guest is entitled to see as zero, and a reused stack\n // slot would otherwise hand it whatever the last call left there.\n bytes().fill(0, ptr, ptr + FILESTAT_BYTES);\n const data = view();\n const isDirectory = stat.kind === \"directory\";\n const times = [stat.atimeMs, stat.mtimeMs, stat.ctimeMs].map((ms) => ms * NS_PER_MS);\n data.setBigUint64(ptr + 0, 1n, true); // dev\n data.setBigUint64(ptr + 8, inodeOf(path), true); // ino\n data.setUint8(ptr + 16, filetypeOf(stat.kind));\n data.setBigUint64(ptr + 24, 1n, true); // nlink\n // A link's size is its target's byte length, exactly as POSIX `lstat` reports it.\n data.setBigUint64(ptr + 32, isDirectory ? DIRECTORY_SIZE : stat.size, true);\n data.setBigUint64(ptr + 40, times[0]!, true); // atim\n data.setBigUint64(ptr + 48, times[1]!, true); // mtim\n data.setBigUint64(ptr + 56, times[2]!, true); // ctim\n }\n\n /** The size of a descriptor's file, from the broker fd (never the path — a rename must not race it). */\n function sizeOf(entry: AdapterFd): { errno: number; size: bigint } {\n if (entry.clientFd === undefined) return { errno: 0, size: DIRECTORY_SIZE };\n const stat = client.fstat(entry.clientFd);\n if (stat.errno !== 0 || stat.stat === undefined) return { errno: stat.errno || WASI_ERRNO.IO, size: 0n };\n return { errno: 0, size: stat.stat.size };\n }\n\n // ---- the WASI surface ----------------------------------------------------\n const fs: WasiPreview1FsFunctions = {\n fd_prestat_get(fd, resultPtr) {\n if (fd !== preopenFd) return WASI_ERRNO.BADF;\n const data = view();\n data.setUint8(resultPtr, 0); // preopentype::dir\n data.setUint32(resultPtr + 4, textEncoder.encode(preopenPath).byteLength, true);\n return WASI_ERRNO.SUCCESS;\n },\n\n fd_prestat_dir_name(fd, pathPtr, pathLen) {\n if (fd !== preopenFd) return WASI_ERRNO.BADF;\n const encoded = textEncoder.encode(preopenPath);\n if (pathLen < encoded.byteLength) return WASI_ERRNO.INVAL;\n bytes().set(encoded, pathPtr);\n return WASI_ERRNO.SUCCESS;\n },\n\n fd_close(fd) {\n if (fd === preopenFd) return WASI_ERRNO.SUCCESS; // the preopen outlives every guest close\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n table.delete(fd);\n if (entry.clientFd === undefined) return WASI_ERRNO.SUCCESS;\n return client.close(entry.clientFd).errno;\n },\n\n fd_read(fd, iovsPtr, iovsLen, nreadPtr) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if (entry.clientFd === undefined) return WASI_ERRNO.ISDIR;\n if (!entry.readable) return WASI_ERRNO.NOTCAPABLE;\n let total = 0;\n let errno: number = WASI_ERRNO.SUCCESS;\n for (const { ptr, len } of iovecs(iovsPtr, iovsLen)) {\n if (len === 0) continue;\n const chunk = client.read(entry.clientFd, len, entry.offset + BigInt(total));\n if (chunk.count > 0) bytes().set(chunk.bytes, ptr);\n total += chunk.count;\n if (chunk.errno !== 0) {\n errno = chunk.errno;\n break;\n }\n if (chunk.count < len) break; // end of file\n }\n entry.offset += BigInt(total);\n view().setUint32(nreadPtr, total, true);\n // A rejection part-way through still reports what transferred, exactly as a short read does.\n return total > 0 ? WASI_ERRNO.SUCCESS : errno;\n },\n\n fd_pread(fd, iovsPtr, iovsLen, offset, nreadPtr) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if (entry.clientFd === undefined) return WASI_ERRNO.ISDIR;\n if (!entry.readable) return WASI_ERRNO.NOTCAPABLE;\n let at = toBigInt(offset);\n let total = 0;\n let errno: number = WASI_ERRNO.SUCCESS;\n for (const { ptr, len } of iovecs(iovsPtr, iovsLen)) {\n if (len === 0) continue;\n const chunk = client.read(entry.clientFd, len, at);\n if (chunk.count > 0) bytes().set(chunk.bytes, ptr);\n at += BigInt(chunk.count);\n total += chunk.count;\n if (chunk.errno !== 0) {\n errno = chunk.errno;\n break;\n }\n if (chunk.count < len) break;\n }\n view().setUint32(nreadPtr, total, true);\n return total > 0 ? WASI_ERRNO.SUCCESS : errno;\n },\n\n fd_write(fd, iovsPtr, iovsLen, nwrittenPtr) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if (entry.clientFd === undefined) return WASI_ERRNO.ISDIR;\n if (!entry.writable) return WASI_ERRNO.NOTCAPABLE;\n // O_APPEND is emulated here: resolve end-of-file once, then write at explicit positions.\n if ((entry.fdflags & FDFLAGS_APPEND) !== 0) {\n const end = sizeOf(entry);\n if (end.errno !== 0) return end.errno;\n entry.offset = end.size;\n }\n let total = 0;\n let errno: number = WASI_ERRNO.SUCCESS;\n for (const { ptr, len } of iovecs(iovsPtr, iovsLen)) {\n if (len === 0) continue;\n const source = bytes().subarray(ptr, ptr + len);\n const written = client.write(entry.clientFd, source, entry.offset + BigInt(total));\n total += written.count;\n if (written.errno !== 0) {\n errno = written.errno;\n break;\n }\n if (written.count < len) break; // the store admitted less than asked\n }\n entry.offset += BigInt(total);\n view().setUint32(nwrittenPtr, total, true);\n return total > 0 ? WASI_ERRNO.SUCCESS : errno;\n },\n\n fd_pwrite(fd, iovsPtr, iovsLen, offset, nwrittenPtr) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if (entry.clientFd === undefined) return WASI_ERRNO.ISDIR;\n if (!entry.writable) return WASI_ERRNO.NOTCAPABLE;\n let at = toBigInt(offset);\n let total = 0;\n let errno: number = WASI_ERRNO.SUCCESS;\n for (const { ptr, len } of iovecs(iovsPtr, iovsLen)) {\n if (len === 0) continue;\n const written = client.write(entry.clientFd, bytes().subarray(ptr, ptr + len), at);\n at += BigInt(written.count);\n total += written.count;\n if (written.errno !== 0) {\n errno = written.errno;\n break;\n }\n if (written.count < len) break;\n }\n view().setUint32(nwrittenPtr, total, true);\n return total > 0 ? WASI_ERRNO.SUCCESS : errno;\n },\n\n fd_seek(fd, offset, whence, resultPtr) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if (entry.clientFd === undefined) return WASI_ERRNO.BADF; // a directory has no seekable offset\n const delta = toBigInt(offset);\n let target: bigint;\n if (whence === WHENCE_SET) target = delta;\n else if (whence === WHENCE_CUR) target = entry.offset + delta;\n else if (whence === WHENCE_END) {\n const end = sizeOf(entry);\n if (end.errno !== 0) return end.errno;\n target = end.size + delta;\n } else return WASI_ERRNO.INVAL;\n if (target < 0n) return WASI_ERRNO.INVAL;\n entry.offset = target;\n view().setBigUint64(resultPtr, target, true);\n return WASI_ERRNO.SUCCESS;\n },\n\n fd_tell(fd, resultPtr) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if (entry.clientFd === undefined) return WASI_ERRNO.BADF;\n view().setBigUint64(resultPtr, entry.offset, true);\n return WASI_ERRNO.SUCCESS;\n },\n\n fd_fdstat_get(fd, resultPtr) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n const data = view();\n data.setUint8(resultPtr, entry.isDir ? WASI_FILETYPE.DIRECTORY : WASI_FILETYPE.REGULAR_FILE);\n data.setUint8(resultPtr + 1, 0);\n data.setUint16(resultPtr + 2, entry.fdflags, true);\n data.setUint32(resultPtr + 4, 0, true);\n data.setBigUint64(resultPtr + 8, entry.rightsBase, true);\n data.setBigUint64(resultPtr + 16, entry.rightsInheriting, true);\n return WASI_ERRNO.SUCCESS;\n },\n\n fd_fdstat_set_flags(fd, fdflags) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n // APPEND is the adapter's own emulation, so it can be turned on and off freely; the rest of the\n // sync bits are accepted and ignored (the store's only durability primitive is `fsync`, which is\n // already store-wide and stronger than DSYNC/RSYNC/SYNC promise). NONBLOCK is meaningless here:\n // every broker call blocks by construction.\n entry.fdflags = fdflags & (FDFLAGS_APPEND | FDFLAGS_DSYNC | FDFLAGS_NONBLOCK | FDFLAGS_RSYNC | FDFLAGS_SYNC);\n return WASI_ERRNO.SUCCESS;\n },\n\n fd_fdstat_set_rights(fd, rightsBase, rightsInheriting) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n // Rights may only ever be narrowed.\n const base = toBigInt(rightsBase);\n const inheriting = toBigInt(rightsInheriting);\n if ((base & ~entry.rightsBase) !== 0n || (inheriting & ~entry.rightsInheriting) !== 0n) {\n return WASI_ERRNO.NOTCAPABLE;\n }\n entry.rightsBase = base;\n entry.rightsInheriting = inheriting;\n return WASI_ERRNO.SUCCESS;\n },\n\n fd_filestat_get(fd, resultPtr) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n const stat = entry.clientFd === undefined ? client.stat(entry.path) : client.fstat(entry.clientFd);\n if (stat.errno !== 0 || stat.stat === undefined) return stat.errno || WASI_ERRNO.IO;\n writeFilestat(resultPtr, entry.path, stat.stat);\n return WASI_ERRNO.SUCCESS;\n },\n\n fd_filestat_set_size(fd, size) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if (entry.clientFd === undefined) return WASI_ERRNO.ISDIR;\n if (!entry.writable) return WASI_ERRNO.NOTCAPABLE;\n // The store resizes by PATH only, which is why every fd remembers the path it was opened with.\n return client.truncate(entry.path, toBigInt(size)).errno;\n },\n\n fd_filestat_set_times(fd, _atim, _mtim, fstflags) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if ((fstflags & ~0b1111) !== 0) return WASI_ERRNO.INVAL;\n if (fstflags === 0) return WASI_ERRNO.SUCCESS;\n // The broker exposes no `utimes`. Answering ENOTSUP is the honest answer: a timestamp kept in\n // this adapter alone would make two threads on ONE store disagree about a file's mtime.\n return WASI_ERRNO.NOTSUP;\n },\n\n fd_readdir(fd, bufPtr, bufLen, cookie, bufusedPtr) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if (!entry.isDir) return WASI_ERRNO.NOTDIR;\n const start = Number(toBigInt(cookie));\n if (!Number.isSafeInteger(start) || start < 0) return WASI_ERRNO.INVAL;\n // Snapshot on cookie 0 so pagination is stable across guest mutations — and so a stale cookie\n // can never be forwarded to the broker, which treats a cursor past the listing as a protocol\n // violation and detaches the client.\n if (start === 0 || entry.listing === undefined) {\n const listed = client.readdir(entry.path);\n if (listed.errno !== 0) return listed.errno;\n entry.listing = { names: listed.entries, filetypes: new Map() };\n }\n const listing = entry.listing;\n const data = view();\n const memory = bytes();\n let used = 0;\n for (let index = start; index < listing.names.length; index += 1) {\n const name = listing.names[index]!;\n const nameBytes = textEncoder.encode(name);\n if (used + DIRENT_HEADER_BYTES >= bufLen) {\n // No room for another header: report the buffer full so the caller grows it and retries.\n used = bufLen;\n break;\n }\n let filetype = listing.filetypes.get(name);\n if (filetype === undefined) {\n // `lstat`, so a link is reported as one: a guest that walks a directory to decide what to\n // recurse into must see the link rather than whatever it points at.\n const child = client.lstat(entry.path === \"/\" ? `/${name}` : `${entry.path}/${name}`);\n filetype =\n child.errno !== 0 || child.stat === undefined ? WASI_FILETYPE.UNKNOWN : filetypeOf(child.stat.kind);\n listing.filetypes.set(name, filetype);\n }\n const at = bufPtr + used;\n data.setBigUint64(at, BigInt(index + 1), true); // d_next\n data.setBigUint64(at + 8, inodeOf(entry.path === \"/\" ? `/${name}` : `${entry.path}/${name}`), true); // d_ino\n data.setUint32(at + 16, nameBytes.byteLength, true); // d_namlen\n data.setUint8(at + 20, filetype);\n data.setUint8(at + 21, 0);\n data.setUint16(at + 22, 0, true);\n const room = bufLen - used - DIRENT_HEADER_BYTES;\n const copied = Math.min(nameBytes.byteLength, room);\n memory.set(nameBytes.subarray(0, copied), at + DIRENT_HEADER_BYTES);\n used += DIRENT_HEADER_BYTES + copied;\n if (copied < nameBytes.byteLength) break; // truncated name: the caller grows the buffer\n }\n data.setUint32(bufusedPtr, used, true);\n return WASI_ERRNO.SUCCESS;\n },\n\n fd_sync(fd) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n // Store-wide by construction: on success every byte any client wrote before the call is durable.\n return entry.clientFd === undefined ? client.fsync().errno : client.fsync(entry.clientFd).errno;\n },\n\n fd_datasync(fd) {\n return fs.fd_sync(fd);\n },\n\n fd_allocate(fd, offset, length) {\n const entry = entryOf(fd);\n if (entry === undefined) return WASI_ERRNO.BADF;\n if (entry.clientFd === undefined) return WASI_ERRNO.ISDIR;\n if (!entry.writable) return WASI_ERRNO.NOTCAPABLE;\n const end = toBigInt(offset) + toBigInt(length);\n if (end < 0n) return WASI_ERRNO.INVAL;\n const current = sizeOf(entry);\n if (current.errno !== 0) return current.errno;\n // The store has no space RESERVATION primitive, so this extends by truncation instead. That\n // satisfies everything `posix_fallocate` observably promises — the file is at least that big,\n // existing bytes are untouched, the gap reads as zeros — but it does not pre-commit capacity, so\n // a later write into the range can still fail on a full store.\n if (end <= current.size) return WASI_ERRNO.SUCCESS;\n return client.truncate(entry.path, end).errno;\n },\n\n fd_advise(fd, _offset, _length, _advice) {\n return entryOf(fd) === undefined ? WASI_ERRNO.BADF : WASI_ERRNO.SUCCESS;\n },\n\n path_open(dirfd, dirflags, pathPtr, pathLen, oflags, rightsBase, rightsInheriting, fdflags, resultPtr) {\n const path = resolve(dirfd, pathPtr, pathLen);\n if (path === undefined) return WASI_ERRNO.BADF;\n const followLinks = (dirflags & LOOKUPFLAGS_SYMLINK_FOLLOW) !== 0;\n const base = toBigInt(rightsBase);\n const inheriting = toBigInt(rightsInheriting);\n const wantsRead = (base & RIGHTS_FD_READ) !== 0n;\n const wantsWrite = (base & RIGHTS_FD_WRITE) !== 0n;\n const create = (oflags & OFLAGS_CREAT) !== 0;\n const exclusive = (oflags & OFLAGS_EXCL) !== 0;\n const truncate = (oflags & OFLAGS_TRUNC) !== 0;\n const directory = (oflags & OFLAGS_DIRECTORY) !== 0;\n // A request that asks for neither right is a plain read-only open.\n const readable = wantsRead || !wantsWrite;\n const writable = wantsWrite;\n\n const openDirectory = (): number => {\n const stat = followLinks ? client.stat(path) : client.lstat(path);\n if (stat.errno !== 0 || stat.stat === undefined) return stat.errno || WASI_ERRNO.IO;\n // Without SYMLINK_FOLLOW a final component that IS a link must not be opened through.\n if (stat.stat.kind === \"symlink\") return WASI_ERRNO.LOOP;\n if (stat.stat.kind !== \"directory\") return WASI_ERRNO.NOTDIR;\n if (create && exclusive) return WASI_ERRNO.EXIST;\n const fd = allocate({\n path,\n isDir: true,\n clientFd: undefined,\n offset: 0n,\n fdflags: 0,\n rightsBase: base === 0n ? RIGHTS_ALL : base,\n rightsInheriting: inheriting === 0n ? RIGHTS_ALL : inheriting,\n readable: true,\n writable: false,\n listing: undefined,\n });\n view().setUint32(resultPtr, fd, true);\n return WASI_ERRNO.SUCCESS;\n };\n\n // With O_DIRECTORY the path must never be created as a file, so `open` is not attempted at all.\n if (directory) return openDirectory();\n\n // `planOpen` refuses O_CREAT/O_TRUNC without write access, but POSIX `open(O_RDONLY|O_CREAT)` is\n // perfectly legal — so the STORE descriptor is opened wide enough to satisfy the plan while the\n // adapter keeps the narrower access the rights asked for and rejects a later write itself.\n const posixWrite = writable || create || truncate;\n const posixRead = readable || !posixWrite;\n let flags = posixRead && posixWrite ? O_RDWR : posixWrite ? O_WRONLY : O_RDONLY;\n if (create) flags |= O_CREAT;\n if (exclusive) flags |= O_EXCL;\n if (truncate) flags |= O_TRUNC;\n // The broker follows a final link by default; the absent lookup flag is what turns that off.\n if (!followLinks) flags |= O_NOFOLLOW;\n // O_APPEND is never sent: it is emulated on this side so the adapter's offset stays exact and\n // `fd_fdstat_set_flags` can add or remove APPEND on an already-open descriptor.\n\n const opened = client.open(path, flags);\n if (opened.errno !== 0) {\n // The store cannot open a directory at all — it answers EISDIR — so that answer is how a\n // directory is recognised on the common path, at no cost to a file open.\n if (opened.errno === WASI_ERRNO.ISDIR) return create && exclusive ? WASI_ERRNO.EXIST : openDirectory();\n return opened.errno;\n }\n const fd = allocate({\n path,\n isDir: false,\n clientFd: opened.fd,\n offset: 0n,\n fdflags: fdflags & (FDFLAGS_APPEND | FDFLAGS_DSYNC | FDFLAGS_NONBLOCK | FDFLAGS_RSYNC | FDFLAGS_SYNC),\n rightsBase: base === 0n ? RIGHTS_ALL : base,\n rightsInheriting: inheriting === 0n ? RIGHTS_ALL : inheriting,\n readable,\n writable,\n listing: undefined,\n });\n view().setUint32(resultPtr, fd, true);\n return WASI_ERRNO.SUCCESS;\n },\n\n path_filestat_get(dirfd, flags, pathPtr, pathLen, resultPtr) {\n const path = resolve(dirfd, pathPtr, pathLen);\n if (path === undefined) return WASI_ERRNO.BADF;\n // The split that makes `std::fs::symlink_metadata` differ from `std::fs::metadata`: without\n // the flag the LINK is reported, with it the thing it points at.\n const follow = (flags & LOOKUPFLAGS_SYMLINK_FOLLOW) !== 0;\n const stat = follow ? client.stat(path) : client.lstat(path);\n if (stat.errno !== 0 || stat.stat === undefined) return stat.errno || WASI_ERRNO.IO;\n writeFilestat(resultPtr, path, stat.stat);\n return WASI_ERRNO.SUCCESS;\n },\n\n path_filestat_set_times(dirfd, _flags, pathPtr, pathLen, _atim, _mtim, fstflags) {\n const path = resolve(dirfd, pathPtr, pathLen);\n if (path === undefined) return WASI_ERRNO.BADF;\n if ((fstflags & ~0b1111) !== 0) return WASI_ERRNO.INVAL;\n const stat = client.lstat(path);\n if (stat.errno !== 0) return stat.errno;\n if (fstflags === 0) return WASI_ERRNO.SUCCESS;\n return WASI_ERRNO.NOTSUP; // see fd_filestat_set_times\n },\n\n path_create_directory(dirfd, pathPtr, pathLen) {\n const path = resolve(dirfd, pathPtr, pathLen);\n if (path === undefined) return WASI_ERRNO.BADF;\n return client.mkdir(path).errno;\n },\n\n path_remove_directory(dirfd, pathPtr, pathLen) {\n const path = resolve(dirfd, pathPtr, pathLen);\n if (path === undefined) return WASI_ERRNO.BADF;\n return client.rmdir(path).errno;\n },\n\n path_unlink_file(dirfd, pathPtr, pathLen) {\n const path = resolve(dirfd, pathPtr, pathLen);\n if (path === undefined) return WASI_ERRNO.BADF;\n return client.unlink(path).errno;\n },\n\n path_rename(dirfd, oldPtr, oldLen, newDirfd, newPtr, newLen) {\n const oldPath = resolve(dirfd, oldPtr, oldLen);\n const newPath = resolve(newDirfd, newPtr, newLen);\n if (oldPath === undefined || newPath === undefined) return WASI_ERRNO.BADF;\n const result = client.rename(oldPath, newPath);\n if (result.errno !== 0) return result.errno;\n // Every descriptor still open on the old path must follow it, or a later `fd_filestat_set_size`\n // would resize whatever now occupies the source name.\n const prefix = oldPath === \"/\" ? \"/\" : `${oldPath}/`;\n for (const entry of table.values()) {\n if (entry.path === oldPath) entry.path = newPath;\n else if (entry.path.startsWith(prefix)) entry.path = newPath + entry.path.slice(oldPath.length);\n }\n return WASI_ERRNO.SUCCESS;\n },\n\n path_readlink(dirfd, pathPtr, pathLen, bufPtr, bufLen, bufusedPtr) {\n const path = resolve(dirfd, pathPtr, pathLen);\n if (path === undefined) return WASI_ERRNO.BADF;\n // EINVAL for a path that is not a link, ENOENT for one that is not there — both come from the\n // store, whose errnos already ARE these numbers.\n const link = client.readlink(path);\n if (link.errno !== 0 || link.target === undefined) return link.errno || WASI_ERRNO.IO;\n const encoded = textEncoder.encode(link.target);\n // preview1 writes no terminator and truncates silently; `bufused === buflen` is how a caller\n // learns its buffer was too small, so a short buffer must NOT be an error here.\n const copied = Math.min(encoded.byteLength, bufLen);\n if (copied > 0) bytes().set(encoded.subarray(0, copied), bufPtr);\n view().setUint32(bufusedPtr, copied, true);\n return WASI_ERRNO.SUCCESS;\n },\n\n path_symlink(oldPtr, oldLen, dirfd, newPtr, newLen) {\n const path = resolve(dirfd, newPtr, newLen);\n if (path === undefined) return WASI_ERRNO.BADF;\n // The TARGET is the link's contents, not a path to walk: it is read verbatim (bar a trailing\n // NUL from a fixed-size guest buffer) and stored as given. The store takes absolute targets\n // only and answers EINVAL for anything else.\n const target = readGuestString(oldPtr, oldLen).replace(/\\0+$/u, \"\");\n return client.symlink(target, path).errno;\n },\n\n path_link(oldDirfd, _oldFlags, _oldPtr, _oldLen, newDirfd, _newPtr, _newLen) {\n if (entryOf(oldDirfd)?.isDir !== true || entryOf(newDirfd)?.isDir !== true) return WASI_ERRNO.BADF;\n return WASI_ERRNO.NOTSUP; // the store has no hard links\n },\n };\n\n // ---- failure containment -------------------------------------------------\n // A JS exception thrown out of a WASI import unwinds through the guest's nounwind frames and\n // surfaces as a bare `RuntimeError: unreachable` with nothing attached. Every call is therefore\n // wrapped: the guest sees EIO and the host sees the stack.\n const guarded: Record<string, unknown> = {};\n for (const name of Object.keys(fs) as (keyof WasiPreview1FsFunctions)[]) {\n const inner = fs[name] as (...args: unknown[]) => number;\n guarded[name] = (...args: unknown[]): number => {\n try {\n return inner(...args);\n } catch (cause) {\n onError(name, cause);\n return WASI_ERRNO.IO;\n }\n };\n }\n\n const adapter = guarded as unknown as WasiPreview1Fs;\n\n adapter.owns = owns;\n\n adapter.openFdCount = (): number => table.size - (table.has(preopenFd) ? 1 : 0);\n\n adapter.closeAll = (): number => {\n let released = 0;\n for (const entry of table.values()) {\n if (entry.clientFd === undefined) continue;\n client.close(entry.clientFd);\n released += 1;\n }\n table.clear();\n table.set(preopenFd, preopenEntry());\n nextFd = fdBase;\n return released;\n };\n\n adapter.compose = (base: Readonly<Record<string, unknown>>): Record<string, unknown> => {\n const merged: Record<string, unknown> = { ...base };\n for (const [name, index] of Object.entries(FD_ARGUMENT_INDEX)) {\n const mine = guarded[name] as (...args: unknown[]) => number;\n const theirs = base[name];\n if (typeof theirs !== \"function\") {\n // The base host does not implement this call at all (`fd_tell`, `fd_allocate` and friends are\n // commonly absent): the adapter answers for its own fds and reports EBADF for anything else,\n // which is exactly what an absent implementation would have to say.\n merged[name] = (...args: unknown[]): number => (owns(Number(args[index])) ? mine(...args) : WASI_ERRNO.BADF);\n continue;\n }\n const fallback = theirs as (...args: unknown[]) => number;\n merged[name] = (...args: unknown[]): number => (owns(Number(args[index])) ? mine(...args) : fallback(...args));\n }\n return merged;\n };\n\n return adapter;\n}\n"
24
24
  ],
25
25
  "mappings": ";;;;;;;;;;;;;;;;AAAO,IAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,QAAQ;AAAA,EAER,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,WAAW;AAAA,EACX,OAAO;AACT;AAAA;AAKO,MAAM,gBAAgB,MAAM;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EAET,WAAW,CACT,MACA,SACA,UAAkE,CAAC,GACnE;AAAA,IACA,MAAM,SAAS,EAAE,OAAO,QAAQ,MAAM,CAAC;AAAA,IACvC,KAAK,OAAO;AAAA,IACZ,KAAK,OA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