@spooky-sync/core 0.0.1-canary.16 → 0.0.1-canary.161

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 (123) hide show
  1. package/AGENTS.md +56 -0
  2. package/dist/index.d.ts +1406 -364
  3. package/dist/index.js +7773 -1391
  4. package/dist/otel/index.d.ts +21 -0
  5. package/dist/otel/index.js +86 -0
  6. package/dist/sqlite-open.js +276 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +420 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +434 -0
  11. package/dist/types.d.ts +874 -0
  12. package/package.json +20 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/sp00ky-core/SKILL.md +258 -0
  15. package/skills/sp00ky-core/references/auth.md +98 -0
  16. package/skills/sp00ky-core/references/config.md +76 -0
  17. package/src/build-globals.d.ts +12 -0
  18. package/src/events/events.test.ts +2 -1
  19. package/src/events/index.ts +3 -0
  20. package/src/index.ts +16 -2
  21. package/src/modules/app-release/index.test.ts +125 -0
  22. package/src/modules/app-release/index.ts +201 -0
  23. package/src/modules/auth/events/index.ts +2 -1
  24. package/src/modules/auth/index.ts +59 -20
  25. package/src/modules/cache/index.ts +112 -32
  26. package/src/modules/cache/types.ts +2 -2
  27. package/src/modules/crdt/crdt-field.ts +294 -0
  28. package/src/modules/crdt/crdt-hydration.test.ts +206 -0
  29. package/src/modules/crdt/index.ts +361 -0
  30. package/src/modules/crdt/loro-loader.ts +25 -0
  31. package/src/modules/data/data.hydration.test.ts +142 -0
  32. package/src/modules/data/data.rebind.test.ts +147 -0
  33. package/src/modules/data/data.run.test.ts +113 -0
  34. package/src/modules/data/data.status.test.ts +249 -0
  35. package/src/modules/data/index.ts +1151 -129
  36. package/src/modules/data/mutation-id.test.ts +25 -0
  37. package/src/modules/data/mutation-id.ts +35 -0
  38. package/src/modules/data/window-query.test.ts +52 -0
  39. package/src/modules/data/window-query.ts +154 -0
  40. package/src/modules/devtools/index.ts +325 -37
  41. package/src/modules/devtools/notify-throttle.test.ts +149 -0
  42. package/src/modules/devtools/storage-info.test.ts +79 -0
  43. package/src/modules/devtools/storage-info.ts +143 -0
  44. package/src/modules/devtools/versions.test.ts +74 -0
  45. package/src/modules/devtools/versions.ts +81 -0
  46. package/src/modules/feature-flag/index.test.ts +120 -0
  47. package/src/modules/feature-flag/index.ts +209 -0
  48. package/src/modules/ref-tables.test.ts +91 -0
  49. package/src/modules/ref-tables.ts +88 -0
  50. package/src/modules/sync/engine.ts +101 -37
  51. package/src/modules/sync/events/index.ts +9 -2
  52. package/src/modules/sync/queue/queue-down.ts +12 -5
  53. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  54. package/src/modules/sync/queue/queue-up.ts +216 -56
  55. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  56. package/src/modules/sync/scheduler.ts +77 -9
  57. package/src/modules/sync/sync.health.test.ts +149 -0
  58. package/src/modules/sync/sync.subquery.test.ts +82 -0
  59. package/src/modules/sync/sync.ts +1333 -92
  60. package/src/modules/sync/utils.test.ts +269 -2
  61. package/src/modules/sync/utils.ts +182 -17
  62. package/src/otel/index.ts +127 -0
  63. package/src/services/database/cache-engine.ts +160 -0
  64. package/src/services/database/database.ts +11 -11
  65. package/src/services/database/engine-factory.ts +33 -0
  66. package/src/services/database/events/index.ts +2 -1
  67. package/src/services/database/index.ts +6 -0
  68. package/src/services/database/local-migrator.ts +28 -27
  69. package/src/services/database/local.test.ts +64 -0
  70. package/src/services/database/local.ts +478 -67
  71. package/src/services/database/plan-render.test.ts +159 -0
  72. package/src/services/database/plan-render.ts +108 -0
  73. package/src/services/database/relation-resolver.test.ts +413 -0
  74. package/src/services/database/relation-resolver.ts +0 -0
  75. package/src/services/database/remote.ts +13 -13
  76. package/src/services/database/sqlite-cache-engine.test.ts +464 -0
  77. package/src/services/database/sqlite-cache-engine.ts +1154 -0
  78. package/src/services/database/sqlite-open.test.ts +150 -0
  79. package/src/services/database/sqlite-open.ts +164 -0
  80. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  81. package/src/services/database/sqlite-plan-sql.ts +106 -0
  82. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  83. package/src/services/database/sqlite-select.test.ts +246 -0
  84. package/src/services/database/sqlite-select.ts +113 -0
  85. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  86. package/src/services/database/sqlite-transport.ts +219 -0
  87. package/src/services/database/sqlite-worker.ts +437 -0
  88. package/src/services/database/surql-translate.ts +291 -0
  89. package/src/services/database/surreal-cache-engine.ts +141 -0
  90. package/src/services/logger/index.ts +6 -109
  91. package/src/services/persistence/localstorage.ts +2 -2
  92. package/src/services/persistence/resilient.ts +11 -4
  93. package/src/services/persistence/surrealdb.ts +10 -10
  94. package/src/services/stream-processor/index.ts +444 -52
  95. package/src/services/stream-processor/permissions.test.ts +47 -0
  96. package/src/services/stream-processor/permissions.ts +53 -0
  97. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  98. package/src/services/stream-processor/stream-processor.reset.test.ts +216 -0
  99. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  100. package/src/services/stream-processor/wasm-types.ts +23 -2
  101. package/src/services/tabs/broker-client.ts +283 -0
  102. package/src/services/tabs/broker.test.ts +278 -0
  103. package/src/services/tabs/coordinator.test.ts +192 -0
  104. package/src/services/tabs/coordinator.ts +567 -0
  105. package/src/services/tabs/fake-ports.fixture.ts +70 -0
  106. package/src/services/tabs/leader-locks.ts +75 -0
  107. package/src/services/tabs/protocol.ts +239 -0
  108. package/src/services/tabs/support.ts +36 -0
  109. package/src/services/tabs/tabs-broker-worker.ts +581 -0
  110. package/src/sp00ky.auth-order.test.ts +92 -0
  111. package/src/sp00ky.init-query.test.ts +183 -0
  112. package/src/sp00ky.ts +1225 -0
  113. package/src/types.ts +342 -15
  114. package/src/utils/error-classification.test.ts +44 -0
  115. package/src/utils/error-classification.ts +7 -0
  116. package/src/utils/index.ts +35 -13
  117. package/src/utils/parser.ts +3 -2
  118. package/src/utils/semver.test.ts +32 -0
  119. package/src/utils/semver.ts +30 -0
  120. package/src/utils/surql.ts +30 -18
  121. package/src/utils/withRetry.test.ts +1 -1
  122. package/tsdown.config.ts +86 -1
  123. package/src/spooky.ts +0 -395
