@pgxsinkit/pgwasm-c 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 (85) hide show
  1. package/LICENSE +23 -0
  2. package/NOTICE +1890 -0
  3. package/README.md +79 -0
  4. package/artefacts/amcheck.tar.gz +0 -0
  5. package/artefacts/initdb.d.ts +6 -0
  6. package/artefacts/initdb.js +2 -0
  7. package/artefacts/initdb.wasm +0 -0
  8. package/artefacts/postgres.d.ts +6 -0
  9. package/artefacts/postgres.data +37595 -8
  10. package/artefacts/postgres.js +2 -0
  11. package/artefacts/postgres.wasm +0 -0
  12. package/artefacts/prepopulated.tar.gz +0 -0
  13. package/dist/artefact-pins.d.ts +57 -0
  14. package/dist/artefact-pins.d.ts.map +1 -0
  15. package/dist/artefacts.d.ts +37 -0
  16. package/dist/artefacts.d.ts.map +1 -0
  17. package/dist/build.d.ts +53 -0
  18. package/dist/build.d.ts.map +1 -0
  19. package/dist/contrib/amcheck.d.ts +9 -0
  20. package/dist/contrib/amcheck.d.ts.map +1 -0
  21. package/dist/contrib/amcheck.js +13 -0
  22. package/dist/contrib/amcheck.js.map +10 -0
  23. package/dist/host/artefact-loader.d.ts +9 -0
  24. package/dist/host/artefact-loader.d.ts.map +1 -0
  25. package/dist/host/command-line.d.ts +11 -0
  26. package/dist/host/command-line.d.ts.map +1 -0
  27. package/dist/host/data-dir.d.ts +11 -0
  28. package/dist/host/data-dir.d.ts.map +1 -0
  29. package/dist/host/emscripten.d.ts +143 -0
  30. package/dist/host/emscripten.d.ts.map +1 -0
  31. package/dist/host/exit-code.d.ts +12 -0
  32. package/dist/host/exit-code.d.ts.map +1 -0
  33. package/dist/host/extensions.d.ts +15 -0
  34. package/dist/host/extensions.d.ts.map +1 -0
  35. package/dist/host/initdb.d.ts +25 -0
  36. package/dist/host/initdb.d.ts.map +1 -0
  37. package/dist/host/mounts/file.d.ts +17 -0
  38. package/dist/host/mounts/file.d.ts.map +1 -0
  39. package/dist/host/mounts/idb.d.ts +32 -0
  40. package/dist/host/mounts/idb.d.ts.map +1 -0
  41. package/dist/host/mounts/index.d.ts +6 -0
  42. package/dist/host/mounts/index.d.ts.map +1 -0
  43. package/dist/host/mounts/memory.d.ts +12 -0
  44. package/dist/host/mounts/memory.d.ts.map +1 -0
  45. package/dist/host/mounts/storage-mount.d.ts +15 -0
  46. package/dist/host/mounts/storage-mount.d.ts.map +1 -0
  47. package/dist/host/mounts/vfs.d.ts +15 -0
  48. package/dist/host/mounts/vfs.d.ts.map +1 -0
  49. package/dist/host/paths.d.ts +10 -0
  50. package/dist/host/paths.d.ts.map +1 -0
  51. package/dist/host/postgres-instance.d.ts +63 -0
  52. package/dist/host/postgres-instance.d.ts.map +1 -0
  53. package/dist/host/vfs-mount.d.ts +10 -0
  54. package/dist/host/vfs-mount.d.ts.map +1 -0
  55. package/dist/index.d.ts +4 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +1393 -0
  58. package/dist/index.js.map +26 -0
  59. package/dist/prepopulated.d.ts +28 -0
  60. package/dist/prepopulated.d.ts.map +1 -0
  61. package/dist/prepopulated.js +15 -0
  62. package/dist/prepopulated.js.map +10 -0
  63. package/package.json +56 -0
  64. package/src/artefact-pins.ts +36 -0
  65. package/src/artefacts.ts +46 -0
  66. package/src/build.ts +326 -0
  67. package/src/contrib/amcheck.ts +17 -0
  68. package/src/host/artefact-loader.ts +75 -0
  69. package/src/host/command-line.ts +64 -0
  70. package/src/host/data-dir.ts +70 -0
  71. package/src/host/emscripten.ts +158 -0
  72. package/src/host/exit-code.ts +29 -0
  73. package/src/host/extensions.ts +83 -0
  74. package/src/host/initdb.ts +180 -0
  75. package/src/host/mounts/file.ts +44 -0
  76. package/src/host/mounts/idb.ts +152 -0
  77. package/src/host/mounts/index.ts +26 -0
  78. package/src/host/mounts/memory.ts +22 -0
  79. package/src/host/mounts/storage-mount.ts +15 -0
  80. package/src/host/mounts/vfs.ts +43 -0
  81. package/src/host/paths.ts +18 -0
  82. package/src/host/postgres-instance.ts +495 -0
  83. package/src/host/vfs-mount.ts +258 -0
  84. package/src/index.ts +3 -0
  85. package/src/prepopulated.ts +38 -0
