@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
package/src/errors.ts ADDED
@@ -0,0 +1,201 @@
1
+ // Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
2
+ // — see NOTICE): `makeQueryError` began as its `makePGliteError`. Owned outright (ADR-0062);
3
+ // compatibility with PGlite is an anti-goal — evolve freely.
4
+
5
+ import type { BuildIdentity, FilesystemKind } from "./build/seam";
6
+ import type { QueryOptions } from "./interface";
7
+ import type { DatabaseError } from "./protocol/wire/messages";
8
+
9
+ /** The base of every error pgwasm itself raises (SQL errors are {@link DatabaseError}). */
10
+ export class PgwasmError extends Error {
11
+ override name = "PgwasmError";
12
+ }
13
+
14
+ /** A `dataDir` pgwasm does not accept: an unknown scheme, a bare path, or `dataDir` with `fs`. */
15
+ export class UnsupportedDataDirError extends PgwasmError {
16
+ override name = "UnsupportedDataDirError";
17
+ readonly dataDir: string;
18
+
19
+ constructor(dataDir: string, reason: string) {
20
+ super(`Unsupported dataDir "${dataDir}": ${reason}`);
21
+ this.dataDir = dataDir;
22
+ }
23
+ }
24
+
25
+ /** An `opfs-ahp://` dataDir: that filesystem is gone (ADR-0062 decision 6). */
26
+ export class OpfsAhpRemovedError extends UnsupportedDataDirError {
27
+ override name = "OpfsAhpRemovedError";
28
+ /** Where the OPFS store lives now. */
29
+ readonly replacement = "@pgxsinkit/pgwasm/opfs";
30
+
31
+ constructor(dataDir: string) {
32
+ super(
33
+ dataDir,
34
+ "the opfs-ahp filesystem has been removed; the OPFS store is @pgxsinkit/pgwasm/opfs, passed in " +
35
+ "explicitly as the `fs` option",
36
+ );
37
+ }
38
+ }
39
+
40
+ /** The build does not mount the requested kind of storage. */
41
+ export class UnsupportedFilesystemError extends PgwasmError {
42
+ override name = "UnsupportedFilesystemError";
43
+ readonly kind: FilesystemKind;
44
+ readonly build: string;
45
+
46
+ constructor(kind: FilesystemKind, build: BuildIdentity, supported: readonly FilesystemKind[]) {
47
+ super(
48
+ `The "${build.name}" Postgres build does not support ${kind} storage (it supports: ${supported.join(", ")}).`,
49
+ );
50
+ this.kind = kind;
51
+ this.build = build.name;
52
+ }
53
+ }
54
+
55
+ /** The build needs a cross-origin-isolated context, and this one is not. */
56
+ export class CrossOriginIsolationRequiredError extends PgwasmError {
57
+ override name = "CrossOriginIsolationRequiredError";
58
+
59
+ constructor(build: BuildIdentity) {
60
+ super(
61
+ `The "${build.name}" Postgres build needs a cross-origin-isolated context (SharedArrayBuffer); serve the ` +
62
+ "page with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp.",
63
+ );
64
+ }
65
+ }
66
+
67
+ /** A server extension compiled for another build. */
68
+ export class ExtensionBuildMismatchError extends PgwasmError {
69
+ override name = "ExtensionBuildMismatchError";
70
+
71
+ constructor(extension: string, extensionBuild: string, build: BuildIdentity) {
72
+ super(
73
+ `The "${extension}" extension was compiled for the "${extensionBuild}" Postgres build and cannot load into ` +
74
+ `the "${build.name}" build.`,
75
+ );
76
+ }
77
+ }
78
+
79
+ /** The build a data directory (or a Store backup) records. `"unmarked"` predates build markers. */
80
+ export type RecordedBuild = { readonly build: string; readonly dataFormat: number } | "unmarked";
81
+
82
+ function describeRecorded(recorded: RecordedBuild): string {
83
+ return recorded === "unmarked"
84
+ ? "an unmarked data directory (created before builds were recorded, by the C build)"
85
+ : `the "${recorded.build}" Postgres build (data format ${recorded.dataFormat})`;
86
+ }
87
+
88
+ /**
89
+ * A data directory or Store backup made by another Postgres build. A store's build is fixed when it is
90
+ * created (ADR-0063 build permanence); nothing was written.
91
+ */
92
+ export class BuildMismatchError extends PgwasmError {
93
+ override name = "BuildMismatchError";
94
+ readonly expected: { readonly build: string; readonly dataFormat: number };
95
+ readonly found: RecordedBuild;
96
+ readonly source: "data-directory" | "backup";
97
+
98
+ constructor(build: BuildIdentity, found: RecordedBuild, source: "data-directory" | "backup") {
99
+ const what = source === "backup" ? "This Store backup" : "This data directory";
100
+ super(
101
+ `${what} was created by ${describeRecorded(found)} and cannot be opened with the "${build.name}" build. A ` +
102
+ "store's Postgres build is fixed when it is created: open it with that build, or destroy the store and " +
103
+ "re-sync it.",
104
+ );
105
+ this.expected = { build: build.name, dataFormat: build.dataFormat };
106
+ this.found = found;
107
+ this.source = source;
108
+ }
109
+ }
110
+
111
+ /** A data directory or backup of the same build in a data format this release does not read. */
112
+ export class DataFormatMismatchError extends PgwasmError {
113
+ override name = "DataFormatMismatchError";
114
+ readonly expected: number;
115
+ readonly found: number;
116
+ readonly source: "data-directory" | "backup";
117
+
118
+ constructor(build: BuildIdentity, found: number, source: "data-directory" | "backup") {
119
+ super(
120
+ `This ${source === "backup" ? "Store backup" : "data directory"} is in data format ${found} of the ` +
121
+ `"${build.name}" Postgres build; this release of the build reads format ${build.dataFormat}.`,
122
+ );
123
+ this.expected = build.dataFormat;
124
+ this.found = found;
125
+ this.source = source;
126
+ }
127
+ }
128
+
129
+ /** A build marker that cannot be read: corrupt, or written by a newer pgwasm. Nothing was written. */
130
+ export class BuildMarkerUnreadableError extends PgwasmError {
131
+ override name = "BuildMarkerUnreadableError";
132
+ readonly raw: string;
133
+
134
+ constructor(raw: string, reason: string) {
135
+ super(`The data directory's build marker cannot be read (${reason}): ${JSON.stringify(raw)}`);
136
+ this.raw = raw;
137
+ }
138
+ }
139
+
140
+ /** `loadDataDir` was given for a data directory that already holds a database. */
141
+ export class DataDirExistsError extends PgwasmError {
142
+ override name = "DataDirExistsError";
143
+
144
+ constructor() {
145
+ super("The data directory already holds a database; a Store backup restores only into an empty one.");
146
+ }
147
+ }
148
+
149
+ /** A Store backup that cannot be restored: not a tarball, or a member outside the data directory. */
150
+ export class BackupFormatError extends PgwasmError {
151
+ override name = "BackupFormatError";
152
+ }
153
+
154
+ /** The storage is held by another open database (an IndexedDB store open in another context). */
155
+ export class StorageInUseError extends PgwasmError {
156
+ override name = "StorageInUseError";
157
+
158
+ constructor(message: string) {
159
+ super(message);
160
+ }
161
+ }
162
+
163
+ /** The database is closing or closed. */
164
+ export class PgwasmClosedError extends PgwasmError {
165
+ override name = "PgwasmClosedError";
166
+
167
+ constructor(state: "closing" | "closed") {
168
+ super(`pgwasm is ${state}`);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * The Postgres build failed underneath a statement (an exception that is not an SQL error: a storage
174
+ * failure thrown into the engine, a PANIC's abort). The instance is failed: every later statement
175
+ * throws this same error, and `close()` releases resources and rejects with it.
176
+ */
177
+ export class PgwasmFailedError extends PgwasmError {
178
+ override name = "PgwasmFailedError";
179
+ }
180
+
181
+ /** A feature the build does not have (see its capabilities). */
182
+ export class UnsupportedFeatureError extends PgwasmError {
183
+ override name = "UnsupportedFeatureError";
184
+ }
185
+
186
+ /** An SQL error from a query, with the query that raised it. */
187
+ export interface QueryError extends DatabaseError {
188
+ query: string | undefined;
189
+ params: readonly unknown[] | undefined;
190
+ queryOptions: QueryOptions | undefined;
191
+ }
192
+
193
+ /** Attach the query to the SQL error it raised. */
194
+ export function makeQueryError(data: {
195
+ error: DatabaseError;
196
+ query: string;
197
+ params: readonly unknown[] | undefined;
198
+ options: QueryOptions | undefined;
199
+ }): QueryError {
200
+ return Object.assign(data.error, { query: data.query, params: data.params, queryOptions: data.options });
201
+ }
@@ -0,0 +1,149 @@
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
+ /** Stat results, in the shape a POSIX `stat` returns them. Times are milliseconds since the epoch. */
5
+ export interface FsStats {
6
+ dev: number;
7
+ ino: number;
8
+ mode: number;
9
+ nlink: number;
10
+ uid: number;
11
+ gid: number;
12
+ rdev: number;
13
+ size: number;
14
+ blksize: number;
15
+ blocks: number;
16
+ atime: number;
17
+ mtime: number;
18
+ ctime: number;
19
+ }
20
+
21
+ /**
22
+ * Errno values, in the numbering Postgres builds use (Emscripten's). A filesystem reports a failed
23
+ * operation by throwing an error whose `code` is one of these; an error without a `code` is reported to
24
+ * Postgres as `EIO`.
25
+ */
26
+ export const ERRNO_CODES = {
27
+ EBADF: 8,
28
+ EBADFD: 127,
29
+ EEXIST: 20,
30
+ EINVAL: 28,
31
+ EIO: 29,
32
+ EISDIR: 31,
33
+ ENODEV: 43,
34
+ ENOENT: 44,
35
+ ENOTDIR: 54,
36
+ ENOTEMPTY: 55,
37
+ } as const;
38
+
39
+ /**
40
+ * A filesystem call that failed and was reported to Postgres as an errno. Kept in a small ring so
41
+ * that when Postgres later fails, the storage failures underneath it are visible.
42
+ */
43
+ export interface SyscallError {
44
+ readonly op: string;
45
+ readonly path: string;
46
+ readonly errno: number;
47
+ readonly message: string;
48
+ readonly timeMs: number;
49
+ }
50
+
51
+ const MAX_SYSCALL_ERRORS = 50;
52
+
53
+ /**
54
+ * What a filesystem says about itself, reported in `pg.storage` as `{ kind: "vfs", ...description }`:
55
+ * a short name for diagnostics, and whether what it holds survives the process (or the page) that wrote it.
56
+ */
57
+ export interface FilesystemDescription {
58
+ /** A short name for diagnostics, e.g. `opfs-repacked`. */
59
+ readonly name: string;
60
+ /**
61
+ * Whether the data directory outlives the process (or page) that wrote it. Absent when the filesystem
62
+ * doesn't say: nothing outside it can tell, so callers treat an undeclared filesystem as the author's
63
+ * own call rather than as non-persistent.
64
+ */
65
+ readonly persistent?: boolean;
66
+ }
67
+
68
+ const DEFAULT_DESCRIPTION: FilesystemDescription = Object.freeze({ name: "custom" });
69
+
70
+ /**
71
+ * A synchronous virtual filesystem that holds a data directory, mounted by a Postgres build in place
72
+ * of its built-in storage (pass it as `createPgwasm({ fs })`). Paths are absolute within the
73
+ * filesystem, `/`-separated, `/` being the data directory itself.
74
+ *
75
+ * Besides the POSIX-shaped operations, a filesystem takes part in durability: pgwasm calls
76
+ * `syncToFs(relaxed)` after statements (see `createPgwasm`'s `relaxedDurability`), the build calls
77
+ * `initialSyncFs()` once when it mounts the filesystem, `closeFs()` when the database closes and
78
+ * `cleanupFailedInit()` when a boot fails after the filesystem was handed over.
79
+ */
80
+ export abstract class BaseFilesystem {
81
+ readonly debug: boolean;
82
+ readonly #recentSyscallErrors: SyscallError[] = [];
83
+
84
+ constructor({ debug = false }: { debug?: boolean } = {}) {
85
+ this.debug = debug;
86
+ }
87
+
88
+ /**
89
+ * What this filesystem is, as `pg.storage` reports it. Defaults to `{ name: "custom" }`, persistence
90
+ * undeclared: a filesystem overrides it to name itself and to say whether its data outlives the process
91
+ * (`persistent: true`) or not (`persistent: false`), since nothing else can tell.
92
+ */
93
+ get description(): FilesystemDescription {
94
+ return DEFAULT_DESCRIPTION;
95
+ }
96
+
97
+ /** The most recent failed filesystem calls reported to Postgres (up to 50), oldest first. */
98
+ get recentSyscallErrors(): readonly SyscallError[] {
99
+ return this.#recentSyscallErrors;
100
+ }
101
+
102
+ /** Record a failed call. The build's mount calls this where it turns a thrown error into an errno. */
103
+ recordSyscallError(op: string, path: string, errno: number, message: string): void {
104
+ const buffer = this.#recentSyscallErrors;
105
+ buffer.push({ op, path, errno, message, timeMs: Date.now() });
106
+ if (buffer.length > MAX_SYSCALL_ERRORS) {
107
+ buffer.shift();
108
+ }
109
+ if (this.debug) {
110
+ console.warn("[pgwasm-fs] syscall error", op, path, errno, message);
111
+ }
112
+ }
113
+
114
+ /** Make everything written so far durable. `relaxed` is pgwasm's background persist. */
115
+ async syncToFs(_relaxed?: boolean): Promise<void> {}
116
+
117
+ /** Called once when the build mounts the filesystem, before anything reads it. */
118
+ async initialSyncFs(): Promise<void> {}
119
+
120
+ /** Release everything the filesystem holds. Called when the database closes. */
121
+ async closeFs(): Promise<void> {}
122
+
123
+ /** Release what the filesystem holds after a boot failed. Defaults to {@link closeFs}. */
124
+ async cleanupFailedInit(): Promise<void> {
125
+ await this.closeFs();
126
+ }
127
+
128
+ abstract chmod(path: string, mode: number): void;
129
+ abstract close(fd: number): void;
130
+ abstract fstat(fd: number): FsStats;
131
+ abstract lstat(path: string): FsStats;
132
+ abstract mkdir(path: string, options?: { recursive?: boolean; mode?: number }): void;
133
+ abstract open(path: string, flags?: string, mode?: number): number;
134
+ abstract readdir(path: string): string[];
135
+ /** Read into `buffer[offset, offset + length)` from `position`; returns the bytes read. */
136
+ abstract read(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): number;
137
+ abstract rename(oldPath: string, newPath: string): void;
138
+ abstract rmdir(path: string): void;
139
+ abstract truncate(path: string, length: number): void;
140
+ abstract unlink(path: string): void;
141
+ abstract utimes(path: string, atime: number, mtime: number): void;
142
+ abstract writeFile(
143
+ path: string,
144
+ data: string | Uint8Array,
145
+ options?: { encoding?: string; mode?: number; flag?: string },
146
+ ): void;
147
+ /** Write `buffer[offset, offset + length)` at `position`; returns the bytes written. */
148
+ abstract write(fd: number, buffer: Uint8Array, offset: number, length: number, position: number): number;
149
+ }
@@ -0,0 +1,7 @@
1
+ export {
2
+ BaseFilesystem,
3
+ ERRNO_CODES,
4
+ type FilesystemDescription,
5
+ type FsStats,
6
+ type SyscallError,
7
+ } from "./base-filesystem";
package/src/index.ts ADDED
@@ -0,0 +1,44 @@
1
+ export { createPgwasm } from "./create";
2
+ export type {
3
+ DebugLevel,
4
+ DumpCompression,
5
+ Extension,
6
+ ExtensionNamespaces,
7
+ ExtensionSetupResult,
8
+ Extensions,
9
+ FilesystemKind,
10
+ ParserOptions,
11
+ Pgwasm,
12
+ PgwasmOptions,
13
+ PgwasmWithExtensions,
14
+ QueryOptions,
15
+ Results,
16
+ Row,
17
+ RowMode,
18
+ SerializerOptions,
19
+ StorageDescription,
20
+ Transaction,
21
+ } from "./interface";
22
+ export type { BuildIdentity, PostgresBuild, ServerExtension } from "./build/seam";
23
+ export {
24
+ BackupFormatError,
25
+ BuildMarkerUnreadableError,
26
+ BuildMismatchError,
27
+ CrossOriginIsolationRequiredError,
28
+ DataDirExistsError,
29
+ DataFormatMismatchError,
30
+ ExtensionBuildMismatchError,
31
+ OpfsAhpRemovedError,
32
+ PgwasmClosedError,
33
+ PgwasmError,
34
+ PgwasmFailedError,
35
+ StorageInUseError,
36
+ UnsupportedDataDirError,
37
+ UnsupportedFeatureError,
38
+ UnsupportedFilesystemError,
39
+ type QueryError,
40
+ type RecordedBuild,
41
+ } from "./errors";
42
+ export { DatabaseError } from "./protocol/wire/messages";
43
+ export { identifier, raw } from "./templating";
44
+ export * as types from "./types";
@@ -0,0 +1,186 @@
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 { BuildIdentity, DebugLevel, FilesystemKind, PostgresBuild, ServerExtension } from "./build/seam";
5
+ import type { BaseFilesystem } from "./fs/base-filesystem";
6
+ import type { NoticeMessage } from "./protocol/wire/messages";
7
+
8
+ export type { DebugLevel } from "./build/seam";
9
+
10
+ /** `object` rows keyed by column name, or `array` rows in column order. */
11
+ export type RowMode = "array" | "object";
12
+
13
+ /** A result row when no row type is given. */
14
+ export type Row = Record<string, unknown>;
15
+
16
+ /** Per-query parsers, by type OID. */
17
+ export interface ParserOptions {
18
+ [pgType: number]: (value: string, typeId?: number) => unknown;
19
+ }
20
+
21
+ /** Per-query serializers, by type OID. */
22
+ export interface SerializerOptions {
23
+ [pgType: number]: (value: unknown) => string;
24
+ }
25
+
26
+ export interface QueryOptions {
27
+ readonly rowMode?: RowMode;
28
+ readonly parsers?: ParserOptions;
29
+ readonly serializers?: SerializerOptions;
30
+ /** What `COPY … FROM '/dev/blob'` reads during this query. */
31
+ readonly blob?: Blob | File;
32
+ readonly onNotice?: (notice: NoticeMessage) => void;
33
+ /** Parameter type OIDs to declare, in order, instead of letting Postgres infer them. */
34
+ readonly paramTypes?: readonly number[];
35
+ }
36
+
37
+ /** The result of one statement. */
38
+ export interface Results<T = Row> {
39
+ rows: T[];
40
+ /** Rows changed so far by INSERT/UPDATE/DELETE/COPY/MERGE, cumulative across a multi-statement exec. */
41
+ affectedRows?: number;
42
+ /** The statement's command, e.g. "SELECT", "INSERT", "CREATE". */
43
+ command?: string;
44
+ /** The row count in the command tag (rows returned or changed by this statement). */
45
+ rowCount?: number;
46
+ fields: { name: string; dataTypeID: number }[];
47
+ /** What `COPY … TO '/dev/blob'` wrote, when it wrote anything. */
48
+ blob?: Blob;
49
+ }
50
+
51
+ /** The handle a `transaction` callback receives. It stops working when the transaction ends. */
52
+ export interface Transaction {
53
+ query<T = Row>(sql: string, params?: readonly unknown[], options?: QueryOptions): Promise<Results<T>>;
54
+ sql<T = Row>(sqlStrings: TemplateStringsArray, ...params: unknown[]): Promise<Results<T>>;
55
+ exec(sql: string, options?: QueryOptions): Promise<Results[]>;
56
+ rollback(): Promise<void>;
57
+ listen(channel: string, callback: (payload: string) => void): Promise<(tx?: Transaction) => Promise<void>>;
58
+ readonly closed: boolean;
59
+ }
60
+
61
+ /** Where a data directory lives, as reported by {@link Pgwasm.storage}. */
62
+ export type StorageDescription =
63
+ | { readonly kind: "memory" }
64
+ | { readonly kind: "idb"; readonly name: string }
65
+ | { readonly kind: "file"; readonly path: string }
66
+ /**
67
+ * A filesystem passed as `createPgwasm({ fs })`, as its `description` reports it. `persistent` is absent
68
+ * when the filesystem doesn't declare it.
69
+ */
70
+ | { readonly kind: "vfs"; readonly name: string; readonly persistent?: boolean };
71
+
72
+ /** How {@link Pgwasm.dumpDataDir} compresses: `auto` and `gzip` gzip the tarball, `none` does not. */
73
+ export type DumpCompression = "none" | "gzip" | "auto";
74
+
75
+ /** What a client extension's `setup` returns. */
76
+ export interface ExtensionSetupResult<TNamespace = unknown> {
77
+ /** Attached to the instance under the extension's key in `extensions`. */
78
+ readonly namespace?: TNamespace;
79
+ /** Run once the database is ready. */
80
+ readonly init?: () => Promise<void>;
81
+ /** Run when the database closes. */
82
+ readonly close?: () => Promise<void>;
83
+ }
84
+
85
+ /** A client extension: code that runs beside the database, such as `live`. */
86
+ export interface Extension<TNamespace = unknown> {
87
+ readonly name: string;
88
+ setup(pg: Pgwasm): Promise<ExtensionSetupResult<TNamespace>>;
89
+ }
90
+
91
+ /** The `extensions` option: client extensions and a build's server extensions, by key. */
92
+ export type Extensions = Readonly<Record<string, Extension | ServerExtension>>;
93
+
94
+ /**
95
+ * The namespaces client extensions attach, by their key in `extensions`. An extension that attaches
96
+ * none (its namespace type is `undefined` or `unknown`) adds no key: the database has no such member.
97
+ */
98
+ export type ExtensionNamespaces<E extends Extensions> = {
99
+ readonly [
100
+ K in keyof E as E[K] extends Extension<infer N>
101
+ ? unknown extends N
102
+ ? never
103
+ : [N] extends [undefined]
104
+ ? never
105
+ : K
106
+ : never
107
+ ]: E[K] extends Extension<infer N> ? N : never;
108
+ };
109
+
110
+ export interface PgwasmOptions<E extends Extensions = Extensions> {
111
+ /** The Postgres build to run, e.g. `cBuild` from `@pgxsinkit/pgwasm-c`. */
112
+ readonly build: PostgresBuild;
113
+ /**
114
+ * Where the data directory lives: `memory://` (the default), `idb://<name>` (IndexedDB) or
115
+ * `file://<path>` (a directory, on Bun). A scheme is required. Exclusive with `fs`.
116
+ */
117
+ readonly dataDir?: string;
118
+ /** A filesystem to mount as the data directory instead of `dataDir`. */
119
+ readonly fs?: BaseFilesystem;
120
+ /** A Store backup (`dumpDataDir()` output) to create the data directory from. */
121
+ readonly loadDataDir?: Blob | File;
122
+ /**
123
+ * Client extensions (such as `live`) and the build's server extensions, by key. Typed as the
124
+ * inferred `E` intersected with {@link Extensions}: `E` carries each extension's namespace onto the
125
+ * database, and the intersection gives an extension written inline its `setup(pg: Pgwasm)` type.
126
+ */
127
+ readonly extensions?: E & Extensions;
128
+ /**
129
+ * Return from a statement before its storage persist completes. The persist runs in the
130
+ * background, and a failure is reported by the next statement.
131
+ */
132
+ readonly relaxedDurability?: boolean;
133
+ /** Run as this role (`SET ROLE`) once started. */
134
+ readonly username?: string;
135
+ /** The database to connect to. Defaults to `postgres`. */
136
+ readonly database?: string;
137
+ /** Server settings (GUCs), e.g. `{ application_name: "app" }`. */
138
+ readonly settings?: Readonly<Record<string, string>>;
139
+ readonly parsers?: ParserOptions;
140
+ readonly serializers?: SerializerOptions;
141
+ readonly debug?: DebugLevel;
142
+ }
143
+
144
+ /** A running database. */
145
+ export interface Pgwasm extends AsyncDisposable {
146
+ /** Settled once the database is ready; `createPgwasm` resolves only then. */
147
+ readonly waitReady: Promise<void>;
148
+ readonly ready: boolean;
149
+ readonly closed: boolean;
150
+ readonly debug: DebugLevel;
151
+ /** The build this database runs on. */
152
+ readonly build: BuildIdentity;
153
+ /** Where the data directory lives. */
154
+ readonly storage: StorageDescription;
155
+
156
+ /** One statement, through the extended protocol, with parameters. */
157
+ query<T = Row>(sql: string, params?: readonly unknown[], options?: QueryOptions): Promise<Results<T>>;
158
+ /** One statement from a template; interpolated values become parameters. */
159
+ sql<T = Row>(sqlStrings: TemplateStringsArray, ...params: unknown[]): Promise<Results<T>>;
160
+ /** Any number of statements, through the simple protocol, without parameters. */
161
+ exec(sql: string, options?: QueryOptions): Promise<Results[]>;
162
+ /** Run `callback` in a transaction: COMMIT when it resolves, ROLLBACK when it throws. */
163
+ transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;
164
+ /** Run `fn` while no query or transaction runs. */
165
+ runExclusive<T>(fn: () => Promise<T>): Promise<T>;
166
+ /** LISTEN on a channel; resolves to the matching unlisten. */
167
+ listen(
168
+ channel: string,
169
+ callback: (payload: string) => void,
170
+ tx?: Transaction,
171
+ ): Promise<(tx?: Transaction) => Promise<void>>;
172
+ /** UNLISTEN one callback, or every callback when none is given. */
173
+ unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>;
174
+ /** Every notification on every channel; returns the unsubscribe. */
175
+ onNotification(callback: (channel: string, payload: string) => void): () => void;
176
+ /** Re-read the array types, after creating a type whose arrays should parse. */
177
+ refreshArrayTypes(): Promise<void>;
178
+ /** A Store backup: the data directory as a tarball, restorable through `loadDataDir`. */
179
+ dumpDataDir(compression?: DumpCompression): Promise<File>;
180
+ close(): Promise<void>;
181
+ }
182
+
183
+ /** A database with its client extensions' namespaces attached. */
184
+ export type PgwasmWithExtensions<E extends Extensions> = Pgwasm & ExtensionNamespaces<E>;
185
+
186
+ export type { FilesystemKind };
@@ -0,0 +1,45 @@
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
+ * Run at most one call at a time, and collapse waiting calls into the latest: a call made while one
6
+ * runs is scheduled after it, replacing (and resolving to `undefined`) any call already scheduled.
7
+ */
8
+ export function debounceMutex<A extends unknown[], R>(
9
+ fn: (...args: A) => Promise<R>,
10
+ ): (...args: A) => Promise<R | undefined> {
11
+ let next:
12
+ | {
13
+ args: A;
14
+ resolve: (value: R | undefined) => void;
15
+ reject: (reason?: unknown) => void;
16
+ }
17
+ | undefined;
18
+ let isRunning = false;
19
+
20
+ const processNext = async (): Promise<void> => {
21
+ const current = next;
22
+ if (!current) {
23
+ isRunning = false;
24
+ return;
25
+ }
26
+ isRunning = true;
27
+ next = undefined;
28
+ try {
29
+ current.resolve(await fn(...current.args));
30
+ } catch (error) {
31
+ current.reject(error);
32
+ } finally {
33
+ void processNext();
34
+ }
35
+ };
36
+
37
+ return async (...args: A) => {
38
+ next?.resolve(undefined);
39
+ const promise = new Promise<R | undefined>((resolve, reject) => {
40
+ next = { args, resolve, reject };
41
+ });
42
+ if (!isRunning) void processNext();
43
+ return await promise;
44
+ };
45
+ }
@@ -0,0 +1,47 @@
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 { protocolAccessOf } from "../core/internals";
5
+ import { parseDescribeStatementResults } from "../core/parse";
6
+ import type { Pgwasm, Transaction } from "../interface";
7
+ import type { BackendMessage } from "../protocol/wire/messages";
8
+ import { serialize } from "../protocol/wire/serializer";
9
+ import { TEXT } from "../types";
10
+
11
+ /**
12
+ * Inline a query's parameters as SQL literals (Postgres' own `format(%L)`), for statements that cannot
13
+ * take parameters (a `CREATE VIEW`). The tables the query references must exist, since the parameter
14
+ * types come from describing it. `tx` runs the final `format()` inside a transaction.
15
+ */
16
+ export async function formatQuery(
17
+ pg: Pgwasm,
18
+ query: string,
19
+ params?: readonly unknown[] | null,
20
+ tx?: Transaction | Pgwasm,
21
+ ): Promise<string> {
22
+ if (!params || params.length === 0) {
23
+ return query;
24
+ }
25
+ const wire = protocolAccessOf(pg);
26
+ const messages: BackendMessage[] = [];
27
+ try {
28
+ await wire.execProtocol(serialize.parse({ text: query }), { persist: false });
29
+ messages.push(...(await wire.execProtocol(serialize.describe({ type: "S" }), { persist: false })).messages);
30
+ } finally {
31
+ messages.push(...(await wire.execProtocol(serialize.sync(), { persist: false })).messages);
32
+ }
33
+ const dataTypeIDs = parseDescribeStatementResults(messages);
34
+
35
+ // $1, $2… become %1$L, %2$L…: the `$` makes format() positional; a bare `%1L` would mean "width 1"
36
+ // and consume arguments in order, binding the wrong value to a repeated or reordered placeholder.
37
+ const subbedQuery = query.replace(/\$([0-9]+)/g, (_, num: string) => `%${num}$L`);
38
+ const runner = tx ?? pg;
39
+ const result = await runner.query<{ query: string }>(
40
+ `SELECT format($1, ${params.map((_, i) => `$${i + 2}`).join(", ")}) as query`,
41
+ [subbedQuery, ...params],
42
+ { paramTypes: [TEXT, ...dataTypeIDs] },
43
+ );
44
+ const formatted = result.rows[0]?.query;
45
+ if (formatted === undefined) throw new Error("format() returned no row");
46
+ return formatted;
47
+ }