@@ -0,0 +1,291 @@
1
+ import type { WhereNode } from '@spooky-sync/query-builder';
2
+ import type { OrderBy, Row } from './cache-engine';
3
+ import { stableKey } from './relation-resolver';
4
+
5
+ /**
6
+ * Translate the BOUNDED set of SurrealQL statements the client actually emits
7
+ * into engine-neutral operations the SQLite backend executes. This is NOT a
8
+ * general SurrealQL parser — it recognizes exactly the shapes produced by the
9
+ * `surql` helper and the handful of literal queries in the codebase. Anything
10
+ * unrecognized throws (with the offending SQL) so gaps surface loudly during a
11
+ * trial rather than silently returning wrong data.
12
+ *
13
+ * The arbitrary user SELECT (`config.surql`, with nested `.related()`
14
+ * subqueries) is intentionally NOT handled here — it flows through
15
+ * `engine.select(plan)` instead, so the translator never faces an unbounded
16
+ * query shape.
17
+ */
18
+
19
+ export type SqlOp =
20
+ | { kind: 'getById'; id: unknown; select?: string[]; value?: string }
21
+ | { kind: 'selectByIds'; ids: unknown[]; select?: string[]; orderBy?: OrderBy; value?: string }
22
+ | { kind: 'selectTable'; table: string; where?: WhereNode[]; orderBy?: OrderBy; select?: string[]; value?: string }
23
+ | { kind: 'upsert'; id: unknown; data: Row; mode: 'replace' | 'merge' }
24
+ | { kind: 'updateSet'; id: unknown; sets: SetClause[]; returnNone: boolean }
25
+ | { kind: 'delete'; id: unknown }
26
+ | { kind: 'deleteAll'; table: string }
27
+ | { kind: 'let'; var: string; inner: SqlOp }
28
+ | { kind: 'return'; entries: { key: string; var: string }[] }
29
+ | { kind: 'noop' };
30
+
31
+ export interface SetClause {
32
+ path: string;
33
+ op: '=' | '+=' | '-=';
34
+ value: unknown;
35
+ }
36
+
37
+ export interface TranslatedQuery {
38
+ /** True for a `BEGIN TRANSACTION … COMMIT` block — the engine prepends a
39
+ * `null` begin-result so `surql.seal`'s `idx+1` extraction still lines up. */
40
+ transaction: boolean;
41
+ ops: SqlOp[];
42
+ }
43
+
44
+ const rid = (v: unknown): unknown => v;
45
+
46
+ /** Table name from a record id value (`table:id` string or RecordId). */
47
+ export function tableOf(id: unknown): string {
48
+ return stableKey(id).split(':')[0];
49
+ }
50
+
51
+ export function translateSurql(sql: string, vars: Record<string, unknown>): TranslatedQuery {
52
+ const trimmed = sql.trim().replace(/;\s*$/, '');
53
+
54
+ if (/^BEGIN\s+TRANSACTION/i.test(trimmed)) {
55
+ const inner = trimmed
56
+ .replace(/^BEGIN\s+TRANSACTION\s*;?/i, '')
57
+ .replace(/;?\s*COMMIT\s+TRANSACTION\s*$/i, '');
58
+ const ops = splitStatements(inner).map((s) => translateStatement(s, vars));
59
+ return { transaction: true, ops };
60
+ }
61
+
62
+ // A plain multi-statement string (e.g. `DEFINE DATABASE x; USE DB x`) — split
63
+ // and translate each. Single statement is just the one-element case.
64
+ const parts = splitStatements(trimmed);
65
+ return { transaction: false, ops: parts.map((s) => translateStatement(s, vars)) };
66
+ }
67
+
68
+ function splitStatements(block: string): string[] {
69
+ // Statements in the client's tx blocks never contain a bare `;` inside a
70
+ // string/paren, so a simple split is sufficient for this bounded vocabulary.
71
+ return block
72
+ .split(';')
73
+ .map((s) => s.trim())
74
+ .filter(Boolean);
75
+ }
76
+
77
+ function translateStatement(stmt: string, vars: Record<string, unknown>): SqlOp {
78
+ const s = stmt.trim();
79
+
80
+ // LET $var = ( <inner statement> ) — bind the inner result into query scope.
81
+ let mLet = /^LET\s+\$(\w+)\s*=\s*\(([\s\S]+)\)$/i.exec(s);
82
+ if (mLet) {
83
+ return { kind: 'let', var: mLet[1], inner: translateStatement(mLet[2].trim(), vars) };
84
+ }
85
+
86
+ // RETURN { key: $var, ... } — build an object from scope/vars.
87
+ let mRet = /^RETURN\s+\{([\s\S]+)\}$/i.exec(s);
88
+ if (mRet) {
89
+ const entries = splitTopLevel(mRet[1], ',').map((pair) => {
90
+ const c = pair.indexOf(':');
91
+ const key = pair.slice(0, c).trim();
92
+ const v = pair.slice(c + 1).trim();
93
+ return { key, var: v.startsWith('$') ? v.slice(1) : v };
94
+ });
95
+ return { kind: 'return', entries };
96
+ }
97
+
98
+ // ---- schema / session DDL: no-ops on a schemaless engine --------------
99
+ // SQLite creates tables lazily and has no namespaces/DB DDL, so DEFINE /
100
+ // REMOVE / USE / INFO / RETURN statements are safely ignored.
101
+ if (/^(DEFINE|REMOVE|USE|INFO|RETURN|CANCEL|COMMIT|BEGIN)\b/i.test(s)) {
102
+ return { kind: 'noop' };
103
+ }
104
+
105
+ // ---- writes -----------------------------------------------------------
106
+ let m =
107
+ /^CREATE\s+ONLY\s+\$(\w+)\s+CONTENT\s+\$(\w+)$/i.exec(s) ||
108
+ /^UPSERT\s+ONLY\s+\$(\w+)\s+REPLACE\s+\$(\w+)$/i.exec(s);
109
+ if (m) {
110
+ return { kind: 'upsert', id: rid(vars[m[1]]), data: asRow(vars[m[2]]), mode: 'replace' };
111
+ }
112
+
113
+ m =
114
+ /^UPSERT\s+ONLY\s+\$(\w+)\s+MERGE\s+\$(\w+)$/i.exec(s) ||
115
+ /^UPDATE\s+ONLY\s+\$(\w+)\s+MERGE\s+\$(\w+)$/i.exec(s);
116
+ if (m) {
117
+ return { kind: 'upsert', id: rid(vars[m[1]]), data: asRow(vars[m[2]]), mode: 'merge' };
118
+ }
119
+
120
+ // CREATE ONLY $id SET a = ..., b = ... (createSet / createMutation)
121
+ m = /^CREATE\s+ONLY\s+\$(\w+)\s+SET\s+(.+)$/i.exec(s);
122
+ if (m) {
123
+ const data: Row = {};
124
+ for (const { path, value } of parseSetClauses(m[2], vars)) setPath(data, path, value);
125
+ return { kind: 'upsert', id: rid(vars[m[1]]), data, mode: 'replace' };
126
+ }
127
+
128
+ // UPDATE $id SET a.b = $x, c = $y [RETURN NONE]
129
+ m = /^UPDATE\s+\$(\w+)\s+SET\s+(.+?)(\s+RETURN\s+NONE)?$/i.exec(s);
130
+ if (m) {
131
+ return {
132
+ kind: 'updateSet',
133
+ id: rid(vars[m[1]]),
134
+ sets: parseSetClauses(m[2], vars),
135
+ returnNone: !!m[3],
136
+ };
137
+ }
138
+
139
+ m = /^DELETE\s+\$(\w+)$/i.exec(s);
140
+ if (m) return { kind: 'delete', id: rid(vars[m[1]]) };
141
+
142
+ m = /^DELETE\s+([A-Za-z_]\w*)$/i.exec(s); // DELETE <table>
143
+ if (m) return { kind: 'deleteAll', table: m[1] };
144
+
145
+ // ---- reads ------------------------------------------------------------
146
+ // SELECT [VALUE] <proj> FROM ONLY $id
147
+ m = /^SELECT\s+(VALUE\s+)?(.+?)\s+FROM\s+ONLY\s+\$(\w+)$/i.exec(s);
148
+ if (m) {
149
+ const value = m[1] ? m[2].trim() : undefined;
150
+ return { kind: 'getById', id: rid(vars[m[3]]), select: projFields(m[2], !!m[1]), value };
151
+ }
152
+
153
+ // SELECT [VALUE] <proj> FROM $arrayParam
154
+ m = /^SELECT\s+(VALUE\s+)?(.+?)\s+FROM\s+\$(\w+)$/i.exec(s);
155
+ if (m) {
156
+ const value = m[1] ? m[2].trim() : undefined;
157
+ return {
158
+ kind: 'selectByIds',
159
+ ids: (vars[m[3]] as unknown[]) ?? [],
160
+ select: projFields(m[2], !!m[1]),
161
+ value,
162
+ };
163
+ }
164
+
165
+ // SELECT <proj> FROM <table> [WHERE ...] [ORDER BY ...]
166
+ m = /^SELECT\s+(VALUE\s+)?(.+?)\s+FROM\s+([A-Za-z_]\w*)(?:\s+WHERE\s+(.+?))?(?:\s+ORDER\s+BY\s+(.+?))?$/i.exec(
167
+ s
168
+ );
169
+ if (m) {
170
+ return {
171
+ kind: 'selectTable',
172
+ table: m[3],
173
+ where: m[4] ? parseWhere(m[4], vars) : undefined,
174
+ orderBy: m[5] ? parseOrderBy(m[5]) : undefined,
175
+ select: projFields(m[2], !!m[1]),
176
+ value: m[1] ? m[2].trim() : undefined,
177
+ };
178
+ }
179
+
180
+ throw new Error(`SqliteCacheEngine: unsupported SurrealQL for translation: ${stmt}`);
181
+ }
182
+
183
+ // ==================== clause parsers ====================
184
+
185
+ function projFields(proj: string, isValue: boolean): string[] | undefined {
186
+ const p = proj.trim();
187
+ if (isValue) return undefined; // VALUE returns a scalar, no projection object
188
+ if (p === '*') return undefined;
189
+ return p.split(',').map((f) => f.trim());
190
+ }
191
+
192
+ function asRow(v: unknown): Row {
193
+ return (v && typeof v === 'object' ? v : {}) as Row;
194
+ }
195
+
196
+ /** Parse `a = $x, b.c = 'lit', _00_rv += 1` into path/op/value triples. */
197
+ function parseSetClauses(clause: string, vars: Record<string, unknown>): SetClause[] {
198
+ return splitTopLevel(clause, ',').map((part) => {
199
+ const m = /^(.+?)\s*(\+=|-=|=)\s*([\s\S]+)$/.exec(part.trim());
200
+ if (!m) throw new Error(`SqliteCacheEngine: cannot parse SET clause: ${part}`);
201
+ return { path: m[1].trim(), op: m[2] as SetClause['op'], value: literalOrVar(m[3], vars) };
202
+ });
203
+ }
204
+
205
+ function literalOrVar(token: string, vars: Record<string, unknown>): unknown {
206
+ const t = token.trim();
207
+ if (t.startsWith('$')) return vars[t.slice(1)];
208
+ if (/^'.*'$/.test(t) || /^".*"$/.test(t)) return t.slice(1, -1);
209
+ if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t);
210
+ if (t === 'true') return true;
211
+ if (t === 'false') return false;
212
+ if (t === 'NONE' || t === 'NULL' || t === 'null') return null;
213
+ return t;
214
+ }
215
+
216
+ function parseWhere(clause: string, vars: Record<string, unknown>): WhereNode[] {
217
+ // Only simple AND-of-equality/comparison is emitted by the client's raw
218
+ // queries; OR/nested go through plan-based select().
219
+ return splitTopLevel(clause, 'AND').map((cond) => {
220
+ const m = /^(\S+)\s*(=|!=|>=|<=|>|<)\s*(.+)$/.exec(cond.trim());
221
+ if (!m) throw new Error(`SqliteCacheEngine: cannot parse WHERE condition: ${cond}`);
222
+ return { field: m[1], op: m[2] as WhereComparisonOp, value: literalOrVar(m[3], vars) };
223
+ });
224
+ }
225
+
226
+ type WhereComparisonOp = '=' | '!=' | '>=' | '<=' | '>' | '<';
227
+
228
+ function parseOrderBy(clause: string): OrderBy {
229
+ return clause.split(',').map((c) => {
230
+ const [f, dir] = c.trim().split(/\s+/);
231
+ return [f, (dir ?? 'asc').toLowerCase() === 'desc' ? 'desc' : 'asc'];
232
+ });
233
+ }
234
+
235
+ /** Split on a top-level separator, ignoring parens/quotes (bounded inputs). */
236
+ function splitTopLevel(input: string, sep: string): string[] {
237
+ const out: string[] = [];
238
+ let depth = 0;
239
+ let inStr: string | null = null;
240
+ let cur = '';
241
+ const isWord = /[A-Za-z]/.test(sep);
242
+ for (let i = 0; i < input.length; i++) {
243
+ const ch = input[i];
244
+ if (inStr) {
245
+ cur += ch;
246
+ if (ch === inStr) inStr = null;
247
+ continue;
248
+ }
249
+ if (ch === "'" || ch === '"') {
250
+ inStr = ch;
251
+ cur += ch;
252
+ continue;
253
+ }
254
+ if (ch === '(') depth++;
255
+ if (ch === ')') depth--;
256
+ const matches = isWord
257
+ ? depth === 0 && input.slice(i, i + sep.length).toUpperCase() === sep && /\s/.test(input[i - 1] ?? ' ')
258
+ : depth === 0 && ch === sep;
259
+ if (matches) {
260
+ out.push(cur.trim());
261
+ cur = '';
262
+ i += sep.length - 1;
263
+ continue;
264
+ }
265
+ cur += ch;
266
+ }
267
+ if (cur.trim()) out.push(cur.trim());
268
+ return out;
269
+ }
270
+
271
+ /** Read a possibly-dotted path (`a.b.c`) from an object. */
272
+ export function getPath(obj: Row, path: string): unknown {
273
+ let cur: unknown = obj;
274
+ for (const k of path.split('.')) {
275
+ if (cur == null || typeof cur !== 'object') return undefined;
276
+ cur = (cur as Row)[k];
277
+ }
278
+ return cur;
279
+ }
280
+
281
+ /** Set a possibly-dotted path (`a.b.c`) on an object. */
282
+ export function setPath(obj: Row, path: string, value: unknown): void {
283
+ const parts = path.split('.');
284
+ let cur: Row = obj;
285
+ for (let i = 0; i < parts.length - 1; i++) {
286
+ const k = parts[i];
287
+ if (typeof cur[k] !== 'object' || cur[k] === null) cur[k] = {};
288
+ cur = cur[k] as Row;
289
+ }
290
+ cur[parts[parts.length - 1]] = value;
291
+ }
@@ -0,0 +1,141 @@
1
+ import type { QueryPlan } from '@spooky-sync/query-builder';
2
+ import { LocalDatabaseService } from './local';
3
+ import { resolveRelations } from './relation-resolver';
4
+ import {
5
+ renderBaseSelectSurql,
6
+ renderRelationFetchSurql,
7
+ } from './plan-render';
8
+ import type {
9
+ EngineTx,
10
+ Id,
11
+ LocalCacheEngine,
12
+ OrderBy,
13
+ RelationFetch,
14
+ Row,
15
+ } from './cache-engine';
16
+ import { stableKey } from './relation-resolver';
17
+ import { surql } from '../../utils/surql';
18
+ import { RecordId } from 'surrealdb';
19
+
20
+ /**
21
+ * Default local cache backend: the in-browser SurrealDB-WASM store. Implemented
22
+ * as a subclass of {@link LocalDatabaseService} so it remains a 100% drop-in for
23
+ * every existing `this.local.query(...)` / `execute` / `switchStore` / `epoch`
24
+ * call site (zero behavior change), while adding the engine-neutral verb surface
25
+ * (`select`/`selectByIds`/`getById`/CRUD) used by the pluggable path.
26
+ *
27
+ * Relations are resolved with the SAME shared {@link resolveRelations} as the
28
+ * SQLite backend, so the two engines decompose `.related()` identically.
29
+ */
30
+ export class SurrealCacheEngine extends LocalDatabaseService implements LocalCacheEngine {
31
+ /** SurrealDB needs its SurrealQL schema provisioned locally. */
32
+ readonly usesSurqlSchema = true;
33
+
34
+ readonly engineKind = 'surrealdb' as const;
35
+
36
+ /** {@link LocalCacheEngine} alias for {@link LocalDatabaseService.switchStore}. */
37
+ switchBucket(bucketId: string): Promise<void> {
38
+ return this.switchStore(bucketId);
39
+ }
40
+
41
+ async fetchRelation(req: RelationFetch): Promise<Row[]> {
42
+ const { sql, vars } = renderRelationFetchSurql(req);
43
+ const [rows] = await this.query<[Row[]]>(sql, vars);
44
+ return rows ?? [];
45
+ }
46
+
47
+ async select(plan: QueryPlan, params: Record<string, unknown> = {}): Promise<Row[]> {
48
+ // Window materialization: base rows are exactly `plan.ids`, ordered.
49
+ if (plan.ids) {
50
+ const result = await this.selectByIds(plan.table, plan.ids, {
51
+ select: plan.select,
52
+ orderBy: plan.orderBy,
53
+ });
54
+ await resolveRelations(result, plan.relations, this);
55
+ return result;
56
+ }
57
+ const { sql, vars } = renderBaseSelectSurql(plan, params);
58
+ const [rows] = await this.query<[Row[]]>(sql, vars);
59
+ const result = rows ?? [];
60
+ await resolveRelations(result, plan.relations, this);
61
+ return result;
62
+ }
63
+
64
+ async selectByIds(
65
+ table: string,
66
+ ids: Id[],
67
+ opts?: { select?: string[]; orderBy?: OrderBy }
68
+ ): Promise<Row[]> {
69
+ if (ids.length === 0) return [];
70
+ const projection =
71
+ opts?.select && opts.select.length > 0 ? ['id', ...opts.select].join(', ') : '*';
72
+ let sql = `SELECT ${projection} FROM $__ids`;
73
+ if (opts?.orderBy && opts.orderBy.length > 0) {
74
+ sql += ` ORDER BY ${opts.orderBy.map(([f, d]) => `${f} ${d}`).join(', ')}`;
75
+ }
76
+ const [rows] = await this.query<[Row[]]>(`${sql};`, { __ids: ids });
77
+ const result = rows ?? [];
78
+ // Preserve caller's id order when no explicit ORDER BY (SurrealDB does not
79
+ // guarantee `FROM $ids` order).
80
+ if (!opts?.orderBy || opts.orderBy.length === 0) {
81
+ const pos = new Map(ids.map((id, i) => [stableKey(id), i]));
82
+ result.sort(
83
+ (a, b) => (pos.get(stableKey(a.id)) ?? 0) - (pos.get(stableKey(b.id)) ?? 0)
84
+ );
85
+ }
86
+ return result;
87
+ }
88
+
89
+ /**
90
+ * Coerce the contract's `Id` (a RecordId, a stable `table:id` string, or a
91
+ * bare id + the verb's `table` param) to a real RecordId. SurrealDB binds
92
+ * `$__id` verbatim: a plain string makes `FROM ONLY $__id` "select" the
93
+ * string itself (a truthy non-row) and `UPSERT $__id` an InternalError, so
94
+ * string ids silently broke every id-verb on this engine.
95
+ */
96
+ private toRecordId(table: string, id: Id): unknown {
97
+ if (typeof id !== 'string') return id;
98
+ const raw = id.startsWith(`${table}:`) ? id.slice(table.length + 1) : id;
99
+ return new RecordId(table, raw);
100
+ }
101
+
102
+ async getById(table: string, id: Id): Promise<Row | null> {
103
+ const [row] = await this.query<[Row | null]>('SELECT * FROM ONLY $__id;', {
104
+ __id: this.toRecordId(table, id),
105
+ });
106
+ // `FROM ONLY <non-record>` echoes the value back; only a real row counts.
107
+ return row && typeof row === 'object' ? row : null;
108
+ }
109
+
110
+ async upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void> {
111
+ const sql = mode === 'merge' ? surql.upsertMerge('__id', '__data') : surql.upsert('__id', '__data');
112
+ await this.query(surql.seal(sql), { __id: this.toRecordId(table, id), __data: data });
113
+ }
114
+
115
+ async patch(table: string, id: Id, patches: unknown[]): Promise<void> {
116
+ await this.query(surql.seal('UPDATE ONLY $__id PATCH $__patches'), {
117
+ __id: this.toRecordId(table, id),
118
+ __patches: patches,
119
+ });
120
+ }
121
+
122
+ async delete(table: string, id: Id): Promise<void> {
123
+ await this.query(surql.seal(surql.delete('__id')), { __id: this.toRecordId(table, id) });
124
+ }
125
+
126
+ /**
127
+ * Serialized (not strictly atomic) transaction: verbs run in order on the
128
+ * same serialized query queue. The SurrealDB-WASM store already funnels every
129
+ * `query()` through one queue, so these never interleave with other work;
130
+ * true multi-statement atomicity is not required by the current call sites
131
+ * (single-record CRDT / mutation writes).
132
+ */
133
+ async transaction<T>(fn: (tx: EngineTx) => Promise<T>): Promise<T> {
134
+ const tx: EngineTx = {
135
+ upsert: (t, id, data, mode) => this.upsert(t, id, data, mode),
136
+ patch: (t, id, patches) => this.patch(t, id, patches),
137
+ delete: (t, id) => this.delete(t, id),
138
+ };
139
+ return fn(tx);
140
+ }
141
+ }
@@ -1,122 +1,19 @@
1
- import pino, { Level, type Logger as PinoLogger, type LoggerOptions } from 'pino';
1
+ import pino, { type Level, type Logger as PinoLogger, type LoggerOptions } from 'pino';
2
+ import type { PinoTransmit } from '../../types';
2
3
 
