@pgxsinkit/pgwasm 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +111 -0
  4. package/README.md +56 -0
  5. package/dist/build/index.d.ts +8 -0
  6. package/dist/build/index.d.ts.map +1 -0
  7. package/dist/build/index.js +21 -0
  8. package/dist/build/index.js.map +9 -0
  9. package/dist/build/seam.d.ts +174 -0
  10. package/dist/build/seam.d.ts.map +1 -0
  11. package/dist/chunk-0w227vw2.js +233 -0
  12. package/dist/chunk-0w227vw2.js.map +11 -0
  13. package/dist/chunk-74gcrk47.js +563 -0
  14. package/dist/chunk-74gcrk47.js.map +14 -0
  15. package/dist/chunk-at1py5s5.js +373 -0
  16. package/dist/chunk-at1py5s5.js.map +12 -0
  17. package/dist/chunk-cpsnmzrf.js +126 -0
  18. package/dist/chunk-cpsnmzrf.js.map +10 -0
  19. package/dist/chunk-d82gg1hx.js +306 -0
  20. package/dist/chunk-d82gg1hx.js.map +10 -0
  21. package/dist/chunk-gjf102c9.js +1005 -0
  22. package/dist/chunk-gjf102c9.js.map +16 -0
  23. package/dist/chunk-kb3rsr7n.js +19 -0
  24. package/dist/chunk-kb3rsr7n.js.map +9 -0
  25. package/dist/chunk-tdvrvgt5.js +83 -0
  26. package/dist/chunk-tdvrvgt5.js.map +11 -0
  27. package/dist/chunk-z0c40tja.js +50 -0
  28. package/dist/chunk-z0c40tja.js.map +10 -0
  29. package/dist/core/data-dir-archive.d.ts +17 -0
  30. package/dist/core/data-dir-archive.d.ts.map +1 -0
  31. package/dist/core/internals.d.ts +59 -0
  32. package/dist/core/internals.d.ts.map +1 -0
  33. package/dist/core/marker.d.ts +35 -0
  34. package/dist/core/marker.d.ts.map +1 -0
  35. package/dist/core/mutex.d.ts +9 -0
  36. package/dist/core/mutex.d.ts.map +1 -0
  37. package/dist/core/names.d.ts +11 -0
  38. package/dist/core/names.d.ts.map +1 -0
  39. package/dist/core/parse.d.ts +11 -0
  40. package/dist/core/parse.d.ts.map +1 -0
  41. package/dist/core/pgwasm.d.ts +53 -0
  42. package/dist/core/pgwasm.d.ts.map +1 -0
  43. package/dist/core/storage.d.ts +14 -0
  44. package/dist/core/storage.d.ts.map +1 -0
  45. package/dist/create.d.ts +10 -0
  46. package/dist/create.d.ts.map +1 -0
  47. package/dist/drizzle/codecs.d.ts +9 -0
  48. package/dist/drizzle/codecs.d.ts.map +1 -0
  49. package/dist/drizzle/driver.d.ts +50 -0
  50. package/dist/drizzle/driver.d.ts.map +1 -0
  51. package/dist/drizzle/index.d.ts +4 -0
  52. package/dist/drizzle/index.d.ts.map +1 -0
  53. package/dist/drizzle/index.js +261 -0
  54. package/dist/drizzle/index.js.map +12 -0
  55. package/dist/drizzle/session.d.ts +39 -0
  56. package/dist/drizzle/session.d.ts.map +1 -0
  57. package/dist/errors.d.ts +115 -0
  58. package/dist/errors.d.ts.map +1 -0
  59. package/dist/fs/base-filesystem.d.ts +118 -0
  60. package/dist/fs/base-filesystem.d.ts.map +1 -0
  61. package/dist/fs/index.d.ts +2 -0
  62. package/dist/fs/index.d.ts.map +1 -0
  63. package/dist/fs/index.js +11 -0
  64. package/dist/fs/index.js.map +9 -0
  65. package/dist/index.d.ts +8 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +53 -0
  68. package/dist/index.js.map +9 -0
  69. package/dist/interface.d.ts +165 -0
  70. package/dist/interface.d.ts.map +1 -0
  71. package/dist/live/debounce-mutex.d.ts +6 -0
  72. package/dist/live/debounce-mutex.d.ts.map +1 -0
  73. package/dist/live/format-query.d.ts +8 -0
  74. package/dist/live/format-query.d.ts.map +1 -0
  75. package/dist/live/index.d.ts +9 -0
  76. package/dist/live/index.d.ts.map +1 -0
  77. package/dist/live/index.js +601 -0
  78. package/dist/live/index.js.map +12 -0
  79. package/dist/live/interface.d.ts +86 -0
  80. package/dist/live/interface.d.ts.map +1 -0
  81. package/dist/opfs/broker/client.d.ts +163 -0
  82. package/dist/opfs/broker/client.d.ts.map +1 -0
  83. package/dist/opfs/broker/protocol.d.ts +326 -0
  84. package/dist/opfs/broker/protocol.d.ts.map +1 -0
  85. package/dist/opfs/broker/server.d.ts +84 -0
  86. package/dist/opfs/broker/server.d.ts.map +1 -0
  87. package/dist/opfs/core/checksum.d.ts +3 -0
  88. package/dist/opfs/core/checksum.d.ts.map +1 -0
  89. package/dist/opfs/core/codec.d.ts +73 -0
  90. package/dist/opfs/core/codec.d.ts.map +1 -0
  91. package/dist/opfs/core/errors.d.ts +80 -0
  92. package/dist/opfs/core/errors.d.ts.map +1 -0
  93. package/dist/opfs/core/limits.d.ts +35 -0
  94. package/dist/opfs/core/limits.d.ts.map +1 -0
  95. package/dist/opfs/core/memory-port.d.ts +51 -0
  96. package/dist/opfs/core/memory-port.d.ts.map +1 -0
  97. package/dist/opfs/core/metadata-store.d.ts +19 -0
  98. package/dist/opfs/core/metadata-store.d.ts.map +1 -0
  99. package/dist/opfs/core/mounted-vfs.d.ts +119 -0
  100. package/dist/opfs/core/mounted-vfs.d.ts.map +1 -0
  101. package/dist/opfs/core/path.d.ts +14 -0
  102. package/dist/opfs/core/path.d.ts.map +1 -0
  103. package/dist/opfs/core/port.d.ts +30 -0
  104. package/dist/opfs/core/port.d.ts.map +1 -0
  105. package/dist/opfs/core/repacked-vfs.d.ts +138 -0
  106. package/dist/opfs/core/repacked-vfs.d.ts.map +1 -0
  107. package/dist/opfs/core/state-machine.d.ts +296 -0
  108. package/dist/opfs/core/state-machine.d.ts.map +1 -0
  109. package/dist/opfs/create.d.ts +50 -0
  110. package/dist/opfs/create.d.ts.map +1 -0
  111. package/dist/opfs/file-port.d.ts +14 -0
  112. package/dist/opfs/file-port.d.ts.map +1 -0
  113. package/dist/opfs/index.d.ts +37 -0
  114. package/dist/opfs/index.d.ts.map +1 -0
  115. package/dist/opfs/index.js +6671 -0
  116. package/dist/opfs/index.js.map +28 -0
  117. package/dist/opfs/opfs-port.d.ts +34 -0
  118. package/dist/opfs/opfs-port.d.ts.map +1 -0
  119. package/dist/opfs/opfs-repacked-fs.d.ts +55 -0
  120. package/dist/opfs/opfs-repacked-fs.d.ts.map +1 -0
  121. package/dist/opfs/wasi/preview1.d.ts +228 -0
  122. package/dist/opfs/wasi/preview1.d.ts.map +1 -0
  123. package/dist/protocol/index.d.ts +15 -0
  124. package/dist/protocol/index.d.ts.map +1 -0
  125. package/dist/protocol/index.js +23 -0
  126. package/dist/protocol/index.js.map +10 -0
  127. package/dist/protocol/wire/buffer-reader.d.ts +13 -0
  128. package/dist/protocol/wire/buffer-reader.d.ts.map +1 -0
  129. package/dist/protocol/wire/buffer-writer.d.ts +12 -0
  130. package/dist/protocol/wire/buffer-writer.d.ts.map +1 -0
  131. package/dist/protocol/wire/index.d.ts +5 -0
  132. package/dist/protocol/wire/index.d.ts.map +1 -0
  133. package/dist/protocol/wire/messages.d.ts +194 -0
  134. package/dist/protocol/wire/messages.d.ts.map +1 -0
  135. package/dist/protocol/wire/parser.d.ts +12 -0
  136. package/dist/protocol/wire/parser.d.ts.map +1 -0
  137. package/dist/protocol/wire/serializer.d.ts +61 -0
  138. package/dist/protocol/wire/serializer.d.ts.map +1 -0
  139. package/dist/protocol/wire/string-utils.d.ts +6 -0
  140. package/dist/protocol/wire/string-utils.d.ts.map +1 -0
  141. package/dist/protocol/wire/types.d.ts +7 -0
  142. package/dist/protocol/wire/types.d.ts.map +1 -0
  143. package/dist/tar/gzip.d.ts +7 -0
  144. package/dist/tar/gzip.d.ts.map +1 -0
  145. package/dist/tar/tar.d.ts +39 -0
  146. package/dist/tar/tar.d.ts.map +1 -0
  147. package/dist/templating.d.ts +42 -0
  148. package/dist/templating.d.ts.map +1 -0
  149. package/dist/types.d.ts +76 -0
  150. package/dist/types.d.ts.map +1 -0
  151. package/package.json +69 -0
  152. package/skills/opfs/SKILL.md +138 -0
  153. package/src/build/index.ts +23 -0
  154. package/src/build/seam.ts +179 -0
  155. package/src/core/data-dir-archive.ts +68 -0
  156. package/src/core/internals.ts +87 -0
  157. package/src/core/marker.ts +94 -0
  158. package/src/core/mutex.ts +16 -0
  159. package/src/core/names.ts +26 -0
  160. package/src/core/parse.ts +79 -0
  161. package/src/core/pgwasm.ts +876 -0
  162. package/src/core/storage.ts +70 -0
  163. package/src/create.ts +134 -0
  164. package/src/drizzle/codecs.ts +114 -0
  165. package/src/drizzle/driver.ts +141 -0
  166. package/src/drizzle/index.ts +15 -0
  167. package/src/drizzle/session.ts +133 -0
  168. package/src/errors.ts +201 -0
  169. package/src/fs/base-filesystem.ts +149 -0
  170. package/src/fs/index.ts +7 -0
  171. package/src/index.ts +44 -0
  172. package/src/interface.ts +186 -0
  173. package/src/live/debounce-mutex.ts +45 -0
  174. package/src/live/format-query.ts +47 -0
  175. package/src/live/index.ts +707 -0
  176. package/src/live/interface.ts +109 -0
  177. package/src/opfs/broker/client.ts +482 -0
  178. package/src/opfs/broker/protocol.ts +624 -0
  179. package/src/opfs/broker/server.ts +522 -0
  180. package/src/opfs/core/checksum.ts +85 -0
  181. package/src/opfs/core/codec.ts +1051 -0
  182. package/src/opfs/core/errors.ts +134 -0
  183. package/src/opfs/core/limits.ts +68 -0
  184. package/src/opfs/core/memory-port.ts +459 -0
  185. package/src/opfs/core/metadata-store.ts +512 -0
  186. package/src/opfs/core/mounted-vfs.ts +407 -0
  187. package/src/opfs/core/path.ts +82 -0
  188. package/src/opfs/core/port.ts +114 -0
  189. package/src/opfs/core/repacked-vfs.ts +1464 -0
  190. package/src/opfs/core/state-machine.ts +1699 -0
  191. package/src/opfs/create.ts +125 -0
  192. package/src/opfs/file-port.ts +183 -0
  193. package/src/opfs/index.ts +113 -0
  194. package/src/opfs/opfs-port.ts +90 -0
  195. package/src/opfs/opfs-repacked-fs.ts +210 -0
  196. package/src/opfs/wasi/preview1.ts +1016 -0
  197. package/src/protocol/index.ts +24 -0
  198. package/src/protocol/wire/buffer-reader.ts +60 -0
  199. package/src/protocol/wire/buffer-writer.ts +93 -0
  200. package/src/protocol/wire/index.ts +15 -0
  201. package/src/protocol/wire/messages.ts +332 -0
  202. package/src/protocol/wire/parser.ts +373 -0
  203. package/src/protocol/wire/serializer.ts +233 -0
  204. package/src/protocol/wire/string-utils.ts +18 -0
  205. package/src/protocol/wire/types.ts +12 -0
  206. package/src/tar/gzip.ts +36 -0
  207. package/src/tar/tar.ts +253 -0
  208. package/src/templating.ts +103 -0
  209. package/src/types.ts +283 -0
