@spooky-sync/core 0.0.1-canary.21 → 0.0.1-canary.211

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 (163) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2514 -58
  3. package/dist/index.js +12561 -2449
  4. package/dist/otel/index.d.ts +2 -2
  5. package/dist/otel/index.js +6 -6
  6. package/dist/sqlite-open.js +303 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +439 -0
  9. package/dist/tabs-broker-worker.d.ts +8 -0
  10. package/dist/tabs-broker-worker.js +472 -0
  11. package/dist/types.d.ts +751 -11
  12. package/package.json +11 -7
  13. package/scripts/check-broker-bundle.mjs +33 -0
  14. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  15. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  16. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  17. package/src/bucket-blurhash.test.ts +148 -0
  18. package/src/build-globals.d.ts +12 -0
  19. package/src/events/events.test.ts +2 -1
  20. package/src/events/index.ts +3 -0
  21. package/src/index.ts +36 -2
  22. package/src/modules/app-release/index.test.ts +125 -0
  23. package/src/modules/app-release/index.ts +201 -0
  24. package/src/modules/auth/auth.local-first.test.ts +101 -0
  25. package/src/modules/auth/events/index.ts +2 -1
  26. package/src/modules/auth/index.ts +127 -24
  27. package/src/modules/cache/cache.relay.test.ts +95 -0
  28. package/src/modules/cache/index.ts +163 -43
  29. package/src/modules/cache/types.ts +2 -2
  30. package/src/modules/crdt/crdt-field.ts +294 -0
  31. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  32. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  33. package/src/modules/crdt/index.ts +463 -0
  34. package/src/modules/crdt/loro-loader.ts +25 -0
  35. package/src/modules/data/data.hydration.test.ts +142 -0
  36. package/src/modules/data/data.membership.test.ts +523 -0
  37. package/src/modules/data/data.notify-table.test.ts +41 -0
  38. package/src/modules/data/data.pending-ids.test.ts +199 -0
  39. package/src/modules/data/data.rebind.test.ts +170 -0
  40. package/src/modules/data/data.rematerialize.test.ts +114 -0
  41. package/src/modules/data/data.run.test.ts +113 -0
  42. package/src/modules/data/data.settled-writes.test.ts +206 -0
  43. package/src/modules/data/data.status.test.ts +249 -0
  44. package/src/modules/data/id-set-plan.test.ts +122 -0
  45. package/src/modules/data/index.ts +1815 -151
  46. package/src/modules/data/mutation-id.test.ts +25 -0
  47. package/src/modules/data/mutation-id.ts +35 -0
  48. package/src/modules/data/window-query.test.ts +52 -0
  49. package/src/modules/data/window-query.ts +194 -0
  50. package/src/modules/devtools/flags.ts +349 -0
  51. package/src/modules/devtools/index.ts +450 -46
  52. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  53. package/src/modules/devtools/state-shape.test.ts +146 -0
  54. package/src/modules/devtools/storage-info.test.ts +79 -0
  55. package/src/modules/devtools/storage-info.ts +168 -0
  56. package/src/modules/devtools/versions.test.ts +74 -0
  57. package/src/modules/devtools/versions.ts +110 -0
  58. package/src/modules/feature-flag/index.test.ts +251 -0
  59. package/src/modules/feature-flag/index.ts +308 -0
  60. package/src/modules/ref-tables.test.ts +91 -0
  61. package/src/modules/ref-tables.ts +88 -0
  62. package/src/modules/sync/engine.ts +164 -82
  63. package/src/modules/sync/events/index.ts +9 -2
  64. package/src/modules/sync/queue/queue-down.test.ts +180 -0
  65. package/src/modules/sync/queue/queue-down.ts +80 -13
  66. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  67. package/src/modules/sync/queue/queue-up.ts +241 -57
  68. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  69. package/src/modules/sync/scheduler.retry.test.ts +237 -0
  70. package/src/modules/sync/scheduler.ts +215 -13
  71. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  72. package/src/modules/sync/sync.health.test.ts +149 -0
  73. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  74. package/src/modules/sync/sync.live-removal.test.ts +175 -0
  75. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  76. package/src/modules/sync/sync.subquery.test.ts +82 -0
  77. package/src/modules/sync/sync.tabs.test.ts +249 -0
  78. package/src/modules/sync/sync.ts +1726 -99
  79. package/src/modules/sync/utils.test.ts +269 -2
  80. package/src/modules/sync/utils.ts +201 -17
  81. package/src/otel/index.ts +13 -10
  82. package/src/services/blobs/blob-cache.test.ts +359 -0
  83. package/src/services/blobs/blob-cache.ts +603 -0
  84. package/src/services/blobs/blob-manifest.ts +227 -0
  85. package/src/services/blobs/blob-store.test.ts +77 -0
  86. package/src/services/blobs/blob-store.ts +359 -0
  87. package/src/services/blobs/blob.fixture.ts +90 -0
  88. package/src/services/blobs/index.ts +70 -0
  89. package/src/services/database/cache-engine.ts +193 -0
  90. package/src/services/database/connection-supervisor.test.ts +289 -0
  91. package/src/services/database/connection-supervisor.ts +415 -0
  92. package/src/services/database/database.query-timeout.test.ts +83 -0
  93. package/src/services/database/database.ts +41 -12
  94. package/src/services/database/engine-factory.ts +33 -0
  95. package/src/services/database/errors.ts +34 -0
  96. package/src/services/database/events/index.ts +2 -1
  97. package/src/services/database/index.ts +7 -0
  98. package/src/services/database/local-migrator.ts +30 -27
  99. package/src/services/database/local.test.ts +64 -0
  100. package/src/services/database/local.ts +484 -67
  101. package/src/services/database/plan-render.test.ts +159 -0
  102. package/src/services/database/plan-render.ts +108 -0
  103. package/src/services/database/relation-resolver.test.ts +413 -0
  104. package/src/services/database/relation-resolver.ts +0 -0
  105. package/src/services/database/remote.ts +110 -14
  106. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  107. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  108. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  109. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  110. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  111. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  112. package/src/services/database/sqlite-lock-verify.ts +45 -0
  113. package/src/services/database/sqlite-open.test.ts +150 -0
  114. package/src/services/database/sqlite-open.ts +164 -0
  115. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  116. package/src/services/database/sqlite-plan-sql.ts +138 -0
  117. package/src/services/database/sqlite-projection.test.ts +99 -0
  118. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  119. package/src/services/database/sqlite-select.test.ts +246 -0
  120. package/src/services/database/sqlite-select.ts +131 -0
  121. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  122. package/src/services/database/sqlite-transport.ts +224 -0
  123. package/src/services/database/sqlite-worker.ts +437 -0
  124. package/src/services/database/surql-translate.ts +416 -0
  125. package/src/services/database/surreal-cache-engine.ts +161 -0
  126. package/src/services/logger/index.ts +3 -2
  127. package/src/services/persistence/localstorage.ts +2 -2
  128. package/src/services/persistence/resilient.ts +11 -4
  129. package/src/services/persistence/surrealdb.ts +10 -10
  130. package/src/services/stream-processor/index.ts +796 -84
  131. package/src/services/stream-processor/permissions.test.ts +47 -0
  132. package/src/services/stream-processor/permissions.ts +53 -0
  133. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  134. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  135. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  136. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  137. package/src/services/stream-processor/wasm-types.ts +59 -3
  138. package/src/services/tabs/broker-client.ts +283 -0
  139. package/src/services/tabs/broker.test.ts +327 -0
  140. package/src/services/tabs/coordinator.test.ts +365 -0
  141. package/src/services/tabs/coordinator.ts +633 -0
  142. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  143. package/src/services/tabs/leader-locks.ts +75 -0
  144. package/src/services/tabs/protocol.ts +258 -0
  145. package/src/services/tabs/support.ts +36 -0
  146. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  147. package/src/sp00ky.auth-order.test.ts +92 -0
  148. package/src/sp00ky.init-query.test.ts +183 -0
  149. package/src/sp00ky.local-first.test.ts +60 -0
  150. package/src/sp00ky.ts +1693 -0
  151. package/src/types.ts +528 -13
  152. package/src/utils/blurhash.ts +90 -0
  153. package/src/utils/error-classification.test.ts +44 -0
  154. package/src/utils/error-classification.ts +7 -0
  155. package/src/utils/index.ts +79 -13
  156. package/src/utils/parser.test.ts +49 -120
  157. package/src/utils/parser.ts +32 -2
  158. package/src/utils/semver.test.ts +32 -0
  159. package/src/utils/semver.ts +30 -0
  160. package/src/utils/surql.ts +30 -18
  161. package/src/utils/withRetry.test.ts +1 -1
  162. package/tsdown.config.ts +86 -1
  163. package/src/spooky.ts +0 -395