3
4
  export type Logger = PinoLogger;
4
5
 
5
- // Map pino levels to OTEL severity numbers
6
- // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/data-model.md#severity-fields
7
- function mapLevelToSeverityNumber(level: string): number {
8
- switch (level) {
9
- case 'trace':
10
- return 1;
11
- case 'debug':
12
- return 5;
13
- case 'info':
14
- return 9;
15
- case 'warn':
16
- return 13;
17
- case 'error':
18
- return 17;
19
- case 'fatal':
20
- return 21;
21
- default:
22
- return 9;
23
- }
24
- }
25
-
26
- async function loadOtelModules(otelEndpoint: string) {
27
- const [{ LoggerProvider, BatchLogRecordProcessor }, { OTLPLogExporter }, { resourceFromAttributes }, { ATTR_SERVICE_NAME }] =
28
- await Promise.all([
29
- import('@opentelemetry/sdk-logs'),
30
- import('@opentelemetry/exporter-logs-otlp-proto'),
31
- import('@opentelemetry/resources'),
32
- import('@opentelemetry/semantic-conventions'),
33
- ]);
34
-
35
- const resource = resourceFromAttributes({
36
- [ATTR_SERVICE_NAME]: 'spooky-client',
37
- });
38
-
39
- const exporter = new OTLPLogExporter({
40
- url: otelEndpoint,
41
- });
42
-
43
- const loggerProvider = new LoggerProvider({
44
- resource,
45
- processors: [new BatchLogRecordProcessor(exporter)],
46
- });
47
-
48
- const otelLoggerCache: Record<string, ReturnType<typeof loggerProvider.getLogger>> = {};
49
-
50
- return (category: string) => {
51
- if (!otelLoggerCache[category]) {
52
- otelLoggerCache[category] = loggerProvider.getLogger(category);
53
- }
54
- return otelLoggerCache[category];
55
- };
56
- }
57
-
58
- export function createLogger(level: Level = 'info', otelEndpoint?: string): Logger {
6
+ export function createLogger(level: Level = 'info', transmit?: PinoTransmit): Logger {
59
7
  const browserConfig: LoggerOptions['browser'] = {
60
8
  asObject: true,
61
9
  write: (o: any) => {
10
+ // oxlint-disable-next-line no-console
62
11
  console.log(JSON.stringify(o));
63
12
  },
64
13
  };
65
14
 
66
- if (otelEndpoint) {
67
- // Start loading OTel modules eagerly (don't await — we're synchronous)
68
- const otelReady = loadOtelModules(otelEndpoint);
69
-
70
- browserConfig.transmit = {
71
- level: level,
72
- send: (levelLabel: string, logEvent: any) => {
73
- otelReady.then((getOtelLogger) => {
74
- try {
75
- const messages = [...logEvent.messages];
76
- const severityNumber = mapLevelToSeverityNumber(levelLabel);
77
-
78
- // Construct the message body
79
- let body = '';
80
- const msg = messages.pop();
81
-
82
- if (typeof msg === 'string') {
83
- body = msg;
84
- } else if (msg) {
85
- body = JSON.stringify(msg);
86
- }
87
-
88
- let category = 'spooky-client::unknown';
89
-
90
- const attributes = {};
91
- for (const msg of messages) {
92
- if (typeof msg === 'object') {
93
- if (msg.Category) {
94
- category = msg.Category;
95
- delete msg.Category;
96
- }
97
- Object.assign(attributes, msg);
98
- }
99
- }
100
-
101
- // Emit to OTEL SDK
102
- getOtelLogger(category).emit({
103
- severityNumber: severityNumber,
104
- severityText: levelLabel.toUpperCase(),
105
- body: body,
106
- attributes: {
107
- ...logEvent.bindings[0],
108
- ...attributes,
109
- },
110
- timestamp: new Date(logEvent.ts),
111
- });
112
- } catch (e) {
113
- console.warn('Failed to transmit log to OTEL endpoint', e);
114
- }
115
- }).catch((e) => {
116
- console.warn('Failed to load OpenTelemetry modules', e);
117
- });
118
- },
119
- };
15
+ if (transmit) {
16
+ browserConfig.transmit = transmit;
120
17
  }
121
18
 
122
19
  return pino({
@@ -1,5 +1,5 @@
1
- import { Logger } from 'pino';
2
- import { PersistenceClient } from '../../types';
1
+ import type { Logger } from 'pino';
2
+ import type { PersistenceClient } from '../../types';
3
3
 
4
4
  export class LocalStoragePersistenceClient implements PersistenceClient {
5
5
  private logger: Logger;
@@ -1,5 +1,5 @@
1
- import { Logger } from 'pino';
2
- import { PersistenceClient } from '../../types';
1
+ import type { Logger } from 'pino';
2
+ import type { PersistenceClient } from '../../types';
3
3
 
4
4
  export class ResilientPersistenceClient implements PersistenceClient {
5
5
  private logger: Logger;
@@ -20,10 +20,17 @@ export class ResilientPersistenceClient implements PersistenceClient {
20
20
  return await this.inner.get<T>(key);
21
21
  } catch (e) {
22
22
  this.logger.warn(
23
- { key, error: e, Category: 'spooky-client::ResilientPersistenceClient::get' },
23
+ { key, error: e, Category: 'sp00ky-client::ResilientPersistenceClient::get' },
24
24
  'Persistence read failed, dropping key'
25
25
  );
26
- await this.inner.remove(key).catch(() => {});
26
+ // Best-effort cleanup of the corrupt key; if removal also fails, the key
27
+ // just gets dropped again on the next failed read, so the failure is safe.
28
+ await this.inner.remove(key).catch((removeErr) => {
29
+ this.logger.debug(
30
+ { key, error: removeErr, Category: 'sp00ky-client::ResilientPersistenceClient::get' },
31
+ 'Failed to drop corrupt persistence key'
32
+ );
33
+ });
27
34
  return null;
28
35
  }
29
36
  }
@@ -1,13 +1,13 @@
1
- import { PersistenceClient } from '../../types';
1
+ import type { PersistenceClient } from '../../types';
2
2
  import { parseRecordIdString, surql } from '../../utils/index';
3
- import { Logger } from 'pino';
4
- import { AbstractDatabaseService } from '../database/database';
3
+ import type { Logger } from 'pino';
4
+ import type { LocalStore } from '../database/cache-engine';
5
5
 
6
6
  export class SurrealDBPersistenceClient implements PersistenceClient {
7
7
  private logger: Logger;
8
8
 
9
9
  constructor(
10
- private db: AbstractDatabaseService,
10
+ private db: LocalStore,
11
11
  logger: Logger
12
12
  ) {
13
13
  this.logger = logger.child({ service: 'PersistenceClient:SurrealDb' });
@@ -15,11 +15,11 @@ export class SurrealDBPersistenceClient implements PersistenceClient {
15
15
 
16
16
  async set<T>(key: string, val: T) {
17
17
  try {
18
- const id = parseRecordIdString(`_spooky_kv:${key}`);
18
+ const id = parseRecordIdString(`_00_kv:${key}`);
19
19
  await this.db.query(surql.seal(surql.upsert('id', 'data')), { id, data: { val } });
20
20
  } catch (error) {
21
21
  this.logger.error(
22
- { error, Category: 'spooky-client::SurrealDBPersistenceClient::set' },
22
+ { error, Category: 'sp00ky-client::SurrealDBPersistenceClient::set' },
23
23
  'Failed to set KV'
24
24
  );
25
25
  throw error;
@@ -28,7 +28,7 @@ export class SurrealDBPersistenceClient implements PersistenceClient {
28
28
 
29
29
  async get<T>(key: string) {
30
30
  try {
31
- const id = parseRecordIdString(`_spooky_kv:${key}`);
31
+ const id = parseRecordIdString(`_00_kv:${key}`);
32
32
  const [result] = await this.db.query<[{ val: T }]>(
33
33
  surql.seal(surql.selectById('id', ['val'])),
34
34
  {
@@ -41,7 +41,7 @@ export class SurrealDBPersistenceClient implements PersistenceClient {
41
41
  return result.val;
42
42
  } catch (error) {
43
43
  this.logger.warn(
44
- { error, Category: 'spooky-client::SurrealDBPersistenceClient::get' },
44
+ { error, Category: 'sp00ky-client::SurrealDBPersistenceClient::get' },
45
45
  'Failed to get KV'
46
46
  );
47
47
  return null;
@@ -50,11 +50,11 @@ export class SurrealDBPersistenceClient implements PersistenceClient {
50
50
 
51
51
  async remove(key: string) {
52
52
  try {
53
- const id = parseRecordIdString(`_spooky_kv:${key}`);
53
+ const id = parseRecordIdString(`_00_kv:${key}`);
54
54
  await this.db.query(surql.seal(surql.delete('id')), { id });
55
55
  } catch (err) {
56
56
  this.logger.info(
57
- { err, Category: 'spooky-client::SurrealDBPersistenceClient::remove' },
57
+ { err, Category: 'sp00ky-client::SurrealDBPersistenceClient::remove' },
58
58
  'Failed to delete KV'
59
59
  );
60
60
  }