@pgxsinkit/client 0.1.46 → 0.1.49

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.
@@ -0,0 +1,128 @@
1
+ // Canonical fingerprint for a live query (ADR-0040 decisions 2 & 3). Two identical live queries — same
2
+ // POST-WRAP SQL, same bound params, same key mode — must map to ONE PGlite registration; anything that
3
+ // changes what PGlite actually runs (or how the diff is keyed) must map to a DISTINCT one. The fingerprint
4
+ // covers EXECUTION-relevant inputs only: the materialized SQL, a TYPED encoding of the params, and the PK
5
+ // columns (which pick `live.incrementalQuery` vs `live.query` and drive the diff key). `use` is deliberately
6
+ // NOT an input — activation/hydration are per-subscriber pre-steps that never influence the registration
7
+ // (ADR-0040 decision 3), so keying on `use` would only split sharing.
8
+ //
9
+ // The param codec runs over the DECODED (structured-clone) values and TAGS every leaf by type, so a value
10
+ // can never collide with a different-typed value that happens to stringify the same — a `Date` never with
11
+ // its ISO string, a `Uint8Array` never with its hex text, a number never with its numeric string.
12
+
13
+ /** The map key (full canonical string — the dedup identity) plus a short digest for diagnostics (Slice 5). */
14
+ export interface LiveQueryFingerprint {
15
+ /** The exact dedup key: two subscriptions share a registration iff their `key` is identical. */
16
+ key: string;
17
+ /** A short, opaque hash of `key` — for diagnostics/observability only, NEVER used for dedup. */
18
+ digest: string;
19
+ }
20
+
21
+ // Per-call unique token for values we cannot canonicalize (unknown prototypes). A random suffix guarantees
22
+ // two opaque values never collide; the counter guarantees uniqueness even within one millisecond.
23
+ let opaqueCounter = 0;
24
+ function opaqueToken(): string {
25
+ return `${(opaqueCounter++).toString(36)}.${Math.random().toString(36).slice(2)}`;
26
+ }
27
+
28
+ /** Lowercase hex of a byte buffer — portable (no `Buffer`/`btoa`, so it runs in a browser SharedWorker). */
29
+ function toHex(bytes: Uint8Array): string {
30
+ let hex = "";
31
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
32
+ return hex;
33
+ }
34
+
35
+ function isPlainObject(value: object): boolean {
36
+ const proto = Object.getPrototypeOf(value);
37
+ return proto === Object.prototype || proto === null;
38
+ }
39
+
40
+ /** A JSON-safe, type-tagged encoding node: a `[tag, …payload]` tuple whose first element is the type tag. */
41
+ type Encoded = readonly [string, ...unknown[]];
42
+
43
+ /**
44
+ * Encode one decoded value into a type-TAGGED, JSON-SAFE STRUCTURE (a `[tag, …]` tuple), never a flat string.
45
+ * The tag is the first array element, so two values of different types can never collide, and because the
46
+ * whole tuple is serialized ONCE with `JSON.stringify` (below), JSON does all the escaping/framing — a
47
+ * delimiter-bearing string in an array or object can no longer masquerade as extra members (the flat-string
48
+ * codec's collision class, e.g. `[["x,s:y"]]` vs `[["x","y"]]`). Recurses through arrays (order-significant)
49
+ * and plain objects (keys SORTED, so object key order never changes the fingerprint).
50
+ */
51
+ function encodeValue(value: unknown): Encoded {
52
+ if (value === null) return ["z"]; // null
53
+ if (value === undefined) return ["v"]; // undefined (distinct from null)
54
+ switch (typeof value) {
55
+ case "boolean":
56
+ return ["b", value];
57
+ case "number":
58
+ // `String` already canonicalizes signed zero (`String(-0) === "0"`) and renders NaN/±Infinity
59
+ // deterministically; NaN is an ALLOWED value here (two NaN params share a fingerprint), not a bail-out.
60
+ return ["n", String(value)];
61
+ case "bigint":
62
+ return ["i", value.toString()];
63
+ case "string":
64
+ return ["s", value];
65
+ case "object": {
66
+ if (value instanceof Date) return ["d", value.getTime()]; // tagged epoch-ms — never equals an ISO string
67
+ if (value instanceof Uint8Array) return ["x", toHex(value)];
68
+ if (value instanceof ArrayBuffer) return ["x", toHex(new Uint8Array(value))];
69
+ // Honour the view's window: encoding the WHOLE underlying buffer would falsely collide two different
70
+ // views sharing one buffer (a wrong-dedup — the exact hazard this codec exists to prevent).
71
+ if (ArrayBuffer.isView(value)) {
72
+ const view = value as ArrayBufferView;
73
+ return ["x", toHex(new Uint8Array(view.buffer, view.byteOffset, view.byteLength))];
74
+ }
75
+ if (Array.isArray(value)) return ["a", value.map(encodeValue)];
76
+ if (isPlainObject(value)) {
77
+ const record = value as Record<string, unknown>;
78
+ const members = Object.keys(record)
79
+ .sort()
80
+ .map((k) => [k, encodeValue(record[k])] as const);
81
+ return ["o", members];
82
+ }
83
+ // Unknown prototype (a class instance, Map, Set, …): we cannot canonicalize it safely, so tag it
84
+ // `opaque` with a per-call unique token — it will NEVER dedup with anything (including an identical
85
+ // instance) and NEVER falsely collide. Correctness over sharing for the values we don't understand.
86
+ return ["q", opaqueToken()];
87
+ }
88
+ default:
89
+ // function / symbol — not producible by structured clone, but stay safe: treat as opaque.
90
+ return ["q", opaqueToken()];
91
+ }
92
+ }
93
+
94
+ /** FNV-1a (32-bit) → 8 hex chars. Diagnostics only; the FULL `key` string is the dedup identity, never this. */
95
+ function shortDigest(key: string): string {
96
+ let hash = 0x811c9dc5;
97
+ for (let i = 0; i < key.length; i++) {
98
+ hash ^= key.charCodeAt(i);
99
+ hash = Math.imul(hash, 0x01000193);
100
+ }
101
+ return (hash >>> 0).toString(16).padStart(8, "0");
102
+ }
103
+
104
+ /**
105
+ * Fingerprint a live query. `materialSql` is the POST-WRAP SQL (the manager's registration input); `params`
106
+ * are the decoded bound params; `pkColumns` selects the key mode. Returns the full canonical `key` (the dedup
107
+ * identity) and a short `digest` for diagnostics.
108
+ */
109
+ export function fingerprintLiveQuery(
110
+ materialSql: string,
111
+ params: readonly unknown[],
112
+ pkColumns?: readonly string[],
113
+ ): LiveQueryFingerprint {
114
+ // Single-column PK → PGlite `live.incrementalQuery`; composite/keyless → `live.query` + worker-side diff.
115
+ // The mode AND the exact pk columns both matter: same SQL with a different pk column is a different
116
+ // registration (different diff key), and incremental vs full are different PGlite machines.
117
+ const mode = pkColumns && pkColumns.length === 1 ? "inc" : "full";
118
+ // ONE `JSON.stringify` over a fixed-shape object of type-tagged encoding STRUCTURES: the SQL is its own JSON
119
+ // string element (cannot bleed into params), and JSON escaping makes the whole key unambiguous — no manual
120
+ // delimiter framing anywhere, so no delimiter-bearing value can forge extra structure.
121
+ const key = JSON.stringify({
122
+ sql: materialSql,
123
+ params: params.map(encodeValue),
124
+ pk: pkColumns ? [...pkColumns] : null,
125
+ mode,
126
+ });
127
+ return { key, digest: shortDigest(key) };
128
+ }