@gonvex/local-runtime 0.5.2-staging.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # Local Reducer execution
2
+
3
+ The generated Gonvex client executes an interactive Reducer's existing TypeScript
4
+ body in a browser worker. Applications define argument/result schemas and `run`;
5
+ they do not maintain a separate optimistic handler or effects list.
6
+
7
+ The CLI compiles a local SQL schema from tenant migrations and bundles the public
8
+ Reducer exports. Unused Action declarations are removed from that bundle. The
9
+ worker uses PGlite as disposable execution memory, seeded from the SDK Local
10
+ Replica. It does not persist another database or become a second source of server
11
+ state. It captures typed database writes and SQL write CTEs as one transaction.
12
+ Both seed rows and writes are rolled back after execution.
13
+
14
+ The client persists the intent, arguments, command ID, artifact hash and local
15
+ transaction in its existing durable outbox before publishing the predicted rows.
16
+ A successful local call returns the Reducer's result without waiting for a server.
17
+ On reconnect the SDK sends the same intent and idempotency key. The Rust runtime
18
+ executes the Reducer in an authoritative PostgreSQL transaction, checking the
19
+ artifact and current permissions. A retry of an already committed command returns
20
+ its stored result and commit barrier. It does not execute the write twice.
21
+
22
+ A server rejection removes the command's entire prediction and recomputes later
23
+ pending intents against the remaining base. The SDK publishes that replacement
24
+ atomically and emits `onReducerRejection`. Transport failures retain the intent.
25
+ The queue and cached session are partitioned by project, tenant and account.
26
+
27
+ Generated replica subscriptions reuse the declared visibility plans and only
28
+ columns already exposed by application reads. The runtime refuses to interpret
29
+ an incomplete collection or an omitted column as an empty/NULL value. A known
30
+ primary-key row can be read from a partial large collection. If required input is
31
+ unavailable, the intent remains queued without a guessed result or transaction.
32
+ First-time authentication and data never downloaded cannot be fabricated offline.
33
+
34
+ Database inserts use the same intent-owned ID allocator in the server module and
35
+ the local module. Explicit IDs remain supported. Action and scheduler calls are
36
+ recorded locally but only the authoritative server commits and executes their
37
+ outbox work. The worker denies ambient network access after loading its WASM.
38
+ Server timestamps, constraints, hidden data and concurrent writes remain
39
+ server-authoritative and reconcile through the change feed.
40
+
41
+ The default host targets browser workers. Other hosts can implement the exported
42
+ `LocalExecutor` interface; this package does not claim a native PGlite host.
43
+ The IndexedDB and Expo SQLite adapters both persist SDK session metadata.
44
+
45
+ ## Verification
46
+
47
+ ```sh
48
+ pnpm --filter @gonvex/local-runtime test
49
+ pnpm --filter @gonvex/client test
50
+ pnpm --filter @gonvex/module-sdk test
51
+ pnpm --filter @gonvex/cli test
52
+ ```
53
+
54
+ Host tests cover atomic writes, SQL CTE capture, incomplete reads, ordered replay,
55
+ stable IDs, validation and scope isolation. Client tests cover durable admission,
56
+ restart, server rejection, dependent edits, concurrent admission, lost responses,
57
+ account switching and argument capture. CLI tests cover generated execution and
58
+ ensure unexposed columns and unused external Actions do not enter local delivery.
@@ -0,0 +1,105 @@
1
+ import type { JsonObject, JsonValue, ReducerContext, ReducerDefinition } from "@gonvex/module-sdk";
2
+ import type { LocalSchema } from "./schema.js";
3
+ export type { LocalSchema, LocalTableSchema, LocalColumn } from "./schema.js";
4
+ /** Schema emitted by code generation, never inferred from possibly empty rows. */
5
+ export type LocalColumnType = "text" | "boolean" | "bigint" | "integer" | "double precision" | "jsonb" | "uuid";
6
+ export type LocalTables = Readonly<Record<string, Readonly<Record<string, LocalColumnType>>>>;
7
+ export type LocalSnapshot = {
8
+ scope: string;
9
+ tables: Record<string, {
10
+ complete: boolean;
11
+ rows: JsonObject[];
12
+ columns?: readonly string[];
13
+ }>;
14
+ };
15
+ export type LocalExecution = {
16
+ scope: string;
17
+ commandId: string;
18
+ intentEntropy?: string;
19
+ now: number;
20
+ artifactHash: string;
21
+ identity: Pick<ReducerContext, "auth" | "tenant" | "member">;
22
+ };
23
+ export type LocalPatch = {
24
+ entity: string;
25
+ rowId: string;
26
+ op: "patch" | "insert";
27
+ fields: JsonObject;
28
+ } | {
29
+ entity: string;
30
+ rowId: string;
31
+ op: "delete";
32
+ };
33
+ export type DeferredWork = {
34
+ id: string;
35
+ kind: "action";
36
+ path: string;
37
+ args: JsonValue;
38
+ } | {
39
+ id: string;
40
+ kind: "schedule";
41
+ path: string;
42
+ args: JsonValue;
43
+ at: number;
44
+ };
45
+ export type LocalTransactionResult = {
46
+ result: JsonValue;
47
+ patches: LocalPatch[];
48
+ deferred: DeferredWork[];
49
+ readTables: string[];
50
+ };
51
+ export type LocalRuntimeOptions = {
52
+ tables?: LocalTables;
53
+ schema?: LocalSchema;
54
+ reducers: Readonly<Record<string, ReducerDefinition<any, any>>>;
55
+ artifactHash: string;
56
+ };
57
+ /** Persist these envelopes in the SDK outbox, never application state. */
58
+ export type LocalIntent = {
59
+ path: string;
60
+ args: JsonValue;
61
+ execution: LocalExecution;
62
+ };
63
+ export type LocalReplay = {
64
+ transactions: {
65
+ commandId: string;
66
+ transaction: LocalTransactionResult;
67
+ }[];
68
+ rejected: {
69
+ commandId: string;
70
+ error: Error;
71
+ }[];
72
+ };
73
+ export declare class IncompleteReplicaError extends Error {
74
+ readonly table: string;
75
+ constructor(table: string);
76
+ }
77
+ /**
78
+ * Executes an existing module reducer against an isolated PostgreSQL workspace.
79
+ * This database is disposable execution memory, never a second durable cache.
80
+ * The caller supplies one immutable Local Replica snapshot. Only a successful
81
+ * execution returns a transaction for the SDK's existing outbox/overlay path.
82
+ */
83
+ export declare class LocalReducerRuntime {
84
+ private readonly options;
85
+ private readonly schema;
86
+ private readonly database;
87
+ private readonly ready;
88
+ private tail;
89
+ private closed;
90
+ constructor(options: LocalRuntimeOptions);
91
+ initializeReady(): Promise<void>;
92
+ execute(path: string, args: JsonValue, snapshot: LocalSnapshot, execution: LocalExecution): Promise<LocalTransactionResult>;
93
+ /**
94
+ * Rebuild pending transactions in intent order after hydration or a changed
95
+ * authoritative base. Failed intent contributes no rows to later execution.
96
+ * The SDK publishes the returned overlays together, after replay completes.
97
+ */
98
+ replay(snapshot: LocalSnapshot, intents: readonly LocalIntent[]): Promise<LocalReplay>;
99
+ close(): Promise<void>;
100
+ private initialize;
101
+ private run;
102
+ private insertRow;
103
+ }
104
+ /** Stable per-intent IDs. The server host must use the identical seed contract. */
105
+ export declare function deterministicId(scope: string, commandId: string, kind: string, ordinal: number): Promise<string>;
package/dist/index.js ADDED
@@ -0,0 +1,382 @@
1
+ import { validateValue } from "./validation.js";
2
+ import { PGlite } from "@electric-sql/pglite";
3
+ import { reducerRowId } from "@gonvex/module-sdk";
4
+ export class IncompleteReplicaError extends Error {
5
+ table;
6
+ constructor(table) {
7
+ super(`Local replica for ${table} is incomplete; this reducer cannot decide from missing rows.`);
8
+ this.table = table;
9
+ this.name = "IncompleteReplicaError";
10
+ }
11
+ }
12
+ const quote = (identifier) => `"${identifier.replaceAll('"', '""')}"`;
13
+ const columnTypes = new Set(["text", "boolean", "bigint", "integer", "double precision", "jsonb", "uuid"]);
14
+ const clone = (value) => structuredClone(value);
15
+ const parseInteger = (value) => {
16
+ const parsed = Number(value);
17
+ if (!Number.isSafeInteger(parsed))
18
+ throw new Error("Local reducer read an integer outside the JSON safe range");
19
+ return parsed;
20
+ };
21
+ const queryOptions = { parsers: { 20: parseInteger } };
22
+ /**
23
+ * Executes an existing module reducer against an isolated PostgreSQL workspace.
24
+ * This database is disposable execution memory, never a second durable cache.
25
+ * The caller supplies one immutable Local Replica snapshot. Only a successful
26
+ * execution returns a transaction for the SDK's existing outbox/overlay path.
27
+ */
28
+ export class LocalReducerRuntime {
29
+ options;
30
+ schema;
31
+ database = new PGlite();
32
+ ready;
33
+ tail = Promise.resolve();
34
+ closed = false;
35
+ constructor(options) {
36
+ this.options = options;
37
+ this.schema = clone(options.schema ?? Object.fromEntries(Object.entries(options.tables ?? {}).map(([table, columns]) => [table, {
38
+ key: "_id", columns: Object.fromEntries(Object.entries(columns).map(([name, type]) => [name, { type, nullable: name !== "_id" }])),
39
+ }])));
40
+ this.ready = this.initialize();
41
+ }
42
+ async initializeReady() { await this.ready; }
43
+ execute(path, args, snapshot, execution) {
44
+ // Capture at admission: the caller may receive a new server transaction or
45
+ // switch tenants while another reducer awaits its database turn.
46
+ const input = clone({ args, snapshot, execution });
47
+ const job = this.tail.then(async () => {
48
+ if (this.closed)
49
+ throw new Error("Local reducer runtime is closed");
50
+ await this.ready;
51
+ return this.run(path, input.args, input.snapshot, input.execution);
52
+ });
53
+ this.tail = job.catch(() => undefined);
54
+ return job;
55
+ }
56
+ /**
57
+ * Rebuild pending transactions in intent order after hydration or a changed
58
+ * authoritative base. Failed intent contributes no rows to later execution.
59
+ * The SDK publishes the returned overlays together, after replay completes.
60
+ */
61
+ async replay(snapshot, intents) {
62
+ const working = clone(snapshot);
63
+ const queue = clone(intents);
64
+ const ids = new Set();
65
+ // These are journal integrity errors, not business rejections. Do not
66
+ // silently drop an intent belonging to another artifact or identity.
67
+ for (const intent of queue) {
68
+ if (intent.execution.scope !== working.scope)
69
+ throw new Error("Local reducer scope mismatch");
70
+ if (intent.execution.artifactHash !== this.options.artifactHash)
71
+ throw new Error("Local reducer artifact mismatch");
72
+ if (ids.has(intent.execution.commandId))
73
+ throw new Error("Duplicate local command id");
74
+ ids.add(intent.execution.commandId);
75
+ }
76
+ const transactions = [];
77
+ const rejected = [];
78
+ for (const intent of queue) {
79
+ let transaction;
80
+ try {
81
+ transaction = await this.execute(intent.path, intent.args, working, intent.execution);
82
+ }
83
+ catch (error) {
84
+ // A missing cache dependency must keep the journal pending. It is not
85
+ // evidence that the server will reject the business operation.
86
+ if (error instanceof IncompleteReplicaError)
87
+ throw error;
88
+ rejected.push({ commandId: intent.execution.commandId, error: error instanceof Error ? error : new Error(String(error)) });
89
+ continue;
90
+ }
91
+ // Invariant failures in the transaction output abort the whole replay;
92
+ // they must never be downgraded to a user/business rejection.
93
+ for (const patch of transaction.patches) {
94
+ const table = working.tables[patch.entity] ??= { complete: false, rows: [] };
95
+ const key = this.schema[patch.entity]?.key ?? "_id";
96
+ const index = table.rows.findIndex((row) => (row[key] ?? row._id) === patch.rowId);
97
+ if (patch.op === "delete") {
98
+ if (index >= 0)
99
+ table.rows.splice(index, 1);
100
+ }
101
+ else if (patch.op === "insert") {
102
+ if (index >= 0)
103
+ throw new Error("Local replay insert refers to an existing row");
104
+ table.rows.push(clone(patch.fields));
105
+ }
106
+ else {
107
+ if (index < 0)
108
+ throw new Error("Local replay patch refers to a missing row");
109
+ table.rows[index] = { ...table.rows[index], ...clone(patch.fields) };
110
+ }
111
+ }
112
+ transactions.push({ commandId: intent.execution.commandId, transaction });
113
+ }
114
+ return { transactions, rejected };
115
+ }
116
+ async close() {
117
+ if (this.closed)
118
+ return;
119
+ this.closed = true;
120
+ await this.tail;
121
+ await this.ready.catch(() => undefined);
122
+ await this.database.close();
123
+ }
124
+ async initialize() {
125
+ for (const [table, definition] of Object.entries(this.schema)) {
126
+ const { columns, key } = definition;
127
+ if (!table || !columns[key])
128
+ throw new Error(`Local table ${table} requires its primary key column`);
129
+ const definitions = Object.entries(columns).map(([column, spec]) => {
130
+ // Types/defaults come only from the generated, build-time schema.
131
+ return `${quote(column)} ${spec.type}${column === key ? " PRIMARY KEY" : ""}${spec.default ? ` DEFAULT ${spec.default}` : ""}`;
132
+ });
133
+ await this.database.exec(`CREATE TABLE ${quote(table)} (${definitions.join(", ")})`);
134
+ }
135
+ }
136
+ async run(path, args, snapshot, execution) {
137
+ if (!execution.scope || execution.scope !== snapshot.scope)
138
+ throw new Error("Local reducer scope mismatch");
139
+ if (!execution.commandId || !Number.isSafeInteger(execution.now))
140
+ throw new Error("Invalid local execution envelope");
141
+ if (execution.artifactHash !== this.options.artifactHash)
142
+ throw new Error("Local reducer artifact mismatch");
143
+ const definition = this.options.reducers[path];
144
+ if (!definition || definition.kind !== "reducer" || definition.internal || !definition.handler) {
145
+ throw new Error(`No public local reducer registered for ${path}`);
146
+ }
147
+ validateValue(definition.options.args, args);
148
+ const patches = [];
149
+ const deferred = [];
150
+ const reads = new Set();
151
+ let ordinal = 0;
152
+ const deferredOrdinals = new Map();
153
+ const nextId = (kind) => deterministicId(execution.scope, execution.commandId, kind, ordinal++);
154
+ const requireTable = (table) => {
155
+ const definition = this.schema[table];
156
+ if (!definition)
157
+ throw new Error(`Unknown local table ${table}`);
158
+ return definition.columns;
159
+ };
160
+ const requireColumns = (table) => {
161
+ const columns = snapshot.tables[table]?.columns;
162
+ if (columns && Object.keys(requireTable(table)).some(column => !columns.includes(column)))
163
+ throw new IncompleteReplicaError(table);
164
+ };
165
+ const requireComplete = (table) => {
166
+ requireTable(table);
167
+ reads.add(table);
168
+ requireColumns(table);
169
+ if (!snapshot.tables[table]?.complete)
170
+ throw new IncompleteReplicaError(table);
171
+ };
172
+ return this.database.transaction(async (tx) => {
173
+ // Both the input rows and reducer writes are rolled back on success. The
174
+ // only published output is the returned transaction, applied by the SDK.
175
+ const seeded = new Set();
176
+ const seed = async (table) => {
177
+ requireTable(table);
178
+ if (seeded.has(table))
179
+ return;
180
+ seeded.add(table);
181
+ for (const row of snapshot.tables[table]?.rows ?? [])
182
+ await this.insertRow(tx, table, row, true);
183
+ };
184
+ const readRow = async (table, id) => {
185
+ requireTable(table);
186
+ reads.add(table);
187
+ requireColumns(table);
188
+ await seed(table);
189
+ const result = await tx.query(`SELECT * FROM ${quote(table)} WHERE ${quote(this.schema[table].key)} = $1`, [id], queryOptions);
190
+ if (!result.rows.length && !snapshot.tables[table]?.complete)
191
+ throw new IncompleteReplicaError(table);
192
+ return result.rows[0];
193
+ };
194
+ const query = async (statement, parameters = []) => {
195
+ // PostgreSQL parses the actual statement and reports every scanned
196
+ // relation, including joins/subqueries. Never infer completeness using
197
+ // a regex that could silently miss a nested relation.
198
+ const explain = await tx.query(`EXPLAIN (FORMAT JSON) ${statement}`, [...parameters], queryOptions);
199
+ const tables = new Set();
200
+ const written = new Set();
201
+ const inspect = (value) => {
202
+ if (Array.isArray(value)) {
203
+ value.forEach(inspect);
204
+ return;
205
+ }
206
+ if (!value || typeof value !== "object")
207
+ return;
208
+ const node = value;
209
+ if (node["Node Type"] === "ModifyTable" && typeof node["Relation Name"] === "string")
210
+ written.add(node["Relation Name"]);
211
+ if (typeof node["Relation Name"] === "string") {
212
+ tables.add(node["Relation Name"]);
213
+ }
214
+ Object.values(node).forEach(inspect);
215
+ };
216
+ inspect(explain.rows);
217
+ for (const table of tables) {
218
+ // Only a proven primary-key lookup can use a partial collection.
219
+ // PostgreSQL still discovers all relations above; joins, counts,
220
+ // subqueries and range reads must have complete input coverage.
221
+ const key = this.schema[table]?.key;
222
+ const exact = /^SELECT (?:\*|"[A-Za-z_][A-Za-z0-9_]*"(?:,\s*"[A-Za-z_][A-Za-z0-9_]*")*) FROM "([A-Za-z_][A-Za-z0-9_]*)" WHERE "([A-Za-z_][A-Za-z0-9_]*)" = \$(\d+)(?: AND "deletedAt" IS NULL)?(?: LIMIT 1)?\s*;?$/i.exec(statement.trim());
223
+ const id = exact ? parameters[Number(exact[3]) - 1] : undefined;
224
+ if (tables.size === 1 && exact?.[1] === table && exact[2] === key && snapshot.tables[table]?.rows.some(row => row[key] === id)) {
225
+ requireColumns(table);
226
+ reads.add(table);
227
+ }
228
+ else
229
+ requireComplete(table);
230
+ await seed(table);
231
+ }
232
+ const before = new Map();
233
+ for (const table of written) {
234
+ const rows = (await tx.query(`SELECT * FROM ${quote(table)}`, [], queryOptions)).rows;
235
+ before.set(table, new Map(rows.map(row => [String(row[this.schema[table].key]), row])));
236
+ }
237
+ const result = await tx.query(statement, [...parameters], queryOptions);
238
+ // Reducer SQL (including data-modifying CTEs) is part of the same
239
+ // transaction. Capture its row delta just like typed database writes.
240
+ for (const table of written) {
241
+ const prior = before.get(table);
242
+ const key = this.schema[table].key;
243
+ for (const row of (await tx.query(`SELECT * FROM ${quote(table)}`, [], queryOptions)).rows) {
244
+ const id = String(row[key]);
245
+ const old = prior.get(id);
246
+ prior.delete(id);
247
+ if (!old)
248
+ patches.push({ entity: table, rowId: id, op: "insert", fields: clone(row) });
249
+ else {
250
+ const fields = Object.fromEntries(Object.entries(row).filter(([column, value]) => JSON.stringify(value) !== JSON.stringify(old[column])));
251
+ if (Object.keys(fields).length)
252
+ patches.push({ entity: table, rowId: id, op: "patch", fields });
253
+ }
254
+ }
255
+ for (const id of prior.keys())
256
+ patches.push({ entity: table, rowId: id, op: "delete" });
257
+ }
258
+ return result.rows;
259
+ };
260
+ const context = {
261
+ intentEntropy: execution.intentEntropy,
262
+ ...clone(execution.identity), now: execution.now,
263
+ invocation: {
264
+ channel: "ui", rootChannel: "ui", commandId: execution.commandId,
265
+ rootCommandId: execution.commandId, artifactHash: execution.artifactHash,
266
+ actorAccountId: execution.identity.auth.account?.id ?? null,
267
+ actorMemberId: execution.identity.member?.id ?? null, onBehalfOfMemberId: null,
268
+ },
269
+ db: {
270
+ query,
271
+ insert: async (table, row, allocation) => {
272
+ const columns = requireTable(table);
273
+ await seed(table);
274
+ const value = clone(row);
275
+ const key = this.schema[table].key;
276
+ if (value[key] == null)
277
+ value[key] = allocation?.generatedId ?? await nextId(`insert:${table}`);
278
+ if (typeof value[key] !== "string" || !value[key])
279
+ throw new Error("Insert requires a non-empty string id");
280
+ if (columns._creationTime && value._creationTime == null)
281
+ value._creationTime = execution.now;
282
+ const inserted = await this.insertRow(tx, table, value);
283
+ patches.push({ entity: table, rowId: value[key], op: "insert", fields: clone(inserted) });
284
+ return clone(inserted);
285
+ },
286
+ update: async (table, id, patch) => {
287
+ const columns = requireTable(table);
288
+ const key = this.schema[table].key;
289
+ if (Object.hasOwn(patch, key))
290
+ throw new Error("Reducer update cannot change a row id");
291
+ const before = await readRow(table, id);
292
+ if (!before)
293
+ throw new Error(`Row ${table}/${id} not found`);
294
+ const keys = Object.keys(patch);
295
+ keys.forEach((key) => { if (!columns[key])
296
+ throw new Error(`Unknown column ${table}.${key}`); });
297
+ for (const name of keys) {
298
+ if (!columns[name].nullable && patch[name] == null)
299
+ throw new Error(`Required field ${table}.${name} is missing`);
300
+ }
301
+ if (!keys.length)
302
+ return clone(before);
303
+ const updated = await tx.query(`UPDATE ${quote(table)} SET ${keys.map((key, index) => `${quote(key)} = $${index + 1}`).join(", ")} WHERE ${quote(key)} = $${keys.length + 1} RETURNING *`, [...keys.map((key) => patch[key]), id], queryOptions);
304
+ patches.push({ entity: table, rowId: id, op: "patch", fields: clone(patch) });
305
+ return clone(updated.rows[0]);
306
+ },
307
+ delete: async (table, id) => {
308
+ const before = await readRow(table, id);
309
+ if (!before)
310
+ return;
311
+ await tx.query(`DELETE FROM ${quote(table)} WHERE ${quote(this.schema[table].key)} = $1`, [id]);
312
+ patches.push({ entity: table, rowId: id, op: "delete" });
313
+ },
314
+ deleteMany: async (table, ids) => {
315
+ let deleted = 0;
316
+ for (const id of new Set(ids)) {
317
+ if (typeof id !== "string")
318
+ throw new Error("Delete requires a string id");
319
+ const before = await readRow(table, id);
320
+ if (before) {
321
+ await context.db.delete(table, id);
322
+ deleted++;
323
+ }
324
+ }
325
+ return { deleted };
326
+ },
327
+ },
328
+ actions: { enqueue: async (path, args) => {
329
+ const ordinal = deferredOrdinals.get("action") ?? 0;
330
+ deferredOrdinals.set("action", ordinal + 1);
331
+ const id = await reducerRowId(context, "deferred:action", ordinal);
332
+ deferred.push({ id, kind: "action", path, args: clone(args) });
333
+ return id;
334
+ } },
335
+ scheduler: {
336
+ runAfter: async (delay, path, args = {}) => context.scheduler.runAt(execution.now + delay, path, args),
337
+ runAt: async (at, path, args = {}) => {
338
+ if (!Number.isSafeInteger(at))
339
+ throw new Error("Invalid schedule time");
340
+ const ordinal = deferredOrdinals.get("schedule") ?? 0;
341
+ deferredOrdinals.set("schedule", ordinal + 1);
342
+ const id = `job_${await reducerRowId(context, "deferred:schedule", ordinal)}`;
343
+ deferred.push({ id, kind: "schedule", path, args: clone(args), at });
344
+ return id;
345
+ },
346
+ },
347
+ };
348
+ const result = clone(await definition.handler(context, args));
349
+ validateValue(definition.options.result, result);
350
+ await tx.rollback();
351
+ return { result, patches, deferred, readTables: [...reads].sort() };
352
+ });
353
+ }
354
+ async insertRow(tx, table, row, seed = false) {
355
+ const { columns, key } = this.schema[table];
356
+ if (seed) {
357
+ row = Object.fromEntries(Object.entries(row).filter(([name]) => !!columns[name]));
358
+ }
359
+ const keys = Object.keys(row);
360
+ keys.forEach((key) => { if (!columns[key])
361
+ throw new Error(`Unknown column ${table}.${key}`); });
362
+ if (!keys.length)
363
+ throw new Error("Cannot insert an empty local row");
364
+ const result = await tx.query(`INSERT INTO ${quote(table)} (${keys.map(quote).join(", ")}) VALUES (${keys.map((_, index) => `$${index + 1}`).join(", ")}) RETURNING *`, keys.map((key) => row[key]), queryOptions);
365
+ const value = result.rows[0];
366
+ if (!seed)
367
+ for (const [name, column] of Object.entries(columns)) {
368
+ if (!column.nullable && value[name] == null)
369
+ throw new Error(`Required field ${table}.${name} is missing`);
370
+ }
371
+ return JSON.parse(JSON.stringify(value));
372
+ }
373
+ }
374
+ /** Stable per-intent IDs. The server host must use the identical seed contract. */
375
+ export async function deterministicId(scope, commandId, kind, ordinal) {
376
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([scope, commandId, kind, ordinal]))));
377
+ bytes[6] = (bytes[6] & 0x0f) | 0x80;
378
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
379
+ const hex = Array.from(bytes.subarray(0, 16), (byte) => byte.toString(16).padStart(2, "0")).join("");
380
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
381
+ }
382
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAoB,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AA6ClD,MAAM,OAAO,sBAAuB,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C,IAAI,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjJ,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAE,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IACrC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAE,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;IACrC,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACrG,OAAO,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,CAAC;AAC7G,CAAC"}
@@ -0,0 +1,15 @@
1
+ export type LocalColumn = {
2
+ type: string;
3
+ nullable: boolean;
4
+ default?: string;
5
+ };
6
+ export type LocalTableSchema = {
7
+ key: string;
8
+ columns: Record<string, LocalColumn>;
9
+ };
10
+ export type LocalSchema = Record<string, LocalTableSchema>;
11
+ /** Compile schema using PostgreSQL itself, without connecting to a service. */
12
+ export declare function compileLocalSchema(migrations: readonly {
13
+ name: string;
14
+ sql: string;
15
+ }[]): Promise<LocalSchema>;
package/dist/schema.js ADDED
@@ -0,0 +1,55 @@
1
+ import { PGlite } from "@electric-sql/pglite";
2
+ import { pg_trgm } from "@electric-sql/pglite/contrib/pg_trgm";
3
+ // The framework's tenant identity table exists before application migrations.
4
+ // Keep this in parity with TENANT_IDENTITY_SQL in postgres/src/provision.rs.
5
+ const identitySchema = `CREATE TABLE members (
6
+ id text PRIMARY KEY, account_id text NOT NULL UNIQUE, status text NOT NULL DEFAULT 'active',
7
+ display_name text NOT NULL DEFAULT '', avatar_url text NOT NULL DEFAULT '',
8
+ role text NOT NULL DEFAULT 'member', permissions jsonb NOT NULL DEFAULT '{}'::jsonb,
9
+ membership_revision bigint NOT NULL DEFAULT 1,
10
+ created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now()
11
+ )`;
12
+ /** Compile schema using PostgreSQL itself, without connecting to a service. */
13
+ export async function compileLocalSchema(migrations) {
14
+ const db = new PGlite({ extensions: { pg_trgm } });
15
+ try {
16
+ await db.exec(identitySchema);
17
+ for (const migration of migrations) {
18
+ // gen_random_uuid is built into modern PostgreSQL. PGlite does not ship
19
+ // pgcrypto's OpenSSL extension; remaining references fail explicitly.
20
+ const sql = migration.sql.replace(/CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?["']?pgcrypto["']?\s*;/gi, "");
21
+ try {
22
+ await db.exec(sql);
23
+ }
24
+ catch (error) {
25
+ throw new Error(`Local schema compilation failed in ${migration.name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
26
+ }
27
+ }
28
+ const { rows } = await db.query(`SELECT c.relname AS table_name, a.attname AS column_name,
29
+ format_type(a.atttypid, a.atttypmod) AS type, NOT a.attnotnull AS nullable,
30
+ pg_get_expr(d.adbin, d.adrelid) AS column_default,
31
+ EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid=c.oid AND i.indisprimary AND a.attnum=ANY(i.indkey)) AS primary_key
32
+ FROM pg_class c JOIN pg_namespace n ON c.relnamespace=n.oid
33
+ JOIN pg_attribute a ON a.attrelid=c.oid AND a.attnum>0 AND NOT a.attisdropped
34
+ LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum
35
+ WHERE n.nspname='public' AND c.relkind='r'
36
+ ORDER BY c.relname, a.attnum`);
37
+ const schema = {};
38
+ for (const row of rows) {
39
+ if (row.table_name.startsWith("_gonvex"))
40
+ continue;
41
+ const table = schema[row.table_name] ??= { key: "_id", columns: {} };
42
+ if (row.primary_key)
43
+ table.key = row.column_name;
44
+ table.columns[row.column_name] = {
45
+ type: row.type, nullable: row.nullable,
46
+ ...(row.column_default ? { default: row.column_default } : {}),
47
+ };
48
+ }
49
+ return schema;
50
+ }
51
+ finally {
52
+ await db.close();
53
+ }
54
+ }
55
+ //# sourceMappingURL=schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,MAAM,sCAAsC,CAAC;AAM/D,8EAA8E;AAC9E,6EAA6E;AAC7E,MAAM,cAAc,GAAG;;;;;;EAMrB,CAAC;AAEH,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,UAAoD;IAC3F,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,EAAE,UAAU,EAAE,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;IACnD,IAAI,CAAC;QACH,MAAM,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QAC9B,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;YACnC,wEAAwE;YACxE,sEAAsE;YACtE,MAAM,GAAG,GAAG,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,wEAAwE,EAAE,EAAE,CAAC,CAAC;YAChH,IAAI,CAAC;gBAAC,MAAM,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAAC,CAAC;YAC3B,OAAO,KAAK,EAAE,CAAC;gBAAC,MAAM,IAAI,KAAK,CAAC,sCAAsC,SAAS,CAAC,IAAI,KAAK,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YAAC,CAAC;QACzK,CAAC;QACD,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAG5B;;;;;;;;mCAQ4B,CAAC,CAAC;QACjC,MAAM,MAAM,GAAgB,EAAE,CAAC;QAC/B,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,IAAI,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC,SAAS,CAAC;gBAAE,SAAS;YACnD,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;YACrE,IAAI,GAAG,CAAC,WAAW;gBAAE,KAAK,CAAC,GAAG,GAAG,GAAG,CAAC,WAAW,CAAC;YACjD,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG;gBAC/B,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,QAAQ,EAAE,GAAG,CAAC,QAAQ;gBACtC,GAAG,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC/D,CAAC;QACJ,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;YAAS,CAAC;QAAC,MAAM,EAAE,CAAC,KAAK,EAAE,CAAC;IAAC,CAAC;AACjC,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { PortableSchema } from "@gonvex/module-sdk";
2
+ /** Mirrors the Rust portable schema validator, including Unicode lengths. */
3
+ export declare function validateValue(schema: PortableSchema | undefined, value: unknown, path?: string, optional?: boolean): void;
@@ -0,0 +1,86 @@
1
+ /** Mirrors the Rust portable schema validator, including Unicode lengths. */
2
+ export function validateValue(schema, value, path = "$", optional = false) {
3
+ if (!schema)
4
+ return;
5
+ const fail = (message) => { throw new Error(`${path}: ${message}`); };
6
+ const object = () => { if (value === null || typeof value !== "object" || Array.isArray(value))
7
+ fail("expected object"); return value; };
8
+ switch (schema.kind) {
9
+ case "any": return;
10
+ case "string": {
11
+ if (typeof value !== "string")
12
+ fail("expected string");
13
+ const length = [...value].length;
14
+ if (schema.minLength !== undefined && length < schema.minLength)
15
+ fail(`string length must be at least ${schema.minLength}`);
16
+ if (schema.maxLength !== undefined && length > schema.maxLength)
17
+ fail(`string length must be at most ${schema.maxLength}`);
18
+ return;
19
+ }
20
+ case "id":
21
+ if (typeof value !== "string")
22
+ fail("expected entity id string");
23
+ return;
24
+ case "number": {
25
+ if (typeof value !== "number" || !Number.isFinite(value))
26
+ fail("expected number");
27
+ if (schema.integer && !Number.isInteger(value))
28
+ fail("expected integer");
29
+ if (schema.minimum !== undefined && value < schema.minimum)
30
+ fail(`number must be at least ${schema.minimum}`);
31
+ if (schema.maximum !== undefined && value > schema.maximum)
32
+ fail(`number must be at most ${schema.maximum}`);
33
+ return;
34
+ }
35
+ case "boolean":
36
+ if (typeof value !== "boolean")
37
+ fail("expected boolean");
38
+ return;
39
+ case "null":
40
+ if (value !== null)
41
+ fail("expected null");
42
+ return;
43
+ case "literal":
44
+ if (!equal(schema.value, value))
45
+ fail("expected literal");
46
+ return;
47
+ case "array":
48
+ if (!Array.isArray(value))
49
+ fail("expected array");
50
+ value.forEach((item, index) => validateValue(schema.items, item, `${path}[${index}]`));
51
+ return;
52
+ case "record":
53
+ Object.entries(object()).forEach(([key, item]) => validateValue(schema.values, item, `${path}.${key}`));
54
+ return;
55
+ case "object": {
56
+ const input = object();
57
+ for (const [key, field] of Object.entries(schema.fields)) {
58
+ if (!Object.hasOwn(input, key)) {
59
+ if (field.kind !== "optional")
60
+ fail(`${key}: required field is missing`);
61
+ continue;
62
+ }
63
+ validateValue(field, input[key], `${path}.${key}`, true);
64
+ }
65
+ if (!schema.allowUnknown)
66
+ for (const key of Object.keys(input))
67
+ if (!Object.hasOwn(schema.fields, key))
68
+ fail(`${key}: unknown field`);
69
+ return;
70
+ }
71
+ case "optional":
72
+ if (!optional)
73
+ fail("optional is only valid on object fields");
74
+ validateValue(schema.value, value, path);
75
+ return;
76
+ }
77
+ }
78
+ function equal(left, right) {
79
+ if (left === right)
80
+ return true;
81
+ if (!left || !right || typeof left !== "object" || typeof right !== "object" || Array.isArray(left) !== Array.isArray(right))
82
+ return false;
83
+ const a = Object.keys(left), b = Object.keys(right);
84
+ return a.length === b.length && a.every(key => Object.hasOwn(right, key) && equal(left[key], right[key]));
85
+ }
86
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAEA,6EAA6E;AAC7E,MAAM,UAAU,aAAa,CAAC,MAAkC,EAAE,KAAc,EAAE,IAAI,GAAG,GAAG,EAAE,QAAQ,GAAG,KAAK;IAC5G,IAAI,CAAC,MAAM;QAAE,OAAO;IACpB,MAAM,IAAI,GAAG,CAAC,OAAe,EAAS,EAAE,GAAG,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,KAAK,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACrF,MAAM,MAAM,GAAG,GAAG,EAAE,GAAG,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC,CAAC,OAAO,KAAgC,CAAC,CAAC,CAAC,CAAC;IACpK,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,KAAK,CAAC,CAAC,OAAO;QACnB,KAAK,QAAQ,CAAC,CAAC,CAAC;Y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+1,15 @@
1
+ import type { JsonValue } from "@gonvex/module-sdk";
2
+ import type { LocalExecution, LocalIntent, LocalReplay, LocalSnapshot, LocalTransactionResult } from "./index.js";
3
+ export type LocalExecutor = {
4
+ ready: Promise<void>;
5
+ execute(path: string, args: JsonValue, snapshot: LocalSnapshot, execution: LocalExecution): Promise<LocalTransactionResult>;
6
+ replay(snapshot: LocalSnapshot, intents: readonly LocalIntent[]): Promise<LocalReplay>;
7
+ close(): void;
8
+ };
9
+ export type LocalRuntimeBinding = {
10
+ artifactHash: string;
11
+ tables: readonly string[];
12
+ create(): LocalExecutor;
13
+ };
14
+ /** Worker lifetime and RPC are SDK-owned; applications only import generated bindings. */
15
+ export declare function createLocalReducerWorker(worker: Worker): LocalExecutor;
@@ -0,0 +1,54 @@
1
+ /** Worker lifetime and RPC are SDK-owned; applications only import generated bindings. */
2
+ export function createLocalReducerWorker(worker) {
3
+ let sequence = 0;
4
+ let closed = false;
5
+ let failure;
6
+ const pending = new Map();
7
+ const ready = new Promise((resolve, reject) => { pending.set(0, { resolve, reject }); });
8
+ // An eager worker can fail before the first reducer is called.
9
+ void ready.catch(() => undefined);
10
+ const fail = (error) => {
11
+ failure = error;
12
+ for (const callback of pending.values())
13
+ callback.reject(error);
14
+ pending.clear();
15
+ };
16
+ worker.addEventListener("error", (event) => fail(new Error(event.message || "Local reducer worker failed")));
17
+ worker.addEventListener("messageerror", () => fail(new Error("Local reducer worker response could not be decoded")));
18
+ worker.addEventListener("message", (event) => {
19
+ const message = event.data;
20
+ const callback = pending.get(message?.id);
21
+ if (!callback)
22
+ return;
23
+ pending.delete(message.id);
24
+ if (message.error)
25
+ callback.reject(Object.assign(new Error(message.error.message), { name: message.error.name }));
26
+ else
27
+ callback.resolve(message.result);
28
+ });
29
+ const call = async (method, args) => {
30
+ await ready;
31
+ if (failure)
32
+ throw failure;
33
+ if (closed)
34
+ throw new Error("Local reducer worker is closed");
35
+ const id = ++sequence;
36
+ return new Promise((resolve, reject) => {
37
+ pending.set(id, { resolve, reject });
38
+ try {
39
+ worker.postMessage({ id, method, args });
40
+ }
41
+ catch (error) {
42
+ pending.delete(id);
43
+ reject(error);
44
+ }
45
+ });
46
+ };
47
+ return {
48
+ ready,
49
+ execute: (...args) => call("execute", args),
50
+ replay: (...args) => call("replay", args),
51
+ close: () => { closed = true; worker.terminate(); fail(new Error("Local reducer worker closed")); },
52
+ };
53
+ }
54
+ //# sourceMappingURL=worker-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-client.js","sourceRoot":"","sources":["../src/worker-client.ts"],"names":[],"mappings":"AAWA,0FAA0F;AAC1F,MAAM,UAAU,wBAAwB,CAAC,MAAc;IACrD,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,IAAI,OAA0B,CAAC;IAC/B,MAAM,OAAO,GAAG,IAAI,GAAG,EAAqE,CAAC;IAC7F,MAAM,KAAK,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/F,+DAA+D;IAC/D,KAAK,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAClC,MAAM,IAAI,GAAG,CAAC,KAAY,EAAE,EAAE;QAC5B,OAAO,GAAG,KAAK,CAAC;QAChB,KAAK,MAAM,QAAQ,IAAI,OAAO,CAAC,MAAM,EAAE;YAAE,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAChE,OAAO,CAAC,KAAK,EAAE,CAAC;IAClB,CAAC,CAAC;IACF,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,OAAO,IAAI,6BAA6B,CAAC,CAAC,C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AC,CAAC;YAAC,CAAC;YACjD,OAAO,KAAK,EAAE,CAAC;gBAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAAC,CAAC;QACtD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO;QACL,KAAK;QACL,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC;QAC3C,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC;QACzC,KAAK,EAAE,GAAG,EAAE,GAAG,MAAM,GAAG,IAAI,CAAC,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC,CAAC,CAAC,CAAC;KACpG,CAAC;AACJ,CAAC"}
@@ -0,0 +1,3 @@
1
+ import { type LocalRuntimeOptions } from "./index.js";
2
+ /** Generated worker entrypoint calls this exactly once. */
3
+ export declare function serveLocalReducerWorker(options: LocalRuntimeOptions): void;
package/dist/worker.js ADDED
@@ -0,0 +1,35 @@
1
+ import { LocalReducerRuntime } from "./index.js";
2
+ /** Generated worker entrypoint calls this exactly once. */
3
+ export function serveLocalReducerWorker(options) {
4
+ const host = new LocalReducerRuntime(options);
5
+ const endpoint = globalThis;
6
+ const respond = async (id, run) => {
7
+ try {
8
+ endpoint.postMessage({ id, result: await run() });
9
+ }
10
+ catch (error) {
11
+ endpoint.postMessage({ id, error: { name: error instanceof Error ? error.name : "Error", message: error instanceof Error ? error.message : String(error) } });
12
+ }
13
+ };
14
+ void respond(0, async () => {
15
+ await host.initializeReady();
16
+ // WASM is loaded before closing ambient network access. Reducers enqueue
17
+ // external work through ctx.actions; they cannot send it during prediction.
18
+ const denied = () => { throw new Error("External I/O is unavailable in a local Reducer; enqueue an Action"); };
19
+ Object.defineProperty(globalThis, "fetch", { value: denied, writable: false, configurable: false });
20
+ Object.defineProperty(globalThis, "WebSocket", { value: denied, writable: false, configurable: false });
21
+ Object.defineProperty(globalThis, "XMLHttpRequest", { value: denied, writable: false, configurable: false });
22
+ });
23
+ endpoint.addEventListener("message", ({ data }) => {
24
+ if (!data || !Number.isSafeInteger(data.id) || !Array.isArray(data.args))
25
+ return;
26
+ void respond(data.id, async () => {
27
+ if (data.method === "execute")
28
+ return host.execute(data.args[0], data.args[1], data.args[2], data.args[3]);
29
+ if (data.method === "replay")
30
+ return host.replay(data.args[0], data.args[1]);
31
+ throw new Error("Unknown local reducer operation");
32
+ });
33
+ });
34
+ }
35
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAA4B,MAAM,YAAY,CAAC;AAE3E,2DAA2D;AAC3D,MAAM,UAAU,uBAAuB,CAAC,OAA4B;IAClE,MAAM,IAAI,GAAG,IAAI,mBAAmB,CAAC,OAAO,CAAC,CAAC;IAC9C,MAAM,QAAQ,GAAG,UAGhB,CAAC;IACF,MAAM,OAAO,GAAG,KAAK,EAAE,EAAU,EAAE,GAA2B,EAAE,EAAE;QAChE,IAAI,CAAC;YAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,EAAE,EAAE,CAAC,CAAC;QAAC,CAAC;QAC1D,OAAO,KAAK,EAAE,CAAC;YAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EA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C,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;YAC3G,IAAI,IAAI,CAAC,MAAM,KAAK,QAAQ;gBAAE,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;YAC7E,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;QACrD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"}
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@gonvex/local-runtime",
3
+ "version": "0.5.2-staging.11",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "default": "./dist/index.js"
9
+ },
10
+ "./schema": {
11
+ "types": "./dist/schema.d.ts",
12
+ "default": "./dist/schema.js"
13
+ },
14
+ "./worker": {
15
+ "types": "./dist/worker.d.ts",
16
+ "default": "./dist/worker.js"
17
+ },
18
+ "./worker-client": {
19
+ "types": "./dist/worker-client.d.ts",
20
+ "default": "./dist/worker-client.js"
21
+ }
22
+ },
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "files": [
26
+ "dist",
27
+ "README.md"
28
+ ],
29
+ "dependencies": {
30
+ "@electric-sql/pglite": "0.5.8",
31
+ "@gonvex/module-sdk": "0.5.2-staging.11"
32
+ },
33
+ "devDependencies": {
34
+ "typescript": "^6.0.3",
35
+ "vitest": "^4.1.6"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.json",
42
+ "typecheck": "tsc -p tsconfig.json --noEmit",
43
+ "test": "vitest run --maxWorkers=1"
44
+ }
45
+ }