@rindle/normalized 0.1.0-rc.5

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,23 @@
1
+ # @rindle/normalized
2
+
3
+ The **normalized local-first** client glue (`NORMALIZED-CHANGES-DESIGN.md` §5/§7) — the
4
+ sibling of the flat remote client that runs its **own local DB** and queries over it (so it
5
+ can do optimistic writes + local query resolution), with its base tables fed by a server
6
+ stream instead of by direct user writes.
7
+
8
+ This package's Slice 4 surface is **`NormalizedSync`**: the cross-query refcount + GC layer
9
+ that sits between the per-query normalized streams (`NormalizedOp` batches, validated by
10
+ `@rindle/remote`) and the one shared local store (the `@rindle/wasm` `Db`'s base tables).
11
+
12
+ - The **server** already de-duplicates *intra-query* multi-path (NormalizeFold, §4.2).
13
+ - `NormalizedSync` does the *cross-query* refcount the server deliberately does **not** —
14
+ keyed by `(table, pk)`, each query's footprint a membership set. A row shared by N queries
15
+ lands in the local `Db` **once** and is GC'd only when the last query stops referencing it.
16
+ No CVR — the refcount lives on the client, per row.
17
+
18
+ It is pure logic: `applyBatch(queryId, ops)` / `rehydrate(queryId, snapshot)` /
19
+ `dropQuery(queryId)` each return the NET `Mutation[]` to commit to the wasm `Db` in one
20
+ transaction. The `Db` re-materializes and each query's `FlatArrayView` folds the result.
21
+
22
+ The `NormalizedStore` wiring (remote normalized stream → `NormalizedSync` → wasm `Db`) lands
23
+ in Slice 5.
@@ -0,0 +1,19 @@
1
+ import type { Ast, CorrelatedSubquery, NormalizedTableSchema } from "@rindle/client";
2
+ /** The synthetic base-table name for a relationship `count` aggregate — the byte-exact twin
3
+ * of Rust `agg_table_name` (`normalize.rs` §3.1). A content hash of the aggregate definition
4
+ * (child table, kind, group key = correlation **child** fields, child `where`); the parent
5
+ * correlation field is excluded. Same definition ⇒ same name (cross-query sharing); a
6
+ * different filter ⇒ a different name (no `(table, pk)` collision). */
7
+ export declare function aggTableName(csq: CorrelatedSubquery): string;
8
+ /** Every synthetic aggregate table `ast` surfaces (recursively, a nested aggregate under a
9
+ * materialized relationship included), as flat table schemas — the twin of Rust
10
+ * `agg_table_schemas`. Columns `[childField…, "count"]`; PK = the leading group columns. */
11
+ export declare function aggTableSchemas(ast: Ast): NormalizedTableSchema[];
12
+ /** Rewrite an AST for the LOCAL engine: each relationship `count` becomes a precomputed,
13
+ * source-backed singular relationship over its synthetic table — read the server's count
14
+ * with a plain join + the same scalar projection (`aggregatePrecomputed`), never a `reduce`
15
+ * (which would recount the already-aggregated rows). Non-aggregate relationships recurse
16
+ * (a nested aggregate is rewritten too); the parent's frame is otherwise untouched, so the
17
+ * view-schema slot order is preserved. Returns a new AST; the input is not mutated. */
18
+ export declare function rewriteAggregates(ast: Ast): Ast;
19
+ //# sourceMappingURL=agg-table.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agg-table.d.ts","sourceRoot":"","sources":["../src/agg-table.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAEV,GAAG,EAEH,kBAAkB,EAGlB,qBAAqB,EAEtB,MAAM,gBAAgB,CAAC;AAsCxB;;;;wEAIwE;AACxE,wBAAgB,YAAY,CAAC,GAAG,EAAE,kBAAkB,GAAG,MAAM,CAM5D;AA8FD;;6FAE6F;AAC7F,wBAAgB,eAAe,CAAC,GAAG,EAAE,GAAG,GAAG,qBAAqB,EAAE,CAIjE;AAiBD;;;;;wFAKwF;AACxF,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,CAG/C"}
@@ -0,0 +1,211 @@
1
+ // Synthetic aggregate tables (AGGREGATE-SYNC-DESIGN.md §3.1/§3.3) — the client twin of
2
+ // `rindle-replica/src/normalize.rs`. A relationship `count` is never recomputed locally
3
+ // (the client lacks the child rows); the server ships the reduce's `(group_key, count)`
4
+ // output as a SYNTHETIC base table, and the client:
5
+ // 1. registers that table on its local engine + the `NormalizedSync` refcount layer,
6
+ // 2. rewrites the local AST so the relationship reads the table with a plain singular
7
+ // join + the same scalar projection (`aggregatePrecomputed`) instead of a reduce.
8
+ //
9
+ // The table NAME is a content hash of the aggregate's definition, so client and server
10
+ // agree without coordinating. `aggTableName` is the **byte-exact** twin of Rust
11
+ // `agg_table_name` — the FNV-1a-64 byte protocol documented there; cross-language vectors
12
+ // pin it (Rust `agg_table_name_cross_language_vector` ↔ this module's test).
13
+ // FNV-1a-64, the same constants as `protocol.ts`'s `Fnv` (a local copy so `@rindle/normalized`
14
+ // keeps no dependency on `@rindle/remote`). The byte methods mirror Rust `normalize::Fnv`.
15
+ const FNV_OFFSET = 0xcbf29ce484222325n;
16
+ const FNV_PRIME = 0x00000100000001b3n;
17
+ const MASK = 0xffffffffffffffffn;
18
+ const enc = new TextEncoder();
19
+ class Fnv {
20
+ h = FNV_OFFSET;
21
+ byte(b) {
22
+ this.h = ((this.h ^ BigInt(b & 0xff)) * FNV_PRIME) & MASK;
23
+ }
24
+ /** A `u32` little-endian (Rust `v.to_le_bytes()`). */
25
+ u32(v) {
26
+ this.byte(v & 0xff);
27
+ this.byte((v >>> 8) & 0xff);
28
+ this.byte((v >>> 16) & 0xff);
29
+ this.byte((v >>> 24) & 0xff);
30
+ }
31
+ /** A length-prefixed string: `u32(byteLen)` then UTF-8 bytes. */
32
+ s(str) {
33
+ const bytes = enc.encode(str);
34
+ this.u32(bytes.length);
35
+ for (const b of bytes)
36
+ this.byte(b);
37
+ }
38
+ /** An `f64` little-endian (Rust `n.to_le_bytes()` — IEEE-754 binary64). */
39
+ f64(v) {
40
+ const buf = new ArrayBuffer(8);
41
+ new DataView(buf).setFloat64(0, v, true);
42
+ for (const b of new Uint8Array(buf))
43
+ this.byte(b);
44
+ }
45
+ hex() {
46
+ return this.h.toString(16).padStart(16, "0");
47
+ }
48
+ }
49
+ /** The synthetic base-table name for a relationship `count` aggregate — the byte-exact twin
50
+ * of Rust `agg_table_name` (`normalize.rs` §3.1). A content hash of the aggregate definition
51
+ * (child table, kind, group key = correlation **child** fields, child `where`); the parent
52
+ * correlation field is excluded. Same definition ⇒ same name (cross-query sharing); a
53
+ * different filter ⇒ a different name (no `(table, pk)` collision). */
54
+ export function aggTableName(csq) {
55
+ const f = new Fnv();
56
+ f.u32(csq.correlation.childField.length);
57
+ for (const cf of csq.correlation.childField)
58
+ f.s(cf);
59
+ hashAggSubquery(f, csq.subquery);
60
+ return `__agg_${f.hex()}`;
61
+ }
62
+ function hashAggSubquery(f, ast) {
63
+ f.s(ast.table);
64
+ f.byte(ast.aggregate === "count" ? 1 : 0); // Some(Count)=1, None=0
65
+ if (ast.where === undefined)
66
+ f.byte(0);
67
+ else {
68
+ f.byte(1);
69
+ hashCondition(f, ast.where);
70
+ }
71
+ const related = ast.related ?? [];
72
+ f.u32(related.length);
73
+ for (const r of related) {
74
+ hashCorrelation(f, r.correlation);
75
+ hashAggSubquery(f, r.subquery);
76
+ }
77
+ }
78
+ function hashCorrelation(f, c) {
79
+ f.u32(c.parentField.length);
80
+ for (const p of c.parentField)
81
+ f.s(p);
82
+ f.u32(c.childField.length);
83
+ for (const x of c.childField)
84
+ f.s(x);
85
+ }
86
+ function hashCondition(f, cond) {
87
+ switch (cond.type) {
88
+ case "simple":
89
+ f.byte(0);
90
+ f.s(cond.op); // SimpleOp is the wire string ("=", "!=", …) === Rust `op_str`
91
+ hashValuePosition(f, cond.left);
92
+ hashValuePosition(f, cond.right);
93
+ break;
94
+ case "and":
95
+ f.byte(1);
96
+ f.u32(cond.conditions.length);
97
+ for (const c of cond.conditions)
98
+ hashCondition(f, c);
99
+ break;
100
+ case "or":
101
+ f.byte(2);
102
+ f.u32(cond.conditions.length);
103
+ for (const c of cond.conditions)
104
+ hashCondition(f, c);
105
+ break;
106
+ case "correlatedSubquery":
107
+ f.byte(3);
108
+ f.byte(cond.op === "EXISTS" ? 1 : 0); // Exists=1, NotExists=0
109
+ f.byte(systemByte(cond.related.system));
110
+ hashCorrelation(f, cond.related.correlation);
111
+ hashAggSubquery(f, cond.related.subquery);
112
+ break;
113
+ }
114
+ }
115
+ function systemByte(sys) {
116
+ switch (sys) {
117
+ case "permissions":
118
+ return 1; // System::Permissions
119
+ case "client":
120
+ return 2; // System::Client
121
+ case "test":
122
+ return 3; // System::Test
123
+ default:
124
+ return 0; // None
125
+ }
126
+ }
127
+ function hashValuePosition(f, vp) {
128
+ if (vp.type === "column") {
129
+ f.byte(0);
130
+ f.s(vp.name);
131
+ }
132
+ else {
133
+ f.byte(1);
134
+ hashLit(f, vp.value);
135
+ }
136
+ }
137
+ function hashLit(f, lit) {
138
+ if (lit === null)
139
+ f.byte(0);
140
+ else if (typeof lit === "boolean") {
141
+ f.byte(1);
142
+ f.byte(lit ? 1 : 0);
143
+ }
144
+ else if (typeof lit === "number") {
145
+ f.byte(2);
146
+ f.f64(lit);
147
+ }
148
+ else if (typeof lit === "string") {
149
+ f.byte(3);
150
+ f.s(lit);
151
+ }
152
+ else {
153
+ f.byte(4);
154
+ f.u32(lit.length);
155
+ for (const x of lit)
156
+ hashLit(f, x);
157
+ }
158
+ }
159
+ /** Every synthetic aggregate table `ast` surfaces (recursively, a nested aggregate under a
160
+ * materialized relationship included), as flat table schemas — the twin of Rust
161
+ * `agg_table_schemas`. Columns `[childField…, "count"]`; PK = the leading group columns. */
162
+ export function aggTableSchemas(ast) {
163
+ const out = [];
164
+ collectAggTables(ast, out);
165
+ return out;
166
+ }
167
+ function collectAggTables(ast, out) {
168
+ for (const r of ast.related ?? []) {
169
+ if (r.subquery.aggregate) {
170
+ const k = r.correlation.childField.length;
171
+ out.push({
172
+ name: aggTableName(r),
173
+ columns: [...r.correlation.childField, "count"],
174
+ primaryKey: Array.from({ length: k }, (_, i) => i),
175
+ });
176
+ }
177
+ else {
178
+ collectAggTables(r.subquery, out);
179
+ }
180
+ }
181
+ }
182
+ /** Rewrite an AST for the LOCAL engine: each relationship `count` becomes a precomputed,
183
+ * source-backed singular relationship over its synthetic table — read the server's count
184
+ * with a plain join + the same scalar projection (`aggregatePrecomputed`), never a `reduce`
185
+ * (which would recount the already-aggregated rows). Non-aggregate relationships recurse
186
+ * (a nested aggregate is rewritten too); the parent's frame is otherwise untouched, so the
187
+ * view-schema slot order is preserved. Returns a new AST; the input is not mutated. */
188
+ export function rewriteAggregates(ast) {
189
+ if (!ast.related?.length)
190
+ return ast;
191
+ return { ...ast, related: ast.related.map(rewriteRelationship) };
192
+ }
193
+ function rewriteRelationship(csq) {
194
+ if (csq.subquery.aggregate) {
195
+ const subquery = {
196
+ table: aggTableName(csq),
197
+ aggregate: csq.subquery.aggregate,
198
+ aggregatePrecomputed: true,
199
+ };
200
+ // The correlation is unchanged: the synthetic table's group columns are named after the
201
+ // child correlation fields, so `childField` still resolves against `[childField…, count]`.
202
+ if (csq.subquery.alias !== undefined)
203
+ subquery.alias = csq.subquery.alias;
204
+ const out = { correlation: csq.correlation, subquery };
205
+ if (csq.system !== undefined)
206
+ out.system = csq.system;
207
+ return out;
208
+ }
209
+ return { ...csq, subquery: rewriteAggregates(csq.subquery) };
210
+ }
211
+ //# sourceMappingURL=agg-table.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agg-table.js","sourceRoot":"","sources":["../src/agg-table.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,wFAAwF;AACxF,wFAAwF;AACxF,oDAAoD;AACpD,uFAAuF;AACvF,wFAAwF;AACxF,uFAAuF;AACvF,EAAE;AACF,uFAAuF;AACvF,gFAAgF;AAChF,0FAA0F;AAC1F,6EAA6E;AAa7E,+FAA+F;AAC/F,2FAA2F;AAC3F,MAAM,UAAU,GAAG,mBAAmB,CAAC;AACvC,MAAM,SAAS,GAAG,mBAAmB,CAAC;AACtC,MAAM,IAAI,GAAG,mBAAmB,CAAC;AACjC,MAAM,GAAG,GAAG,IAAI,WAAW,EAAE,CAAC;AAE9B,MAAM,GAAG;IACP,CAAC,GAAG,UAAU,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GAAG,CAAC;IACb,CAAC;IACD,OAAO,EAAE,GAAG,GAAG,EAAE,QAAQ,EAAE,iBAAiB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;AAC/D,CAAC"}
@@ -0,0 +1,53 @@
1
+ import { Store } from "@rindle/client";
2
+ import type { Ast, Backend, ChangeEvent, ColsMap, Mutation, NormalizedSource, QueryId, RemoteQuery, Schema } from "@rindle/client";
3
+ export type { NormalizedEvent, NormalizedSource, NormalizedTableSchema } from "@rindle/client";
4
+ export declare class NormalizedBackend<S extends ColsMap> implements Backend {
5
+ private readonly local;
6
+ private readonly sync;
7
+ private readonly source;
8
+ private handler;
9
+ private readonly remoteSubs;
10
+ private readonly localToRemote;
11
+ /** The client's OWN typed per-table schemas (for CRIT#4 validation), fixed at construction. */
12
+ private readonly clientTables;
13
+ /** Synthetic aggregate tables (`__agg_*`) registered so far, by name (§3.3). Per aggregate
14
+ * DEFINITION (not per query), so two queries over the same count share one table. */
15
+ private readonly synthetic;
16
+ /** table → (column name → base ColId), for mapping a projected hello to base positions. */
17
+ private readonly colIndex;
18
+ /** table → full column count, to detect whether a hello's table is projected. */
19
+ private readonly colCounts;
20
+ /** Synthetic table name → how many registered queries reference it. Materialized on `0→1`,
21
+ * reclaimed (engine source + refcount layer) on `1→0` — so aggregate state is not permanent (§4). */
22
+ private readonly syntheticRefs;
23
+ /** queryId → the synthetic tables it referenced at registration, to decrement on teardown. */
24
+ private readonly queryAggTables;
25
+ constructor(schema: Schema<S>, source: NormalizedSource);
26
+ registerQuery(qid: QueryId, ast: Ast, remote?: RemoteQuery): void;
27
+ /** Register every synthetic aggregate table `ast` needs that we haven't seen yet: on the
28
+ * local engine (so it can join to it), on `NormalizedSync` (so its rows refcount/GC by
29
+ * group key), and into the source's expected-schema set (so the server's `hello` — which
30
+ * advertises the same table — passes CRIT#4 validation, the client deriving the schema
31
+ * identically). Idempotent across queries that share an aggregate definition. */
32
+ private ensureSyntheticTables;
33
+ /** Decrement each synthetic table query `qid` referenced; remove the ones that reach 0 (no
34
+ * reader left) from the engine + refcount layer — aggregate state reclaimed, not permanent
35
+ * (§4). Runs AFTER `local.unregisterQuery(qid)` so the source has no live connection when
36
+ * `unregisterTable` frees it. */
37
+ private releaseSyntheticTables;
38
+ unregisterQuery(qid: QueryId): void;
39
+ retainRemoteQuery(qid: QueryId, remote: RemoteQuery): void;
40
+ releaseRemoteQuery(qid: QueryId): void;
41
+ /** Writes are authoritative-only here: send to the server, the stream reconciles locally.
42
+ * (Optimistic local apply + rebase is Slice 6.) */
43
+ mutate(mutations: Mutation[]): Promise<void>;
44
+ onEvent(handler: (qid: QueryId, ev: ChangeEvent) => void): void;
45
+ private onNormalized;
46
+ private retainRemote;
47
+ private releaseRemote;
48
+ }
49
+ /** A local-first {@link Store} whose base tables are fed by a server's normalized stream.
50
+ * The returned Store is the ordinary `@rindle/client` Store — `store.query…materialize()` and
51
+ * `store.write(…)` work as always; only the backend composition differs. */
52
+ export declare function createNormalizedStore<S extends ColsMap>(schema: Schema<S>, source: NormalizedSource): Store<S>;
53
+ //# sourceMappingURL=backend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backend.d.ts","sourceRoot":"","sources":["../src/backend.ts"],"names":[],"mappings":"AAoBA,OAAO,EAA0B,KAAK,EAAa,MAAM,gBAAgB,CAAC;AAC1E,OAAO,KAAK,EACV,GAAG,EACH,OAAO,EACP,WAAW,EACX,OAAO,EACP,QAAQ,EAER,gBAAgB,EAEhB,OAAO,EACP,WAAW,EACX,MAAM,EACP,MAAM,gBAAgB,CAAC;AASxB,YAAY,EAAE,eAAe,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AA2B/F,qBAAa,iBAAiB,CAAC,CAAC,SAAS,OAAO,CAAE,YAAW,OAAO;IAClE,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAiB;IACvC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiB;IACtC,OAAO,CAAC,QAAQ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