package/src/build.ts ADDED
@@ -0,0 +1,326 @@
1
+ // Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
2
+ // — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
3
+
4
+ import type {
5
+ BlobDevice,
6
+ BootRequest,
7
+ BuildCapabilities,
8
+ BuildIdentity,
9
+ DataDirEntry,
10
+ MountedDataDirectory,
11
+ PostgresBuild,
12
+ RunningPostgres,
13
+ StartOptions,
14
+ TarEntry,
15
+ WireSession,
16
+ } from "@pgxsinkit/pgwasm/build";
17
+
18
+ import { ARTEFACT_RELEASE } from "./artefact-pins";
19
+ import { type CBuildArtefactSet, pinnedCBuildArtefacts } from "./artefacts";
20
+ import { bytesOf, compileModule, loadBundle, prefetch } from "./host/artefact-loader";
21
+ import { readDataDirEntries, readDataDirFile, writeDataDirEntries, writeDataDirFile } from "./host/data-dir";
22
+ import type { PostgresModule } from "./host/emscripten";
23
+ import { fetchExtensionBundle, installExtensionFiles } from "./host/extensions";
24
+ import { runInitdb } from "./host/initdb";
25
+ import { mountFor, type StorageMount } from "./host/mounts";
26
+ import { DEFAULT_START_PARAMS, PostgresInstance } from "./host/postgres-instance";
27
+
28
+ /**
29
+ * The C build's identity, recorded in every data directory it creates (ADR-0063). Its release and data
30
+ * format are the pinned pgwasm-postgres release's (`bun run pgwasm:pin` writes both; ADR-0064): the
31
+ * release is the build's name in version(), and `pgwasm:pin` refuses a release of another data format.
32
+ */
33
+ export const C_BUILD_IDENTITY: BuildIdentity = {
34
+ name: "c",
35
+ dataFormat: ARTEFACT_RELEASE.dataFormat,
36
+ // Every data directory made before builds were recorded was made by this build.
37
+ claimsUnmarkedDirectories: true,
38
+ release: ARTEFACT_RELEASE.name,
39
+ };
40
+
41
+ const C_BUILD_CAPABILITIES: BuildCapabilities = {
42
+ sessions: 1,
43
+ requiresCrossOriginIsolation: false,
44
+ filesystems: ["memory", "idb", "file", "vfs"],
45
+ synchronousExchange: true,
46
+ blobDevice: true,
47
+ };
48
+
49
+ /**
50
+ * The C build's artefacts, fetched and compiled ahead of a boot (e.g. by an app's warm module on an earlier
51
+ * screen, from the URLs in `cBuildArtefacts`). A field left out is loaded by the build itself.
52
+ */
53
+ export interface CBuildAssets {
54
+ readonly postgresWasmModule?: WebAssembly.Module;
55
+ readonly initdbWasmModule?: WebAssembly.Module;
56
+ readonly fsBundle?: Blob;
57
+ }
58
+
59
+ export interface CBuildOptions {
60
+ /** The Postgres module, compiled ahead (e.g. on an earlier screen). */
61
+ readonly postgresWasmModule?: WebAssembly.Module | Promise<WebAssembly.Module>;
62
+ /** The initdb module, compiled ahead; used only when a data directory is created. */
63
+ readonly initdbWasmModule?: WebAssembly.Module | Promise<WebAssembly.Module>;
64
+ /** The filesystem bundle, fetched ahead. */
65
+ readonly fsBundle?: Blob | Promise<Blob>;
66
+ /**
67
+ * The artefacts being warmed ahead. A boot waits for the promise to settle and uses each asset it
68
+ * resolves with in place of that artefact's own load. The warm-up is only an accelerator: a rejected
69
+ * promise never fails a boot, the build loads the artefacts itself instead. An explicit
70
+ * `postgresWasmModule`, `initdbWasmModule` or `fsBundle` wins over the same asset.
71
+ */
72
+ readonly assets?: Promise<CBuildAssets>;
73
+ /** @internal A test's view of each Postgres module the build instantiates. */
74
+ readonly onPostgresModule?: (module: PostgresModule) => void;
75
+ /** @internal Every command line initdb runs through the host. */
76
+ readonly onInitdbCommand?: (command: string) => void;
77
+ }
78
+
79
+ interface Resolved {
80
+ readonly artefacts: CBuildArtefactSet;
81
+ readonly postgresWasm: () => Promise<WebAssembly.Module>;
82
+ readonly initdbWasm: () => Promise<WebAssembly.Module>;
83
+ readonly fsBundle: () => Promise<ArrayBuffer>;
84
+ readonly options: CBuildOptions;
85
+ }
86
+
87
+ class CRunningPostgres implements RunningPostgres {
88
+ readonly #instance: PostgresInstance;
89
+ readonly #mount: StorageMount;
90
+ #sessionOpened = false;
91
+ readonly blob: BlobDevice;
92
+
93
+ constructor(instance: PostgresInstance, mount: StorageMount) {
94
+ this.#instance = instance;
95
+ this.#mount = mount;
96
+ this.blob = {
97
+ setReadSource: (data) => instance.setBlobReadSource(data),
98
+ takeWritten: () => instance.takeBlobWritten(),
99
+ };
100
+ }
101
+
102
+ async openSession(): Promise<WireSession> {
103
+ if (this.#sessionOpened) throw new Error("The C build holds a single session, and it is open.");
104
+ this.#sessionOpened = true;
105
+ const instance = this.#instance;
106
+ return {
107
+ exchange: (message, onData) => instance.exchange(message, onData),
108
+ onUnsolicited: undefined,
109
+ close: async () => {},
110
+ };
111
+ }
112
+
113
+ async persist(relaxed: boolean): Promise<void> {
114
+ await this.#mount.persist(this.#instance.module, relaxed);
115
+ }
116
+
117
+ async readEntries(): Promise<DataDirEntry[]> {
118
+ return readDataDirEntries(this.#instance.module.FS);
119
+ }
120
+
121
+ async shutdown(): Promise<void> {
122
+ this.#instance.shutdown();
123
+ }
124
+
125
+ async release(options: { readonly afterFailedBoot?: boolean } = {}): Promise<void> {
126
+ try {
127
+ if (options.afterFailedBoot) await this.#mount.cleanupFailedInit(this.#instance.module);
128
+ else await this.#mount.close(this.#instance.module);
129
+ } finally {
130
+ this.#instance.dispose(options.afterFailedBoot ? 1 : 0);
131
+ }
132
+ }
133
+ }
134
+
135
+ class CMountedDataDirectory implements MountedDataDirectory {
136
+ readonly #instance: PostgresInstance;
137
+ readonly #mount: StorageMount;
138
+ readonly #request: BootRequest;
139
+ readonly #resolved: Resolved;
140
+ readonly #extensionBundles: Promise<TarEntry[][]>;
141
+
142
+ constructor(
143
+ instance: PostgresInstance,
144
+ mount: StorageMount,
145
+ request: BootRequest,
146
+ resolved: Resolved,
147
+ extensionBundles: Promise<TarEntry[][]>,
148
+ ) {
149
+ this.#instance = instance;
150
+ this.#mount = mount;
151
+ this.#request = request;
152
+ this.#resolved = resolved;
153
+ this.#extensionBundles = extensionBundles;
154
+ }
155
+
156
+ get #FS() {
157
+ return this.#instance.module.FS;
158
+ }
159
+
160
+ async readFile(path: string): Promise<Uint8Array | undefined> {
161
+ return readDataDirFile(this.#FS, path);
162
+ }
163
+
164
+ async createCluster(): Promise<void> {
165
+ // initdb runs on a scratch instance of its own, never on the mounted storage: its backend
166
+ // invocations reset the instance's heap between runs, and a filesystem holding exclusive resources
167
+ // (an OPFS store's handles) must not be initialised twice.
168
+ const scratch = await PostgresInstance.create({
169
+ glue: this.#resolved.artefacts,
170
+ wasmModule: this.#resolved.postgresWasm(),
171
+ fsBundle: this.#resolved.fsBundle(),
172
+ user: this.#request.user,
173
+ database: this.#request.database,
174
+ debug: this.#request.debug,
175
+ });
176
+ try {
177
+ const result = await runInitdb({
178
+ createInitdbModule: this.#resolved.artefacts.createInitdbModule,
179
+ postgres: scratch,
180
+ initdbWasm: await this.#resolved.initdbWasm(),
181
+ debug: this.#request.debug,
182
+ ...(this.#resolved.options.onInitdbCommand ? { onCommand: this.#resolved.options.onInitdbCommand } : {}),
183
+ });
184
+ if (result.exitCode !== 0 && !result.stderr.includes("exists but is not empty")) {
185
+ throw new Error(`initdb failed to create the data directory (exit ${result.exitCode}): ${result.stderr}`);
186
+ }
187
+ writeDataDirEntries(this.#FS, readDataDirEntries(scratch.module.FS));
188
+ } finally {
189
+ scratch.dispose(0);
190
+ }
191
+ }
192
+
193
+ async writeEntries(entries: readonly DataDirEntry[]): Promise<void> {
194
+ writeDataDirEntries(this.#FS, entries);
195
+ }
196
+
197
+ async writeFile(path: string, data: Uint8Array): Promise<void> {
198
+ writeDataDirFile(this.#FS, path, data);
199
+ }
200
+
201
+ async persist(): Promise<void> {
202
+ await this.#mount.persist(this.#instance.module, false);
203
+ }
204
+
205
+ async start(options: StartOptions): Promise<RunningPostgres> {
206
+ const log = (...args: unknown[]) => {
207
+ if (this.#request.debug > 0) console.log(...args);
208
+ };
209
+ await installExtensionFiles(this.#instance.module, await this.#extensionBundles, log);
210
+ this.#instance.startSingleMode([
211
+ ...DEFAULT_START_PARAMS,
212
+ ...(this.#request.debug > 0 ? ["-d", String(this.#request.debug)] : []),
213
+ ...Object.entries(options.settings).flatMap(([name, value]) => ["-c", `${name}=${value}`]),
214
+ ]);
215
+ return new CRunningPostgres(this.#instance, this.#mount);
216
+ }
217
+
218
+ async release(): Promise<void> {
219
+ try {
220
+ await this.#mount.cleanupFailedInit(this.#instance.module);
221
+ } finally {
222
+ this.#instance.dispose(1);
223
+ }
224
+ }
225
+ }
226
+
227
+ /**
228
+ * A C build, optionally with its artefacts fetched and compiled ahead. `cBuild` is the build with
229
+ * defaults; a build object can boot any number of databases.
230
+ */
231
+ export function createCBuild(options: CBuildOptions = {}): PostgresBuild {
232
+ return createCBuildFrom(C_BUILD_IDENTITY, pinnedCBuildArtefacts, options);
233
+ }
234
+
235
+ /**
236
+ * @internal A C build on the given artefacts, recording the given identity: what {@link createCBuild}
237
+ * builds on the pinned release's. Not exported from the package; the IndexedDB browser lane reaches it
238
+ * from source to boot an earlier release's glue and files, so the stores that release wrote can be opened
239
+ * by the current build (tests/e2e/pgwasm-idb/continuity-builds.ts). That list starts empty at 18.6.2: its
240
+ * filesystem root changed, so no earlier release's stores open under it; 18.6.2 is the first entry.
241
+ */
242
+ export function createCBuildFrom(
243
+ identity: BuildIdentity,
244
+ artefacts: CBuildArtefactSet,
245
+ options: CBuildOptions = {},
246
+ ): PostgresBuild {
247
+ // Settled once, and handled here: a failed warm-up means the lazy load, never an unhandled rejection.
248
+ const warmed: Promise<CBuildAssets | undefined> =
249
+ options.assets === undefined
250
+ ? Promise.resolve(undefined)
251
+ : options.assets.then(
252
+ (assets) => assets,
253
+ () => undefined,
254
+ );
255
+ const resolved: Resolved = {
256
+ artefacts,
257
+ postgresWasm: async () => {
258
+ const module = options.postgresWasmModule ?? (await warmed)?.postgresWasmModule;
259
+ return module === undefined ? compileModule(artefacts.postgresWasm) : module;
260
+ },
261
+ initdbWasm: async () => {
262
+ const module = options.initdbWasmModule ?? (await warmed)?.initdbWasmModule;
263
+ return module === undefined ? compileModule(artefacts.initdbWasm) : module;
264
+ },
265
+ fsBundle: async () => {
266
+ const bundle = options.fsBundle ?? (await warmed)?.fsBundle;
267
+ return bundle === undefined ? loadBundle(artefacts.fsBundle) : bytesOf(bundle);
268
+ },
269
+ options,
270
+ };
271
+
272
+ // Everything a boot waits on before its own work: the warm-up, and the explicit Postgres module and
273
+ // filesystem bundle when given as promises. Settled, never rejected: a rejected one fails (or falls back in)
274
+ // the boot itself, which is where that belongs.
275
+ const prepared: Promise<void> = Promise.allSettled([warmed, options.postgresWasmModule, options.fsBundle]).then(
276
+ () => undefined,
277
+ );
278
+
279
+ return {
280
+ identity,
281
+ capabilities: C_BUILD_CAPABILITIES,
282
+ prepare: () => prepared,
283
+ async boot(request: BootRequest): Promise<MountedDataDirectory> {
284
+ const extensionBundles = Promise.all(request.extensions.map((extension) => fetchExtensionBundle(extension)));
285
+ // Awaited in start(); a failure before then must not surface as unhandled.
286
+ extensionBundles.catch(() => undefined);
287
+ // Start the downloads the warm-up did not cover now; the boot needs them in turn.
288
+ const assets = await warmed;
289
+ if (options.postgresWasmModule === undefined && assets?.postgresWasmModule === undefined) {
290
+ prefetch(artefacts.postgresWasm);
291
+ }
292
+ if (options.initdbWasmModule === undefined && assets?.initdbWasmModule === undefined) {
293
+ prefetch(artefacts.initdbWasm);
294
+ }
295
+
296
+ const mount = mountFor(request.storage);
297
+ await mount.acquire();
298
+ let instance: PostgresInstance | undefined;
299
+ try {
300
+ instance = await PostgresInstance.create({
301
+ glue: artefacts,
302
+ wasmModule: resolved.postgresWasm(),
303
+ fsBundle: resolved.fsBundle(),
304
+ user: request.user,
305
+ database: request.database,
306
+ debug: request.debug,
307
+ ...(mount.preRun ? { mountPreRun: mount.preRun } : {}),
308
+ ...(options.onPostgresModule ? { onModule: options.onPostgresModule } : {}),
309
+ });
310
+ await mount.initialSync(instance.module);
311
+ } catch (error) {
312
+ try {
313
+ await mount.cleanupFailedInit(instance?.module);
314
+ } catch {
315
+ // The boot already failed; keep its cause.
316
+ }
317
+ instance?.dispose(1);
318
+ throw error;
319
+ }
320
+ return new CMountedDataDirectory(instance, mount, request, resolved, extensionBundles);
321
+ },
322
+ };
323
+ }
324
+
325
+ /** The C build with its defaults: the artefacts load from next to this module when first booted. */
326
+ export const cBuild: PostgresBuild = createCBuild();
@@ -0,0 +1,17 @@
1
+ // Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
2
+ // — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
3
+
4
+ import type { ServerExtension } from "@pgxsinkit/pgwasm/build";
5
+
6
+ /**
7
+ * `amcheck`, compiled for the C build: pass it in `extensions`, then `CREATE EXTENSION amcheck`.
8
+ *
9
+ * The bundle URL sits in this entry point, which is emitted at its own depth (dist/contrib/), so the
10
+ * relative reference stays valid once bundled.
11
+ */
12
+ export const amcheck: ServerExtension = {
13
+ kind: "server",
14
+ name: "amcheck",
15
+ build: "c",
16
+ bundle: new URL("../../artefacts/amcheck.tar.gz", import.meta.url),
17
+ };
@@ -0,0 +1,75 @@
1
+ // Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
2
+ // — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
3
+
4
+ /**
5
+ * Fetching and compiling the artefacts. One path for Bun and browsers: Bun's `fetch` reads `file://`
6
+ * URLs and serves `.wasm` as `application/wasm`, so neither needs a Node `fs` branch.
7
+ */
8
+
9
+ const downloads = new Map<string, Promise<Response>>();
10
+ const compiled = new Map<string, Promise<WebAssembly.Module>>();
11
+ const bundles = new Map<string, Promise<ArrayBuffer>>();
12
+
13
+ function download(url: URL): Promise<Response> {
14
+ const key = url.href;
15
+ let pending = downloads.get(key);
16
+ if (pending === undefined) {
17
+ pending = fetch(url).then((response) => {
18
+ if (!response.ok) {
19
+ throw new Error(`Could not load ${key}: HTTP ${response.status} ${response.statusText}`);
20
+ }
21
+ return response;
22
+ });
23
+ downloads.set(key, pending);
24
+ // A failed download is retried on the next boot rather than cached.
25
+ pending.catch(() => downloads.delete(key));
26
+ }
27
+ return pending;
28
+ }
29
+
30
+ /** Start downloading an artefact now, so it is on its way when the boot needs it. */
31
+ export function prefetch(url: URL): void {
32
+ download(url).catch(() => undefined);
33
+ }
34
+
35
+ /** The compiled module at `url`, compiled once per URL. */
36
+ export function compileModule(url: URL): Promise<WebAssembly.Module> {
37
+ const key = url.href;
38
+ let pending = compiled.get(key);
39
+ if (pending === undefined) {
40
+ pending = download(url).then(async (response) => {
41
+ try {
42
+ // Bun's Response and the WebAssembly typings' Response are distinct declarations of one type.
43
+ return await WebAssembly.compileStreaming(
44
+ response.clone() as unknown as Parameters<typeof WebAssembly.compileStreaming>[0],
45
+ );
46
+ } catch (error) {
47
+ // A server that sends the wrong MIME type defeats streaming compilation; compile the bytes.
48
+ if (error instanceof TypeError) return await WebAssembly.compile(await response.clone().arrayBuffer());
49
+ throw error;
50
+ }
51
+ });
52
+ compiled.set(key, pending);
53
+ pending.catch(() => compiled.delete(key));
54
+ }
55
+ return pending;
56
+ }
57
+
58
+ /** The filesystem bundle's bytes, fetched once per URL; every caller gets its own copy. */
59
+ export async function loadBundle(url: URL): Promise<ArrayBuffer> {
60
+ const key = url.href;
61
+ let pending = bundles.get(key);
62
+ if (pending === undefined) {
63
+ pending = download(url).then((response) => response.clone().arrayBuffer());
64
+ bundles.set(key, pending);
65
+ pending.catch(() => bundles.delete(key));
66
+ }
67
+ // A module may keep views into the buffer it was given and write through them, so no two modules
68
+ // share one.
69
+ return (await pending).slice(0);
70
+ }
71
+
72
+ /** A Blob or its promise, as bytes. */
73
+ export async function bytesOf(source: Blob | Promise<Blob>): Promise<ArrayBuffer> {
74
+ return await (await source).arrayBuffer();
75
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The words of a command line initdb hands to `system()` / `popen()`, up to the first shell operator.
3
+ *
4
+ * initdb runs its backend through a shell command (`"/pgwasm/bin/postgres" --boot -X 1048576 …`, or
5
+ * `… template1 >"/dev/null"`); the host runs that backend itself, so it needs the argument words, not a
6
+ * shell. Quoting is honoured (`'…'`, `"…"` with `\` escaping `"`, `\`, `$` and backtick, and a bare
7
+ * `\`); the first redirection or control operator (`< > | & ; ( )`) ends the words, as a shell would
8
+ * end the command there.
9
+ */
10
+ export function commandWords(command: string): string[] {
11
+ const words: string[] = [];
12
+ let current = "";
13
+ let inWord = false;
14
+ let index = 0;
15
+ const end = command.length;
16
+ const finishWord = () => {
17
+ if (inWord) words.push(current);
18
+ current = "";
19
+ inWord = false;
20
+ };
21
+
22
+ while (index < end) {
23
+ const char = command[index] ?? "";
24
+ if (char === "'") {
25
+ const close = command.indexOf("'", index + 1);
26
+ if (close === -1) throw new SyntaxError(`unterminated ' in command line: ${command}`);
27
+ current += command.slice(index + 1, close);
28
+ inWord = true;
29
+ index = close + 1;
30
+ } else if (char === '"') {
31
+ inWord = true;
32
+ index++;
33
+ while (index < end && command[index] !== '"') {
34
+ const inner = command[index] ?? "";
35
+ const next = command[index + 1];
36
+ if (inner === "\\" && next !== undefined && '"\\$`'.includes(next)) {
37
+ current += next;
38
+ index += 2;
39
+ } else {
40
+ current += inner;
41
+ index++;
42
+ }
43
+ }
44
+ if (index >= end) throw new SyntaxError(`unterminated " in command line: ${command}`);
45
+ index++;
46
+ } else if (char === "\\") {
47
+ const next = command[index + 1];
48
+ if (next !== undefined) current += next;
49
+ inWord = true;
50
+ index += 2;
51
+ } else if (/\s/.test(char)) {
52
+ finishWord();
53
+ index++;
54
+ } else if ("<>|&;()".includes(char)) {
55
+ break;
56
+ } else {
57
+ current += char;
58
+ inWord = true;
59
+ index++;
60
+ }
61
+ }
62
+ finishWord();
63
+ return words;
64
+ }
@@ -0,0 +1,70 @@
1
+ // Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
2
+ // — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
3
+
4
+ import type { DataDirEntry } from "@pgxsinkit/pgwasm/build";
5
+
6
+ import type { EmscriptenFS } from "./emscripten";
7
+ import { PGDATA } from "./paths";
8
+
9
+ function mtimeSeconds(mtime: Date | number): number {
10
+ return Math.floor((typeof mtime === "number" ? mtime : mtime.getTime()) / 1000);
11
+ }
12
+
13
+ /** Every entry under the data directory, a directory before its contents. */
14
+ export function readDataDirEntries(FS: EmscriptenFS, root = PGDATA): DataDirEntry[] {
15
+ const entries: DataDirEntry[] = [];
16
+ const walk = (directory: string) => {
17
+ for (const name of FS.readdir(directory)) {
18
+ if (name === "." || name === "..") continue;
19
+ const fullPath = `${directory}/${name}`;
20
+ const stats = FS.stat(fullPath);
21
+ const isFile = FS.isFile(stats.mode);
22
+ entries.push({
23
+ path: fullPath.slice(root.length),
24
+ type: isFile ? "file" : "directory",
25
+ mode: stats.mode & 0o7777,
26
+ mtimeSeconds: mtimeSeconds(stats.mtime),
27
+ data: isFile ? FS.readFile(fullPath, { encoding: "binary" }) : new Uint8Array(0),
28
+ });
29
+ if (FS.isDir(stats.mode)) walk(fullPath);
30
+ }
31
+ };
32
+ walk(root);
33
+ return entries;
34
+ }
35
+
36
+ function ensureDirectory(FS: EmscriptenFS, path: string): void {
37
+ if (!FS.analyzePath(path).exists) FS.mkdirTree(path);
38
+ }
39
+
40
+ /** Write entries into the data directory, creating it and any missing parents. */
41
+ export function writeDataDirEntries(FS: EmscriptenFS, entries: readonly DataDirEntry[], root = PGDATA): void {
42
+ ensureDirectory(FS, root);
43
+ for (const entry of entries) {
44
+ const path = `${root}${entry.path}`;
45
+ if (entry.type === "directory") {
46
+ ensureDirectory(FS, path);
47
+ continue;
48
+ }
49
+ ensureDirectory(FS, path.slice(0, path.lastIndexOf("/")));
50
+ FS.writeFile(path, entry.data);
51
+ const mtimeMs = entry.mtimeSeconds * 1000;
52
+ FS.utime(path, mtimeMs, mtimeMs);
53
+ }
54
+ }
55
+
56
+ /** Write one file, creating its directory. */
57
+ export function writeDataDirFile(FS: EmscriptenFS, path: string, data: Uint8Array, root = PGDATA): void {
58
+ const target = `${root}${path}`;
59
+ ensureDirectory(FS, target.slice(0, target.lastIndexOf("/")));
60
+ FS.writeFile(target, data);
61
+ }
62
+
63
+ /** A file in the data directory, or `undefined` when it does not exist. */
64
+ export function readDataDirFile(FS: EmscriptenFS, path: string, root = PGDATA): Uint8Array | undefined {
65
+ const target = `${root}${path}`;
66
+ if (!FS.analyzePath(target).exists) return undefined;
67
+ const stats = FS.stat(target);
68
+ if (!FS.isFile(stats.mode)) return undefined;
69
+ return FS.readFile(target, { encoding: "binary" });
70
+ }