@@ -1,4 +1,4 @@
1
- import { MutationEventType } from '../types';
1
+ import type { MutationEventType } from '../types';
2
2
 
3
3
  // ==================== TYPES ====================
4
4
 
@@ -34,6 +34,7 @@ export interface SurqlHelper {
34
34
  keyDataVars: ({ key: string; variable: string } | { statement: string } | string)[]
35
35
  ): string;
36
36
  upsert(idVar: string, dataVar: string): string;
37
+ upsertMerge(idVar: string, dataVar: string): string;
37
38
  updateMerge(idVar: string, dataVar: string): string;
38
39
  updateSet(
39
40
  idVar: string,
@@ -90,17 +91,9 @@ export const surql: SurqlHelper = {
90
91
  returnValues: ({ field: string; alias: string } | string)[]
91
92
  ) {
92
93
  return `SELECT ${returnValues
93
- .map((returnValues) =>
94
- typeof returnValues === 'string'
95
- ? returnValues
96
- : `${returnValues.field} as ${returnValues.alias}`
97
- )
94
+ .map((rv) => (typeof rv === 'string' ? rv : `${rv.field} as ${rv.alias}`))
98
95
  .join(',')} FROM ${table} WHERE ${whereVar
99
- .map((whereVar) =>
100
- typeof whereVar === 'string'
101
- ? `${whereVar} = $${whereVar}`
102
- : `${whereVar.field} = $${whereVar.variable}`
103
- )
96
+ .map((wv) => (typeof wv === 'string' ? `${wv} = $${wv}` : `${wv.field} = $${wv.variable}`))
104
97
  .join(' AND ')}`;
105
98
  },
106
99
 
@@ -127,6 +120,14 @@ export const surql: SurqlHelper = {
127
120
  return `UPSERT ONLY $${idVar} REPLACE $${dataVar}`;
128
121
  },
129
122
 
123
+ // Use this for sync-down ingestion: the remote payload omits local-only
124
+ // fields injected by the CLI's local-schema setup (`_00_crdt`,
125
+ // `_00_cursor`), and REPLACE would wipe them on every round-trip and
126
+ // break offline reload of CRDT state.
127
+ upsertMerge(idVar: string, dataVar: string) {
128
+ return `UPSERT ONLY $${idVar} MERGE $${dataVar}`;
129
+ },
130
+
130
131
  updateMerge(idVar: string, dataVar: string) {
131
132
  return `UPDATE ONLY $${idVar} MERGE $${dataVar}`;
132
133
  },
@@ -136,12 +137,12 @@ export const surql: SurqlHelper = {
136
137
  keyDataVar: ({ key: string; variable: string } | { statement: string } | string)[]
137
138
  ) {
138
139
  return `UPDATE $${idVar} SET ${keyDataVar
139
- .map((keyDataVar) =>
140
- typeof keyDataVar === 'string'
141
- ? `${keyDataVar} = $${keyDataVar}`
142
- : 'statement' in keyDataVar
143
- ? keyDataVar.statement
144
- : `${keyDataVar.key} = $${keyDataVar.variable}`
140
+ .map((kdv) =>
141
+ typeof kdv === 'string'
142
+ ? `${kdv} = $${kdv}`
143
+ : 'statement' in kdv
144
+ ? kdv.statement
145
+ : `${kdv.key} = $${kdv.variable}`
145
146
  )
146
147
  .join(', ')}`;
147
148
  },
@@ -163,7 +164,18 @@ export const surql: SurqlHelper = {
163
164
  ) {
164
165
  switch (t) {
165
166
  case 'create':
166
- return `CREATE ONLY $${mutationIdVar} SET mutationType = 'create', recordId = $${recordIdVar}`;
167
+ // `data` is REQUIRED here, not decorative. The outbox row is the only
168
+ // copy of a pending create once the in-memory UpEvent is gone (reload,
169
+ // or a shared-tabs follower whose row is replayed by the leader). This
170
+ // used to drop `dataVar` on the floor, so every replayed create arrived
171
+ // with `data: undefined` and `processUpEvent` threw on
172
+ // `Object.keys(event.data)` before it ever reached the network: the
173
+ // create was unsendable AND it sat at the head of the queue blocking
174
+ // every later mutation. The payload was simply never persisted, so
175
+ // those creates were unrecoverable.
176
+ return dataVar
177
+ ? `CREATE ONLY $${mutationIdVar} SET mutationType = 'create', recordId = $${recordIdVar}, data = $${dataVar}`
178
+ : `CREATE ONLY $${mutationIdVar} SET mutationType = 'create', recordId = $${recordIdVar}`;
167
179
  case 'update': {
168
180
  let stmt = `CREATE ONLY $${mutationIdVar} SET mutationType = 'update', recordId = $${recordIdVar}, data = $${dataVar}`;
169
181
  if (beforeRecordVar) {
@@ -145,7 +145,7 @@ describe('withRetry', () => {
145
145
  attempt: 1,
146
146
  retries: 3,
147
147
  error: 'Can not open transaction',
148
- Category: 'spooky-client::utils::withRetry',
148
+ Category: 'sp00ky-client::utils::withRetry',
149
149
  }),
150
150
  'Retrying DB operation'
151
151
  );
package/tsdown.config.ts CHANGED
@@ -1,9 +1,94 @@
1
1
  import { defineConfig } from 'tsdown';
2
+ import { createRequire } from 'node:module';
3
+
4
+ const require = createRequire(import.meta.url);
5
+
6
+ // Resolve real package versions at build time so the DevTools can report the
7
+ // actual bundled frontend versions (used to detect frontend/backend drift).
8
+ const corePkg = require('./package.json');
9
+ const coreVersion: string = corePkg.version;
10
+ // ssp-wasm has no `exports` map; resolve its package.json directly, falling
11
+ // back to the relative workspace path if module resolution can't find it.
12
+ let wasmVersion: string;
13
+ try {
14
+ wasmVersion = require('@spooky-sync/ssp-wasm/package.json').version;
15
+ } catch {
16
+ wasmVersion = require('../ssp-wasm/package.json').version;
17
+ }
18
+ // Report the SurrealDB WASM ENGINE version (`@surrealdb/wasm`) — the engine the
19
+ // in-browser local DB actually runs — NOT the `surrealdb` JS client library
20
+ // version. The WASM engine is the one that must stay compatible with the server
21
+ // engine, so it's the meaningful number to compare in DevTools. Prefer the
22
+ // actually-installed version; fall back to our pinned range if its `exports`
23
+ // map blocks importing its package.json.
24
+ let surrealVersion: string;
25
+ try {
26
+ surrealVersion = require('@surrealdb/wasm/package.json').version;
27
+ } catch {
28
+ surrealVersion = String(corePkg.dependencies?.['@surrealdb/wasm'] ?? 'unknown').replace(
29
+ /^[\^~]/,
30
+ ''
31
+ );
32
+ }
33
+
34
+ // tsdown 0.12.x forwards a top-level `define` to rolldown's inputOptions, which
35
+ // rejects it — so we do the substitution ourselves with a tiny transform
36
+ // plugin. Only our own modules reference the `__SP00KY_*__` identifiers, and
37
+ // the early `includes` check skips everything else.
38
+ const replacements: Record<string, string> = {
39
+ __SP00KY_CORE_VERSION__: JSON.stringify(coreVersion),
40
+ __SP00KY_WASM_VERSION__: JSON.stringify(wasmVersion),
41
+ __SP00KY_SURREAL_VERSION__: JSON.stringify(surrealVersion),
42
+ };
43
+
44
+ const versionDefinePlugin = {
45
+ name: 'sp00ky-version-define',
46
+ transform(code: string) {
47
+ if (!code.includes('__SP00KY_')) return null;
48
+ let out = code;
49
+ for (const [token, value] of Object.entries(replacements)) {
50
+ out = out.split(token).join(value);
51
+ }
52
+ return out;
53
+ },
54
+ };
55
+
56
+ // Worker URLs are written as `./<name>.ts` in source so Vite's src-bundling
57
+ // consumers (the example app aliases core to `src`) resolve them. In the
58
+ // published build each worker is emitted at `dist/<name>.js`, so rewrite the
59
+ // references to `.js` here — otherwise the flat `dist/index.js` carries
60
+ // dangling `.ts` URLs that a consumer's bundler can't resolve.
61
+ const workerUrlPlugin = {
62
+ name: 'sp00ky-worker-url',
63
+ transform(code: string) {
64
+ if (!code.includes('sqlite-worker.ts') && !code.includes('tabs-broker-worker.ts')) return null;
65
+ return code
66
+ .split('sqlite-worker.ts')
67
+ .join('sqlite-worker.js')
68
+ .split('tabs-broker-worker.ts')
69
+ .join('tabs-broker-worker.js');
70
+ },
71
+ };
2
72
 
3
73
  export default defineConfig({
4
- entry: ['src/index.ts', 'src/otel/index.ts'],
74
+ // `sqlite-worker` is emitted at `dist/sqlite-worker.js` (top level, NOT under
75
+ // services/database) so the `new URL('./sqlite-worker.js', import.meta.url)`
76
+ // in `SqliteCacheEngine` — which gets bundled into the flat `dist/index.js` —
77
+ // resolves correctly. It (and `@sqlite.org/sqlite-wasm`) load lazily in the
78
+ // Worker; never pulled into the main bundle unless `localEngine: 'sqlite'`.
79
+ entry: {
80
+ index: 'src/index.ts',
81
+ 'otel/index': 'src/otel/index.ts',
82
+ 'sqlite-worker': 'src/services/database/sqlite-worker.ts',
83
+ // The shared-tabs broker MUST stay a self-contained emit (no chunk
84
+ // imports): bundlers cannot trace `new SharedWorker(url)` graphs, so a
85
+ // relative chunk import would 404 in consumers. The source keeps zero
86
+ // runtime imports and scripts/check-broker-bundle.mjs enforces it.
87
+ 'tabs-broker-worker': 'src/services/tabs/tabs-broker-worker.ts',
88
+ },
5
89
  format: ['esm'],
6
90
  dts: true,
7
91
  clean: true,
8
92
  hash: false,
93
+ plugins: [versionDefinePlugin, workerUrlPlugin],
9
94
  });
package/src/spooky.ts DELETED
@@ -1,395 +0,0 @@
1
- import { DataModule } from './modules/data/index';
2
- import {
3
- SpookyConfig,
4
- QueryTimeToLive,
5
- SpookyQueryResultPromise,
6
- PersistenceClient,
7
- MutationEvent,
8
- UpdateOptions,
9
- RunOptions,
10
- } from './types';
11
- import {
12
- LocalDatabaseService,
13
- LocalMigrator,
14
- RemoteDatabaseService,
15
- } from './services/database/index';
16
- import { Surreal } from 'surrealdb';
17
- import { SpookySync, UpEvent } from './modules/sync/index';
18
- import {
19
- GetTable,
20
- InnerQuery,
21
- QueryBuilder,
22
- QueryOptions,
23
- SchemaStructure,
24
- TableModel,
25
- TableNames,
26
- BucketNames,
27
- BackendNames,
28
- BackendRoutes,
29
- RoutePayload,
30
- } from '@spooky-sync/query-builder';
31
-
32
- import { DevToolsService } from './modules/devtools/index';
33
- import { createLogger } from './services/logger/index';
34
- import { AuthService } from './modules/auth/index';
35
- import { StreamProcessorService } from './services/stream-processor/index';
36
- import { EventSystem } from './events/index';
37
- import { CacheModule } from './modules/cache/index';
38
- import { LocalStoragePersistenceClient } from './services/persistence/localstorage';
39
- import { generateId, parseParams } from './utils/index';
40
- import { SurrealDBPersistenceClient } from './services/persistence/surrealdb';
41
- import { ResilientPersistenceClient } from './services/persistence/resilient';
42
-
43
- export class BucketHandle {
44
- constructor(private bucketName: string, private remote: RemoteDatabaseService) {}
45
-
46
- async put(path: string, content: string | Uint8Array | Blob): Promise<void> {
47
- await this.remote.query(`RETURN f"${this.bucketName}:/${path}".put($content);`, { content });
48
- }
49
-
50
- async get(path: string): Promise<unknown> {
51
- const [result] = await this.remote.query<[unknown]>(`RETURN f"${this.bucketName}:/${path}".get();`);
52
- return result;
53
- }
54
-
55
- async delete(path: string): Promise<void> {
56
- await this.remote.query(`RETURN f"${this.bucketName}:/${path}".delete();`);
57
- }
58
-
59
- async exists(path: string): Promise<boolean> {
60
- const [result] = await this.remote.query<[boolean]>(`RETURN f"${this.bucketName}:/${path}".exists();`);
61
- return result;
62
- }
63
-
64
- async head(path: string): Promise<Record<string, unknown>> {
65
- const [result] = await this.remote.query<[Record<string, unknown>]>(`RETURN f"${this.bucketName}:/${path}".head();`);
66
- return result;
67
- }
68
-
69
- async copy(sourcePath: string, targetPath: string): Promise<void> {
70
- await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".copy($target);`, { target: targetPath });
71
- }
72
-
73
- async rename(sourcePath: string, targetPath: string): Promise<void> {
74
- await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".rename($target);`, { target: targetPath });
75
- }
76
-
77
- async list(prefix?: string): Promise<string[]> {
78
- const p = prefix ?? '';
79
- const [result] = await this.remote.query<[string[]]>(`RETURN f"${this.bucketName}:/${p}".list();`);
80
- return result;
81
- }
82
- }
83
-
84
- export class SpookyClient<S extends SchemaStructure> {
85
- private local: LocalDatabaseService;
86
- private remote: RemoteDatabaseService;
87
- private persistenceClient: PersistenceClient;
88
-
89
- private migrator: LocalMigrator;
90
- private cache: CacheModule;
91
- private dataModule: DataModule<S>;
92
- private sync: SpookySync<S>;
93
- private devTools: DevToolsService;
94
-
95
- private logger: ReturnType<typeof createLogger>;
96
- public auth: AuthService<S>;
97
- public streamProcessor: StreamProcessorService;
98
-
99
- get remoteClient() {
100
- return this.remote.getClient();
101
- }
102
-
103
- get localClient() {
104
- return this.local.getClient();
105
- }
106
-
107
- get pendingMutationCount(): number {
108
- return this.sync.pendingMutationCount;
109
- }
110
-
111
- subscribeToPendingMutations(cb: (count: number) => void): () => void {
112
- return this.sync.subscribeToPendingMutations(cb);
113
- }
114
-
115
- constructor(private config: SpookyConfig<S>) {
116
- const logger = createLogger(config.logLevel ?? 'info', config.otelTransmit);
117
- this.logger = logger.child({ service: 'SpookyClient' });
118
-
119
- this.logger.info(
120
- {
121
- config: { ...config, schema: '[SchemaStructure]' },
122
- Category: 'spooky-client::SpookyClient::constructor',
123
- },
124
- 'SpookyClient initialized'
125
- );
126
-
127
- this.local = new LocalDatabaseService(this.config.database, logger);
128
- this.remote = new RemoteDatabaseService(this.config.database, logger);
129
-
130
- if (config.persistenceClient === 'surrealdb') {
131
- this.persistenceClient = new SurrealDBPersistenceClient(this.local, logger);
132
- } else if (config.persistenceClient === 'localstorage' || !config.persistenceClient) {
133
- this.persistenceClient = new LocalStoragePersistenceClient(logger);
134
- } else {
135
- this.persistenceClient = config.persistenceClient;
136
- }
137
-
138
- this.persistenceClient = new ResilientPersistenceClient(this.persistenceClient, logger);
139
-
140
- this.streamProcessor = new StreamProcessorService(
141
- new EventSystem(['stream_update']),
142
- this.local,
143
- this.persistenceClient,
144
- logger
145
- );
146
- this.migrator = new LocalMigrator(this.local, logger);
147
-
148
- this.cache = new CacheModule(
149
- this.local,
150
- this.streamProcessor,
151
- (update) => {
152
- // Direct callback from cache to data module
153
- this.dataModule.onStreamUpdate(update);
154
- },
155
- logger
156
- );
157
-
158
- this.dataModule = new DataModule(
159
- this.cache,
160
- this.local,
161
- this.config.schema,
162
- logger,
163
- this.config.streamDebounceTime
164
- );
165
-
166
- // Initialize Auth
167
- this.auth = new AuthService(this.config.schema, this.remote, this.persistenceClient, logger);
168
-
169
- // Initialize Sync
170
- this.sync = new SpookySync(this.local, this.remote, this.cache, this.dataModule, this.config.schema, this.logger);
171
-
172
- // Initialize DevTools
173
- this.devTools = new DevToolsService(
174
- this.local,
175
- this.remote,
176
- logger,
177
- this.config.schema,
178
- this.auth,
179
- this.dataModule
180
- );
181
-
182
- // Register DevTools as a receiver for stream updates
183
- this.streamProcessor.addReceiver(this.devTools);
184
-
185
- // Wire up callbacks instead of events
186
- this.setupCallbacks();
187
- }
188
-
189
- /**
190
- * Setup direct callbacks instead of event subscriptions
191
- */
192
- private setupCallbacks() {
193
- // Mutation callback for sync
194
- this.dataModule.onMutation((mutations: UpEvent[]) => {
195
- // Notify DevTools
196
- this.devTools.onMutation(mutations);
197
-
198
- // Enqueue in Sync
199
- if (mutations.length > 0) {
200
- this.sync.enqueueMutation(mutations);
201
- }
202
- });
203
-
204
- // Sync events for incoming updates
205
- this.sync.events.subscribe('SYNC_QUERY_UPDATED', (event: any) => {
206
- this.devTools.logEvent('SYNC_QUERY_UPDATED', event.payload);
207
- });
208
-
209
- // Database events for DevTools
210
- this.local.getEvents().subscribe('DATABASE_LOCAL_QUERY', (event: any) => {
211
- this.devTools.logEvent('LOCAL_QUERY', event.payload);
212
- });
213
-
214
- this.remote.getEvents().subscribe('DATABASE_REMOTE_QUERY', (event: any) => {
215
- this.devTools.logEvent('REMOTE_QUERY', event.payload);
216
- });
217
- }
218
-
219
- async init() {
220
- this.logger.info(
221
- { Category: 'spooky-client::SpookyClient::init' },
222
- 'SpookyClient initialization started'
223
- );
224
- try {
225
- const clientId = this.config.clientId ?? (await this.loadOrGenerateClientId());
226
- this.persistClientId(clientId);
227
- this.logger.debug(
228
- { clientId, Category: 'spooky-client::SpookyClient::init' },
229
- 'Client ID loaded'
230
- );
231
-
232
- await this.local.connect();
233
- this.logger.debug(
234
- { Category: 'spooky-client::SpookyClient::init' },
235
- 'Local database connected'
236
- );
237
-
238
- await this.migrator.provision(this.config.schemaSurql);
239
- this.logger.debug({ Category: 'spooky-client::SpookyClient::init' }, 'Schema provisioned');
240
-
241
- await this.remote.connect();
242
- this.logger.debug(
243
- { Category: 'spooky-client::SpookyClient::init' },
244
- 'Remote database connected'
245
- );
246
-
247
- await this.streamProcessor.init();
248
- this.logger.debug(
249
- { Category: 'spooky-client::SpookyClient::init' },
250
- 'StreamProcessor initialized'
251
- );
252
-
253
- await this.auth.init();
254
- this.logger.debug({ Category: 'spooky-client::SpookyClient::init' }, 'Auth initialized');
255
-
256
- await this.dataModule.init();
257
- this.logger.debug(
258
- { Category: 'spooky-client::SpookyClient::init' },
259
- 'DataModule initialized'
260
- );
261
-
262
- await this.sync.init(clientId);
263
- this.logger.debug({ Category: 'spooky-client::SpookyClient::init' }, 'Sync initialized');
264
-
265
- this.logger.info(
266
- { Category: 'spooky-client::SpookyClient::init' },
267
- 'SpookyClient initialization completed successfully'
268
- );
269
- } catch (e) {
270
- this.logger.error(
271
- { error: e, Category: 'spooky-client::SpookyClient::init' },
272
- 'SpookyClient initialization failed'
273
- );
274
- throw e;
275
- }
276
- }
277
-
278
- async close() {
279
- await this.local.close();
280
- await this.remote.close();
281
- }
282
-
283
- authenticate(token: string) {
284
- return this.remote.getClient().authenticate(token);
285
- }
286
-
287
- deauthenticate() {
288
- return this.remote.getClient().invalidate();
289
- }
290
-
291
- query<Table extends TableNames<S>>(
292
- table: Table,
293
- options: QueryOptions<TableModel<GetTable<S, Table>>, false>,
294
- ttl: QueryTimeToLive = '10m'
295
- ): QueryBuilder<S, Table, SpookyQueryResultPromise> {
296
- return new QueryBuilder<S, Table, SpookyQueryResultPromise>(
297
- this.config.schema,
298
- table,
299
- async (q) => ({
300
- hash: await this.initQuery(table, q, ttl),
301
- }),
302
- options
303
- );
304
- }
305
-
306
- private async initQuery<Table extends TableNames<S>>(
307
- table: Table,
308
- q: InnerQuery<any, any, any>,
309
- ttl: QueryTimeToLive
310
- ) {
311
- const tableSchema = this.config.schema.tables.find((t) => t.name === table);
312
- if (!tableSchema) {
313
- throw new Error(`Table ${table} not found`);
314
- }
315
-
316
- const hash = await this.dataModule.query(
317
- table,
318
- q.selectQuery.query,
319
- parseParams(tableSchema.columns, q.selectQuery.vars ?? {}),
320
- ttl
321
- );
322
-
323
- await this.sync.enqueueDownEvent({
324
- type: 'register',
325
- payload: {
326
- hash,
327
- },
328
- });
329
-
330
- return hash;
331
- }
332
-
333
- async queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive) {
334
- const tableName = sql.split('FROM ')[1].split(' ')[0];
335
- return this.dataModule.query(tableName, sql, params, ttl);
336
- }
337
-
338
- async subscribe(
339
- queryHash: string,
340
- callback: (records: Record<string, any>[]) => void,
341
- options?: { immediate?: boolean }
342
- ): Promise<() => void> {
343
- return this.dataModule.subscribe(queryHash, callback, options);
344
- }
345
-
346
- run<
347
- B extends BackendNames<S>,
348
- R extends BackendRoutes<S, B>,
349
- >(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions) {
350
- return this.dataModule.run(backend, path, payload, options);
351
- }
352
-
353
- bucket<B extends BucketNames<S>>(name: B): BucketHandle {
354
- return new BucketHandle(name, this.remote);
355
- }
356
-
357
- create(id: string, data: Record<string, unknown>) {
358
- return this.dataModule.create(id, data);
359
- }
360
-
361
- update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions) {
362
- return this.dataModule.update(table, id, data, options);
363
- }
364
-
365
- delete(table: string, id: string) {
366
- return this.dataModule.delete(table, id);
367
- }
368
-
369
- async useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T> {
370
- return fn(this.remote.getClient());
371
- }
372
-
373
- private persistClientId(id: string) {
374
- try {
375
- this.persistenceClient.set('spooky_client_id', id);
376
- } catch (e) {
377
- this.logger.warn(
378
- { error: e, Category: 'spooky-client::SpookyClient::persistClientId' },
379
- 'Failed to persist client ID'
380
- );
381
- }
382
- }
383
-
384
- private async loadOrGenerateClientId(): Promise<string> {
385
- const clientId = await this.persistenceClient.get<string>('spooky_client_id');
386
-
387
- if (clientId) {
388
- return clientId;
389
- }
390
-
391
- const newId = generateId();
392
- await this.persistClientId(newId);
393
- return newId;
394
- }
395
- }