@spooky-sync/core 0.0.1-canary.20 → 0.0.1-canary.201

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 (148) hide show
  1. package/AGENTS.md +57 -0
  2. package/dist/index.d.ts +2184 -54
  3. package/dist/index.js +11515 -2399
  4. package/dist/otel/index.d.ts +2 -2
  5. package/dist/otel/index.js +6 -6
  6. package/dist/sqlite-open.js +276 -0
  7. package/dist/sqlite-worker.d.ts +1 -0
  8. package/dist/sqlite-worker.js +421 -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 +688 -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 +35 -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/events/index.ts +2 -1
  25. package/src/modules/auth/index.ts +59 -20
  26. package/src/modules/cache/index.ts +112 -32
  27. package/src/modules/cache/types.ts +2 -2
  28. package/src/modules/crdt/crdt-field.ts +294 -0
  29. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  30. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  31. package/src/modules/crdt/index.ts +463 -0
  32. package/src/modules/crdt/loro-loader.ts +25 -0
  33. package/src/modules/data/data.hydration.test.ts +142 -0
  34. package/src/modules/data/data.membership.test.ts +462 -0
  35. package/src/modules/data/data.rebind.test.ts +147 -0
  36. package/src/modules/data/data.run.test.ts +113 -0
  37. package/src/modules/data/data.settled-writes.test.ts +206 -0
  38. package/src/modules/data/data.status.test.ts +249 -0
  39. package/src/modules/data/id-set-plan.test.ts +122 -0
  40. package/src/modules/data/index.ts +1580 -130
  41. package/src/modules/data/mutation-id.test.ts +25 -0
  42. package/src/modules/data/mutation-id.ts +35 -0
  43. package/src/modules/data/window-query.test.ts +52 -0
  44. package/src/modules/data/window-query.ts +194 -0
  45. package/src/modules/devtools/flags.ts +349 -0
  46. package/src/modules/devtools/index.ts +386 -37
  47. package/src/modules/devtools/notify-throttle.test.ts +149 -0
  48. package/src/modules/devtools/storage-info.test.ts +79 -0
  49. package/src/modules/devtools/storage-info.ts +168 -0
  50. package/src/modules/devtools/versions.test.ts +74 -0
  51. package/src/modules/devtools/versions.ts +110 -0
  52. package/src/modules/feature-flag/index.test.ts +251 -0
  53. package/src/modules/feature-flag/index.ts +308 -0
  54. package/src/modules/ref-tables.test.ts +91 -0
  55. package/src/modules/ref-tables.ts +88 -0
  56. package/src/modules/sync/engine.ts +101 -37
  57. package/src/modules/sync/events/index.ts +9 -2
  58. package/src/modules/sync/queue/queue-down.test.ts +107 -0
  59. package/src/modules/sync/queue/queue-down.ts +35 -6
  60. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  61. package/src/modules/sync/queue/queue-up.ts +241 -57
  62. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  63. package/src/modules/sync/scheduler.retry.test.ts +156 -0
  64. package/src/modules/sync/scheduler.ts +158 -11
  65. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  66. package/src/modules/sync/sync.health.test.ts +149 -0
  67. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  68. package/src/modules/sync/sync.live-removal.test.ts +134 -0
  69. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  70. package/src/modules/sync/sync.subquery.test.ts +82 -0
  71. package/src/modules/sync/sync.ts +1558 -99
  72. package/src/modules/sync/utils.test.ts +269 -2
  73. package/src/modules/sync/utils.ts +201 -17
  74. package/src/otel/index.ts +13 -10
  75. package/src/services/blobs/blob-cache.test.ts +359 -0
  76. package/src/services/blobs/blob-cache.ts +603 -0
  77. package/src/services/blobs/blob-manifest.ts +227 -0
  78. package/src/services/blobs/blob-store.test.ts +77 -0
  79. package/src/services/blobs/blob-store.ts +359 -0
  80. package/src/services/blobs/blob.fixture.ts +90 -0
  81. package/src/services/blobs/index.ts +70 -0
  82. package/src/services/database/cache-engine.ts +160 -0
  83. package/src/services/database/connection-supervisor.test.ts +289 -0
  84. package/src/services/database/connection-supervisor.ts +415 -0
  85. package/src/services/database/database.query-timeout.test.ts +83 -0
  86. package/src/services/database/database.ts +32 -12
  87. package/src/services/database/engine-factory.ts +33 -0
  88. package/src/services/database/events/index.ts +2 -1
  89. package/src/services/database/index.ts +7 -0
  90. package/src/services/database/local-migrator.ts +30 -27
  91. package/src/services/database/local.test.ts +64 -0
  92. package/src/services/database/local.ts +478 -67
  93. package/src/services/database/plan-render.test.ts +159 -0
  94. package/src/services/database/plan-render.ts +108 -0
  95. package/src/services/database/relation-resolver.test.ts +413 -0
  96. package/src/services/database/relation-resolver.ts +0 -0
  97. package/src/services/database/remote.ts +110 -14
  98. package/src/services/database/sqlite-cache-engine.test.ts +558 -0
  99. package/src/services/database/sqlite-cache-engine.ts +1257 -0
  100. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  101. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  102. package/src/services/database/sqlite-open.test.ts +150 -0
  103. package/src/services/database/sqlite-open.ts +164 -0
  104. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  105. package/src/services/database/sqlite-plan-sql.ts +106 -0
  106. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  107. package/src/services/database/sqlite-select.test.ts +246 -0
  108. package/src/services/database/sqlite-select.ts +121 -0
  109. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  110. package/src/services/database/sqlite-transport.ts +221 -0
  111. package/src/services/database/sqlite-worker.ts +437 -0
  112. package/src/services/database/surql-translate.ts +416 -0
  113. package/src/services/database/surreal-cache-engine.ts +141 -0
  114. package/src/services/logger/index.ts +3 -2
  115. package/src/services/persistence/localstorage.ts +2 -2
  116. package/src/services/persistence/resilient.ts +11 -4
  117. package/src/services/persistence/surrealdb.ts +10 -10
  118. package/src/services/stream-processor/index.ts +444 -52
  119. package/src/services/stream-processor/permissions.test.ts +47 -0
  120. package/src/services/stream-processor/permissions.ts +53 -0
  121. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  122. package/src/services/stream-processor/stream-processor.reset.test.ts +216 -0
  123. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  124. package/src/services/stream-processor/wasm-types.ts +23 -2
  125. package/src/services/tabs/broker-client.ts +283 -0
  126. package/src/services/tabs/broker.test.ts +278 -0
  127. package/src/services/tabs/coordinator.test.ts +244 -0
  128. package/src/services/tabs/coordinator.ts +576 -0
  129. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  130. package/src/services/tabs/leader-locks.ts +75 -0
  131. package/src/services/tabs/protocol.ts +242 -0
  132. package/src/services/tabs/support.ts +36 -0
  133. package/src/services/tabs/tabs-broker-worker.ts +586 -0
  134. package/src/sp00ky.auth-order.test.ts +92 -0
  135. package/src/sp00ky.init-query.test.ts +183 -0
  136. package/src/sp00ky.ts +1543 -0
  137. package/src/types.ts +496 -13
  138. package/src/utils/blurhash.ts +90 -0
  139. package/src/utils/error-classification.test.ts +44 -0
  140. package/src/utils/error-classification.ts +7 -0
  141. package/src/utils/index.ts +73 -13
  142. package/src/utils/parser.ts +3 -2
  143. package/src/utils/semver.test.ts +32 -0
  144. package/src/utils/semver.ts +30 -0
  145. package/src/utils/surql.ts +30 -18
  146. package/src/utils/withRetry.test.ts +1 -1
  147. package/tsdown.config.ts +86 -1
  148. package/src/spooky.ts +0 -395
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
- }