@@ -0,0 +1,624 @@
1
+ /**
2
+ * The synchronous broker wire protocol.
3
+ *
4
+ * ## Why a wire protocol at all
5
+ *
6
+ * A repacked store is a single-owner object: it holds four exclusive file handles and one in-memory
7
+ * metadata generation, and it is not shareable across JavaScript agents. A multi-backend engine needs
8
+ * several worker threads to reach ONE store, and a worker running wasm parks in futexes, so it cannot
9
+ * await a promise to get a file answered. The store therefore lives alone in a coordinator worker and
10
+ * every other thread asks for file operations over a `SharedArrayBuffer`, blocking in `Atomics.wait`
11
+ * until the coordinator answers. Nothing here knows about PGlite, wasm, or OPFS.
12
+ *
13
+ * ## Topology
14
+ *
15
+ * One CHANNEL per client, plus one DOORBELL shared by every channel of one broker:
16
+ *
17
+ * client A ─ channel A ─┐
18
+ * client B ─ channel B ─┼─→ doorbell ─→ RepackedSyncBroker (owns the RepackedVfs)
19
+ * client C ─ channel C ─┘
20
+ *
21
+ * A client publishes its request into its own channel and then bumps the doorbell, so one blocking
22
+ * server loop can wait on a single word and still service any number of clients.
23
+ *
24
+ * ## Channel layout
25
+ *
26
+ * One `SharedArrayBuffer`, `CHANNEL_HEADER_BYTES` (64) of `Int32Array` header followed by a byte
27
+ * payload region (`DEFAULT_PAYLOAD_BYTES`, 64 KiB, chosen at channel creation):
28
+ *
29
+ * offset size as name
30
+ * ------ ---- -------- ------------------------------------------------------------------
31
+ * 0 4 int32 HEADER_STATE the word both sides `Atomics.wait` / `notify` on
32
+ * 4 4 int32 HEADER_OPCODE `OPCODE_*`, written by the client
33
+ * 8 4 int32 HEADER_REQUEST request bytes valid in the payload region
34
+ * 12 4 int32 HEADER_RESPONSE response bytes valid in the payload region
35
+ * 16 4 int32 HEADER_ERRNO 0, or the WASI preview1 errno of a file rejection
36
+ * 20 4 int32 HEADER_RESULT_LO low 32 bits of the unsigned 64-bit result
37
+ * 24 4 int32 HEADER_RESULT_HI high 32 bits of the unsigned 64-bit result
38
+ * 28 4 int32 HEADER_SEQUENCE the client's monotonic request number
39
+ * 32 4 int32 HEADER_FAULT `FAULT_*` — a transport/store failure, not a file one
40
+ * 36 4 int32 HEADER_PAYLOAD payload capacity in bytes (written once at creation)
41
+ * 40 24 int32[6] reserved, always zero
42
+ * 64 … bytes payload region
43
+ *
44
+ * `HEADER_STATE` is the whole handshake:
45
+ *
46
+ * STATE_IDLE (0) ──client publishes──→ STATE_REQUEST (1) ──server answers──→ STATE_RESPONSE (2)
47
+ * ↑ │ │
48
+ * └─────────────client consumes─────────┼─────────────────────────────────────┘
49
+ * └──server rejects the client──→ STATE_DETACHED (3)
50
+ *
51
+ * `STATE_DETACHED` is terminal: the server has closed the client's descriptors and dropped it, and
52
+ * every later client call throws instead of blocking forever.
53
+ *
54
+ * ## Doorbell layout
55
+ *
56
+ * A small separate `SharedArrayBuffer`, `DOORBELL_BYTES` (16) of `Int32Array`:
57
+ *
58
+ * index name meaning
59
+ * ----- ---------------- ----------------------------------------------------------------
60
+ * 0 DOORBELL_TICKET incremented by any client that publishes a request; the word the
61
+ * server's blocking loop waits on
62
+ * 1 DOORBELL_RUNNING 1 while the server should keep looping, 0 to ask it to return
63
+ * 2 reserved
64
+ * 3 reserved
65
+ *
66
+ * The server reads `DOORBELL_TICKET` BEFORE it scans the channels and waits on that observed value,
67
+ * so a request published during the scan makes the wait return `not-equal` immediately rather than
68
+ * being missed.
69
+ *
70
+ * ## Ordering
71
+ *
72
+ * Nothing in the payload region is atomic, and nothing needs to be. Each side writes its payload with
73
+ * ordinary stores and then publishes with `Atomics.store` on `HEADER_STATE`; the other side observes
74
+ * with `Atomics.load` on the same word before touching the payload. That store/load pair is the
75
+ * release/acquire edge, so every payload byte written before the publish is visible after the observe.
76
+ *
77
+ * ## Encoding
78
+ *
79
+ * Payloads are little-endian. Paths — and a symbolic link's TARGET, which is a path the store never
80
+ * walks — are `u32` byte length followed by UTF-8 bytes; sizes, offsets and
81
+ * timestamps are unsigned 64-bit (`bigint`) because a virtual file may exceed 2^53 in principle and
82
+ * the core store speaks `bigint` throughout. Byte counts that cannot exceed the payload region stay
83
+ * `u32`. The single numeric answer of an operation travels in the header's 64-bit result pair, not in
84
+ * the payload, so a read reply is nothing but its bytes.
85
+ */
86
+
87
+ import { FS_ERRNO, FsError } from "../core/errors";
88
+ import type { FsErrorName } from "../core/errors";
89
+
90
+ /** Int32 slot indices of the channel header. */
91
+ export const HEADER_STATE = 0;
92
+ export const HEADER_OPCODE = 1;
93
+ export const HEADER_REQUEST = 2;
94
+ export const HEADER_RESPONSE = 3;
95
+ export const HEADER_ERRNO = 4;
96
+ export const HEADER_RESULT_LO = 5;
97
+ export const HEADER_RESULT_HI = 6;
98
+ export const HEADER_SEQUENCE = 7;
99
+ export const HEADER_FAULT = 8;
100
+ export const HEADER_PAYLOAD = 9;
101
+ export const CHANNEL_HEADER_SLOTS = 16;
102
+ export const CHANNEL_HEADER_BYTES = CHANNEL_HEADER_SLOTS * 4;
103
+
104
+ /** `HEADER_STATE` values. */
105
+ export const STATE_IDLE = 0;
106
+ export const STATE_REQUEST = 1;
107
+ export const STATE_RESPONSE = 2;
108
+ export const STATE_DETACHED = 3;
109
+
110
+ /** Int32 slot indices of the doorbell. */
111
+ export const DOORBELL_TICKET = 0;
112
+ export const DOORBELL_RUNNING = 1;
113
+ export const DOORBELL_SLOTS = 4;
114
+ export const DOORBELL_BYTES = DOORBELL_SLOTS * 4;
115
+
116
+ /** The default payload region: large enough that a Postgres 8 KiB page round-trips in one request. */
117
+ export const DEFAULT_PAYLOAD_BYTES = 64 * 1024;
118
+ /** A payload region below this cannot hold the fixed part of every request. */
119
+ export const MIN_PAYLOAD_BYTES = 1024;
120
+
121
+ /**
122
+ * `HEADER_FAULT` values. A fault is NOT a file rejection: `HEADER_ERRNO` carries those and leaves the
123
+ * client working. A fault means the transport or the store itself failed.
124
+ */
125
+ export const FAULT_NONE = 0;
126
+ /** The client violated the protocol (unknown opcode, impossible length, truncated payload). */
127
+ export const FAULT_PROTOCOL = 1;
128
+ /** The store threw something that is not an `FsError` — it is very likely poisoned. */
129
+ export const FAULT_STORE = 2;
130
+ /** The server rejected or dropped the client for a reason of its own (explicit `detach`). */
131
+ export const FAULT_DETACHED = 3;
132
+
133
+ /** Every operation the broker speaks. */
134
+ export const OPCODE_OPEN = 1;
135
+ export const OPCODE_CLOSE = 2;
136
+ export const OPCODE_READ = 3;
137
+ export const OPCODE_WRITE = 4;
138
+ export const OPCODE_FSYNC = 5;
139
+ export const OPCODE_FSTAT = 6;
140
+ export const OPCODE_STAT = 7;
141
+ export const OPCODE_LSTAT = 8;
142
+ export const OPCODE_READDIR = 9;
143
+ export const OPCODE_MKDIR = 10;
144
+ export const OPCODE_RMDIR = 11;
145
+ export const OPCODE_UNLINK = 12;
146
+ export const OPCODE_RENAME = 13;
147
+ export const OPCODE_TRUNCATE = 14;
148
+ export const OPCODE_SIZE = 15;
149
+ export const OPCODE_SYMLINK = 16;
150
+ export const OPCODE_READLINK = 17;
151
+ const MIN_OPCODE = OPCODE_OPEN;
152
+ const MAX_OPCODE = OPCODE_READLINK;
153
+
154
+ export function isKnownOpcode(opcode: number): boolean {
155
+ return Number.isInteger(opcode) && opcode >= MIN_OPCODE && opcode <= MAX_OPCODE;
156
+ }
157
+
158
+ /**
159
+ * POSIX/WASI-shaped open bits. The wire carries these, never the core's node-style flag string: a WASI
160
+ * `path_open` maps its `oflags`/`fdflags`/`fs_rights_base` onto them directly, and the server is the
161
+ * only place that has to know the core's string vocabulary.
162
+ */
163
+ export const O_RDONLY = 0;
164
+ export const O_WRONLY = 1;
165
+ export const O_RDWR = 2;
166
+ export const O_ACCMODE = 3;
167
+ export const O_CREAT = 0o100;
168
+ export const O_EXCL = 0o200;
169
+ export const O_TRUNC = 0o1000;
170
+ export const O_APPEND = 0o2000;
171
+ /**
172
+ * Refuse to follow a symbolic link on the FINAL component. Linux's own bit value, and the wire form
173
+ * of a WASI `path_open` whose lookup flags omit `SYMLINK_FOLLOW`.
174
+ */
175
+ export const O_NOFOLLOW = 0o400000;
176
+ const O_KNOWN = O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC | O_APPEND | O_NOFOLLOW;
177
+
178
+ /** The stat shape on the wire: `kind` + mode + size + the three timestamps. */
179
+ export const STAT_KIND_FILE = 0;
180
+ export const STAT_KIND_DIRECTORY = 1;
181
+ export const STAT_KIND_SYMLINK = 2;
182
+ export const STAT_BYTES = 1 + 4 + 8 * 4;
183
+
184
+ /** A `readdir` reply that ran out of payload room reports the cursor to resume from; -1 means done. */
185
+ export const READDIR_DONE = -1;
186
+
187
+ /**
188
+ * How the server should satisfy one open request with the core's fixed flag-string vocabulary
189
+ * (`r`, `r+`, `w`, `w+`, `wx`, `wx+`, `a`, `a+`, `ax`, `ax+`).
190
+ *
191
+ * `readable`/`writable` are the access the CLIENT asked for, which is not always what `coreFlags`
192
+ * grants: the core has no "create without truncating and without appending" and no write-only
193
+ * non-truncating mode, so those requests open a wider core descriptor and the broker enforces the
194
+ * requested access itself on every later read/write.
195
+ */
196
+ export interface OpenPlan {
197
+ /** The core flag string to try first. */
198
+ readonly coreFlags: string;
199
+ /** Used only when `coreFlags` fails with ENOENT — the create-without-truncate two-step. */
200
+ readonly fallbackFlags: string | undefined;
201
+ /** `O_TRUNC` without `O_CREAT`: truncate the existing path to zero before opening. */
202
+ readonly truncateFirst: boolean;
203
+ /** No `O_CREAT`, but `coreFlags` would create: the server must prove the path exists first. */
204
+ readonly requireExisting: boolean;
205
+ /** The access the client asked for, enforced by the broker on top of the core descriptor. */
206
+ readonly readable: boolean;
207
+ readonly writable: boolean;
208
+ /** `false` for `O_NOFOLLOW`: a final component that IS a symbolic link must answer `ELOOP`. */
209
+ readonly follow: boolean;
210
+ }
211
+
212
+ /**
213
+ * Translate POSIX open bits into the core's vocabulary, or reject the combination with `EINVAL`.
214
+ *
215
+ * Rejected because they are meaningless rather than merely unsupported: an unknown bit, `O_EXCL`
216
+ * without `O_CREAT`, `O_TRUNC` with `O_APPEND`, and a read-only request that also creates,
217
+ * truncates, or appends.
218
+ */
219
+ export function planOpen(flags: number): OpenPlan {
220
+ if (!Number.isInteger(flags) || flags < 0 || (flags & ~O_KNOWN) !== 0) {
221
+ throw new FsError("EINVAL", `unsupported open flags: ${flags}`);
222
+ }
223
+ const access = flags & O_ACCMODE;
224
+ if (access === O_ACCMODE) throw new FsError("EINVAL", "open access mode is invalid");
225
+ const readable = access === O_RDONLY || access === O_RDWR;
226
+ const writable = access === O_WRONLY || access === O_RDWR;
227
+ const create = (flags & O_CREAT) !== 0;
228
+ const exclusive = (flags & O_EXCL) !== 0;
229
+ const truncate = (flags & O_TRUNC) !== 0;
230
+ const append = (flags & O_APPEND) !== 0;
231
+
232
+ if (exclusive && !create) throw new FsError("EINVAL", "O_EXCL requires O_CREAT");
233
+ if (truncate && append) throw new FsError("EINVAL", "O_TRUNC and O_APPEND are contradictory");
234
+ if (!writable && (create || truncate || append)) {
235
+ throw new FsError("EINVAL", "O_CREAT, O_TRUNC and O_APPEND require write access");
236
+ }
237
+
238
+ const plan = (coreFlags: string, extra: Partial<OpenPlan> = {}): OpenPlan => ({
239
+ coreFlags,
240
+ fallbackFlags: undefined,
241
+ truncateFirst: false,
242
+ requireExisting: false,
243
+ readable,
244
+ writable,
245
+ follow: (flags & O_NOFOLLOW) === 0,
246
+ ...extra,
247
+ });
248
+
249
+ // Exclusive creation can never truncate anything (the file must not exist), so `wx`/`ax` serve
250
+ // both the with- and without-O_TRUNC spellings.
251
+ if (exclusive) return plan(append ? (readable ? "ax+" : "ax") : readable ? "wx+" : "wx");
252
+ if (append && create) return plan(readable ? "a+" : "a");
253
+ if (truncate && create) return plan(readable ? "w+" : "w");
254
+ // No O_CREAT past this point: every core append flag creates, so the server proves existence first.
255
+ if (append) return plan(readable ? "a+" : "a", { requireExisting: true });
256
+ if (truncate) return plan("r+", { truncateFirst: true });
257
+ // Create-without-truncate: reuse the file if it is there, otherwise create it empty. `r+` is wider
258
+ // than a write-only request asked for, which is why `writable`/`readable` are carried separately.
259
+ if (create) return plan("r+", { fallbackFlags: "w+" });
260
+ return plan(readable && !writable ? "r" : "r+");
261
+ }
262
+
263
+ const textEncoder = new TextEncoder();
264
+ const textDecoder = new TextDecoder("utf-8", { fatal: true });
265
+
266
+ /** Thrown when a payload cannot hold what a caller is trying to put in it. */
267
+ export class PayloadOverflowError extends Error {
268
+ constructor(needed: number, capacity: number) {
269
+ super(`broker payload needs ${needed} bytes but the channel region holds ${capacity}`);
270
+ this.name = "PayloadOverflowError";
271
+ }
272
+ }
273
+
274
+ /** Thrown when a payload does not decode — always a protocol violation by the peer that wrote it. */
275
+ export class PayloadDecodeError extends Error {
276
+ constructor(message: string) {
277
+ super(`broker payload is malformed: ${message}`);
278
+ this.name = "PayloadDecodeError";
279
+ }
280
+ }
281
+
282
+ /** Sequential little-endian writer over a channel's payload region. */
283
+ export class PayloadWriter {
284
+ readonly #view: DataView;
285
+ readonly #bytes: Uint8Array;
286
+ #cursor = 0;
287
+
288
+ constructor(payload: Uint8Array) {
289
+ this.#bytes = payload;
290
+ this.#view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
291
+ }
292
+
293
+ get length(): number {
294
+ return this.#cursor;
295
+ }
296
+
297
+ get remaining(): number {
298
+ return this.#bytes.byteLength - this.#cursor;
299
+ }
300
+
301
+ u8(value: number): void {
302
+ this.#view.setUint8(this.#reserve(1), value);
303
+ }
304
+
305
+ u32(value: number): void {
306
+ this.#view.setUint32(this.#reserve(4), value, true);
307
+ }
308
+
309
+ i32(value: number): void {
310
+ this.#view.setInt32(this.#reserve(4), value, true);
311
+ }
312
+
313
+ u64(value: bigint): void {
314
+ this.#view.setBigUint64(this.#reserve(8), value, true);
315
+ }
316
+
317
+ bytes(source: Uint8Array): void {
318
+ this.#bytes.set(source, this.#reserve(source.byteLength));
319
+ }
320
+
321
+ string(value: string): void {
322
+ const encoded = textEncoder.encode(value);
323
+ this.u32(encoded.byteLength);
324
+ this.bytes(encoded);
325
+ }
326
+
327
+ /**
328
+ * Discard everything written after `to`, backing out a field that did not fit. A `string` reserves
329
+ * its length prefix before its bytes, so a name that overflows can leave four bytes behind.
330
+ */
331
+ rewind(to: number): void {
332
+ if (!Number.isSafeInteger(to) || to < 0 || to > this.#cursor) {
333
+ throw new RangeError("the payload rewind target is outside what has been written");
334
+ }
335
+ this.#cursor = to;
336
+ }
337
+
338
+ /**
339
+ * A mutable view over `count` bytes already written at `at` — for a counter that has to be reserved
340
+ * before its value is known (a `readdir` page fills until the payload runs out).
341
+ */
342
+ patch(at: number, count: number): DataView {
343
+ if (!Number.isSafeInteger(at) || !Number.isSafeInteger(count) || at < 0 || count < 0 || at + count > this.#cursor) {
344
+ throw new RangeError("the payload patch range is outside what has been written");
345
+ }
346
+ return new DataView(this.#bytes.buffer, this.#bytes.byteOffset + at, count);
347
+ }
348
+
349
+ #reserve(count: number): number {
350
+ if (count > this.remaining) throw new PayloadOverflowError(this.#cursor + count, this.#bytes.byteLength);
351
+ const at = this.#cursor;
352
+ this.#cursor += count;
353
+ return at;
354
+ }
355
+ }
356
+
357
+ /** Sequential little-endian reader over a channel's payload region. */
358
+ export class PayloadReader {
359
+ readonly #view: DataView;
360
+ readonly #bytes: Uint8Array;
361
+ #cursor = 0;
362
+
363
+ constructor(payload: Uint8Array, length: number) {
364
+ if (!Number.isSafeInteger(length) || length < 0 || length > payload.byteLength) {
365
+ throw new PayloadDecodeError(`declared length ${length} is outside the payload region`);
366
+ }
367
+ this.#bytes = payload.subarray(0, length);
368
+ this.#view = new DataView(payload.buffer, payload.byteOffset, length);
369
+ }
370
+
371
+ get remaining(): number {
372
+ return this.#bytes.byteLength - this.#cursor;
373
+ }
374
+
375
+ u8(): number {
376
+ return this.#view.getUint8(this.#take(1));
377
+ }
378
+
379
+ u32(): number {
380
+ return this.#view.getUint32(this.#take(4), true);
381
+ }
382
+
383
+ i32(): number {
384
+ return this.#view.getInt32(this.#take(4), true);
385
+ }
386
+
387
+ u64(): bigint {
388
+ return this.#view.getBigUint64(this.#take(8), true);
389
+ }
390
+
391
+ bytes(count: number): Uint8Array {
392
+ return this.#bytes.subarray(this.#take(count), this.#cursor);
393
+ }
394
+
395
+ string(): string {
396
+ const length = this.u32();
397
+ // `.slice()`, not the `.subarray()` `bytes()` hands out: a payload region lives in a
398
+ // `SharedArrayBuffer`, and Chrome REFUSES a shared-backed view to `TextDecoder.decode()`
399
+ // ("The provided ArrayBufferView value must not be shared" — the same `[AllowShared]` rule
400
+ // that bites `crypto.getRandomValues`). Node accepts it, so a browser is the only place this
401
+ // shows up, and it shows up as the SERVER rejecting every path-carrying request as malformed
402
+ // and detaching the client. Paths are short; the copy costs nothing.
403
+ const raw = this.bytes(length);
404
+ try {
405
+ return textDecoder.decode(raw.slice());
406
+ } catch (cause) {
407
+ throw new PayloadDecodeError(`a string is not valid UTF-8: ${String(cause)}`);
408
+ }
409
+ }
410
+
411
+ #take(count: number): number {
412
+ if (!Number.isSafeInteger(count) || count < 0) throw new PayloadDecodeError(`length ${count} is invalid`);
413
+ if (count > this.remaining) throw new PayloadDecodeError("the payload ended mid-field");
414
+ const at = this.#cursor;
415
+ this.#cursor += count;
416
+ return at;
417
+ }
418
+ }
419
+
420
+ /** Split an unsigned 64-bit result into the header's low/high `int32` pair. */
421
+ export function splitResult(value: bigint): { readonly lo: number; readonly hi: number } {
422
+ if (value < 0n || value > 0xffff_ffff_ffff_ffffn) {
423
+ throw new RangeError(`broker result ${value} is outside the unsigned 64-bit range`);
424
+ }
425
+ return { lo: Number(value & 0xffff_ffffn) | 0, hi: Number(value >> 32n) | 0 };
426
+ }
427
+
428
+ /** Rejoin the header's low/high `int32` pair into an unsigned 64-bit result. */
429
+ export function joinResult(lo: number, hi: number): bigint {
430
+ return (BigInt(hi >>> 0) << 32n) | BigInt(lo >>> 0);
431
+ }
432
+
433
+ /** The stat shape both sides exchange; `bigint` everywhere the core is `bigint`. */
434
+ export interface BrokerStat {
435
+ /** `symlink` only ever comes back from `lstat`; `size` is then the target's UTF-8 byte length. */
436
+ readonly kind: "directory" | "file" | "symlink";
437
+ readonly mode: number;
438
+ readonly size: bigint;
439
+ readonly atimeMs: bigint;
440
+ readonly mtimeMs: bigint;
441
+ readonly ctimeMs: bigint;
442
+ }
443
+
444
+ export function writeStat(writer: PayloadWriter, stat: BrokerStat): void {
445
+ writer.u8(
446
+ stat.kind === "directory" ? STAT_KIND_DIRECTORY : stat.kind === "symlink" ? STAT_KIND_SYMLINK : STAT_KIND_FILE,
447
+ );
448
+ writer.u32(stat.mode);
449
+ writer.u64(stat.size);
450
+ writer.u64(stat.atimeMs);
451
+ writer.u64(stat.mtimeMs);
452
+ writer.u64(stat.ctimeMs);
453
+ }
454
+
455
+ export function readStat(reader: PayloadReader): BrokerStat {
456
+ const code = reader.u8();
457
+ const kind = code === STAT_KIND_DIRECTORY ? "directory" : code === STAT_KIND_SYMLINK ? "symlink" : "file";
458
+ return {
459
+ kind,
460
+ mode: reader.u32(),
461
+ size: reader.u64(),
462
+ atimeMs: reader.u64(),
463
+ mtimeMs: reader.u64(),
464
+ ctimeMs: reader.u64(),
465
+ };
466
+ }
467
+
468
+ /** A channel's two shared buffers, in the form that survives `postMessage`. */
469
+ export interface RepackedChannelTransfer {
470
+ readonly id: number;
471
+ readonly channel: SharedArrayBuffer;
472
+ readonly doorbell: SharedArrayBuffer;
473
+ }
474
+
475
+ /**
476
+ * The shared word one blocking server loop waits on. Both sides hold the same buffer; a client only
477
+ * ever rings it, and only the host that created it may ask the loop to stop.
478
+ */
479
+ export class RepackedDoorbell {
480
+ readonly buffer: SharedArrayBuffer;
481
+ readonly #slots: Int32Array;
482
+
483
+ private constructor(buffer: SharedArrayBuffer) {
484
+ if (buffer.byteLength < DOORBELL_BYTES) {
485
+ throw new RangeError(`a broker doorbell needs at least ${DOORBELL_BYTES} bytes`);
486
+ }
487
+ this.buffer = buffer;
488
+ this.#slots = new Int32Array(buffer, 0, DOORBELL_SLOTS);
489
+ }
490
+
491
+ static create(): RepackedDoorbell {
492
+ const doorbell = new RepackedDoorbell(new SharedArrayBuffer(DOORBELL_BYTES));
493
+ Atomics.store(doorbell.#slots, DOORBELL_RUNNING, 1);
494
+ return doorbell;
495
+ }
496
+
497
+ /** Rebuild the doorbell around a buffer that arrived over `postMessage`. */
498
+ static attach(buffer: SharedArrayBuffer): RepackedDoorbell {
499
+ return new RepackedDoorbell(buffer);
500
+ }
501
+
502
+ /** The value a server must observe BEFORE it scans, so a concurrent request cannot be missed. */
503
+ ticket(): number {
504
+ return Atomics.load(this.#slots, DOORBELL_TICKET);
505
+ }
506
+
507
+ /** Announce that some channel now holds a request. */
508
+ ring(): void {
509
+ Atomics.add(this.#slots, DOORBELL_TICKET, 1);
510
+ Atomics.notify(this.#slots, DOORBELL_TICKET);
511
+ }
512
+
513
+ running(): boolean {
514
+ return Atomics.load(this.#slots, DOORBELL_RUNNING) === 1;
515
+ }
516
+
517
+ /**
518
+ * Ask a blocking `serveForever()` to return. This is the only way to stop it from another thread:
519
+ * once inside the loop the server never reaches its own event loop, so `postMessage` cannot reach it.
520
+ */
521
+ requestStop(): void {
522
+ Atomics.store(this.#slots, DOORBELL_RUNNING, 0);
523
+ this.ring();
524
+ }
525
+
526
+ /** Undo a `requestStop()` so the same doorbell can drive another loop. */
527
+ resume(): void {
528
+ Atomics.store(this.#slots, DOORBELL_RUNNING, 1);
529
+ }
530
+
531
+ /** Block until the ticket leaves `observed`, or the timeout elapses. */
532
+ wait(observed: number, timeoutMs: number): "ok" | "not-equal" | "timed-out" {
533
+ return Atomics.wait(this.#slots, DOORBELL_TICKET, observed, timeoutMs);
534
+ }
535
+
536
+ /** The non-blocking form, for a host that must not park its thread. */
537
+ waitAsync(observed: number, timeoutMs: number): Promise<"ok" | "not-equal" | "timed-out"> {
538
+ const result = Atomics.waitAsync(this.#slots, DOORBELL_TICKET, observed, timeoutMs);
539
+ return result.async ? result.value : Promise.resolve(result.value);
540
+ }
541
+ }
542
+
543
+ /**
544
+ * One client's request/response channel. Both the client and the server hold an instance over the
545
+ * same `SharedArrayBuffer`; neither owns the memory, and nothing but the header words is atomic.
546
+ */
547
+ export class RepackedChannel {
548
+ readonly id: number;
549
+ readonly buffer: SharedArrayBuffer;
550
+ readonly doorbell: RepackedDoorbell;
551
+ readonly header: Int32Array;
552
+ readonly payload: Uint8Array;
553
+
554
+ private constructor(id: number, buffer: SharedArrayBuffer, doorbell: RepackedDoorbell) {
555
+ this.id = id;
556
+ this.buffer = buffer;
557
+ this.doorbell = doorbell;
558
+ this.header = new Int32Array(buffer, 0, CHANNEL_HEADER_SLOTS);
559
+ this.payload = new Uint8Array(buffer, CHANNEL_HEADER_BYTES);
560
+ }
561
+
562
+ static create(options: { id: number; doorbell: RepackedDoorbell; payloadBytes?: number }): RepackedChannel {
563
+ const payloadBytes = options.payloadBytes ?? DEFAULT_PAYLOAD_BYTES;
564
+ if (!Number.isSafeInteger(payloadBytes) || payloadBytes < MIN_PAYLOAD_BYTES) {
565
+ throw new RangeError(`a broker channel payload must be at least ${MIN_PAYLOAD_BYTES} bytes`);
566
+ }
567
+ if (!Number.isSafeInteger(options.id) || options.id < 0) {
568
+ throw new RangeError("a broker channel id must be a non-negative safe integer");
569
+ }
570
+ const channel = new RepackedChannel(
571
+ options.id,
572
+ new SharedArrayBuffer(CHANNEL_HEADER_BYTES + payloadBytes),
573
+ options.doorbell,
574
+ );
575
+ Atomics.store(channel.header, HEADER_PAYLOAD, payloadBytes);
576
+ Atomics.store(channel.header, HEADER_STATE, STATE_IDLE);
577
+ return channel;
578
+ }
579
+
580
+ /** Rebuild a channel around buffers that arrived over `postMessage`. */
581
+ static attach(transfer: RepackedChannelTransfer): RepackedChannel {
582
+ const doorbell = RepackedDoorbell.attach(transfer.doorbell);
583
+ if (transfer.channel.byteLength < CHANNEL_HEADER_BYTES + MIN_PAYLOAD_BYTES) {
584
+ throw new RangeError("the broker channel buffer is too small to be a channel");
585
+ }
586
+ const channel = new RepackedChannel(transfer.id, transfer.channel, doorbell);
587
+ const declared = Atomics.load(channel.header, HEADER_PAYLOAD);
588
+ if (declared !== channel.payload.byteLength) {
589
+ throw new RangeError(`the broker channel declares ${declared} payload bytes but carries a different region`);
590
+ }
591
+ return channel;
592
+ }
593
+
594
+ /** The shape to hand to `postMessage`. */
595
+ transfer(): RepackedChannelTransfer {
596
+ return { id: this.id, channel: this.buffer, doorbell: this.doorbell.buffer };
597
+ }
598
+
599
+ get payloadBytes(): number {
600
+ return this.payload.byteLength;
601
+ }
602
+
603
+ state(): number {
604
+ return Atomics.load(this.header, HEADER_STATE);
605
+ }
606
+ }
607
+
608
+ /** The errno of a rejection, or `undefined` when it is not a plain file rejection. */
609
+ export function errnoOf(cause: unknown): number | undefined {
610
+ return cause instanceof FsError ? cause.code : undefined;
611
+ }
612
+
613
+ /** The core error name behind a wire errno, or `undefined` for a code the core never produces. */
614
+ export function fsErrorNameOf(code: number): FsErrorName | undefined {
615
+ for (const name of Object.keys(FS_ERRNO) as FsErrorName[]) {
616
+ if (FS_ERRNO[name] === code) return name;
617
+ }
618
+ return undefined;
619
+ }
620
+
621
+ /** Readable form of a wire errno, for a message. */
622
+ export function errnoName(code: number): string {
623
+ return fsErrorNameOf(code) ?? `errno ${code}`;
624
+ }