@spooky-sync/core 0.0.1-canary.7 → 0.0.1-canary.70

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 (64) hide show
  1. package/AGENTS.md +56 -0
  2. package/dist/index.d.ts +299 -369
  3. package/dist/index.js +2275 -399
  4. package/dist/otel/index.d.ts +21 -0
  5. package/dist/otel/index.js +86 -0
  6. package/dist/types.d.ts +460 -0
  7. package/package.json +37 -7
  8. package/skills/sp00ky-core/SKILL.md +258 -0
  9. package/skills/sp00ky-core/references/auth.md +98 -0
  10. package/skills/sp00ky-core/references/config.md +76 -0
  11. package/src/build-globals.d.ts +6 -0
  12. package/src/events/events.test.ts +2 -1
  13. package/src/events/index.ts +3 -0
  14. package/src/index.ts +3 -2
  15. package/src/modules/auth/events/index.ts +2 -1
  16. package/src/modules/auth/index.ts +17 -20
  17. package/src/modules/cache/index.ts +41 -29
  18. package/src/modules/cache/types.ts +2 -2
  19. package/src/modules/crdt/crdt-field.ts +281 -0
  20. package/src/modules/crdt/crdt-hydration.test.ts +206 -0
  21. package/src/modules/crdt/index.ts +352 -0
  22. package/src/modules/data/data.status.test.ts +108 -0
  23. package/src/modules/data/index.ts +662 -108
  24. package/src/modules/data/window-query.test.ts +52 -0
  25. package/src/modules/data/window-query.ts +130 -0
  26. package/src/modules/devtools/index.ts +77 -21
  27. package/src/modules/devtools/versions.test.ts +74 -0
  28. package/src/modules/devtools/versions.ts +81 -0
  29. package/src/modules/ref-tables.test.ts +56 -0
  30. package/src/modules/ref-tables.ts +57 -0
  31. package/src/modules/sync/engine.ts +97 -37
  32. package/src/modules/sync/events/index.ts +3 -2
  33. package/src/modules/sync/queue/queue-down.ts +5 -4
  34. package/src/modules/sync/queue/queue-up.ts +14 -13
  35. package/src/modules/sync/scheduler.ts +2 -2
  36. package/src/modules/sync/sync.ts +553 -58
  37. package/src/modules/sync/utils.test.ts +239 -2
  38. package/src/modules/sync/utils.ts +166 -17
  39. package/src/otel/index.ts +127 -0
  40. package/src/services/database/database.ts +11 -11
  41. package/src/services/database/events/index.ts +2 -1
  42. package/src/services/database/local-migrator.ts +21 -21
  43. package/src/services/database/local.test.ts +33 -0
  44. package/src/services/database/local.ts +192 -32
  45. package/src/services/database/remote.ts +13 -13
  46. package/src/services/logger/index.ts +6 -101
  47. package/src/services/persistence/localstorage.ts +2 -2
  48. package/src/services/persistence/resilient.ts +41 -0
  49. package/src/services/persistence/surrealdb.ts +9 -9
  50. package/src/services/stream-processor/index.ts +205 -36
  51. package/src/services/stream-processor/permissions.test.ts +47 -0
  52. package/src/services/stream-processor/permissions.ts +53 -0
  53. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  54. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  55. package/src/services/stream-processor/wasm-types.ts +18 -2
  56. package/src/sp00ky.auth-order.test.ts +65 -0
  57. package/src/sp00ky.ts +582 -0
  58. package/src/types.ts +132 -13
  59. package/src/utils/index.ts +35 -13
  60. package/src/utils/parser.ts +3 -2
  61. package/src/utils/surql.ts +24 -15
  62. package/src/utils/withRetry.test.ts +1 -1
  63. package/tsdown.config.ts +55 -1
  64. package/src/spooky.ts +0 -392
package/src/spooky.ts DELETED
@@ -1,392 +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
-
42
- export class BucketHandle {
43
- constructor(private bucketName: string, private remote: RemoteDatabaseService) {}
44
-
45
- async put(path: string, content: string | Uint8Array | Blob): Promise<void> {
46
- await this.remote.query(`RETURN f"${this.bucketName}:/${path}".put($content);`, { content });
47
- }
48
-
49
- async get(path: string): Promise<unknown> {
50
- const [result] = await this.remote.query<[unknown]>(`RETURN f"${this.bucketName}:/${path}".get();`);
51
- return result;
52
- }
53
-
54
- async delete(path: string): Promise<void> {
55
- await this.remote.query(`RETURN f"${this.bucketName}:/${path}".delete();`);
56
- }
57
-
58
- async exists(path: string): Promise<boolean> {
59
- const [result] = await this.remote.query<[boolean]>(`RETURN f"${this.bucketName}:/${path}".exists();`);
60
- return result;
61
- }
62
-
63
- async head(path: string): Promise<Record<string, unknown>> {
64
- const [result] = await this.remote.query<[Record<string, unknown>]>(`RETURN f"${this.bucketName}:/${path}".head();`);
65
- return result;
66
- }
67
-
68
- async copy(sourcePath: string, targetPath: string): Promise<void> {
69
- await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".copy($target);`, { target: targetPath });
70
- }
71
-
72
- async rename(sourcePath: string, targetPath: string): Promise<void> {
73
- await this.remote.query(`RETURN f"${this.bucketName}:/${sourcePath}".rename($target);`, { target: targetPath });
74
- }
75
-
76
- async list(prefix?: string): Promise<string[]> {
77
- const p = prefix ?? '';
78
- const [result] = await this.remote.query<[string[]]>(`RETURN f"${this.bucketName}:/${p}".list();`);
79
- return result;
80
- }
81
- }
82
-
83
- export class SpookyClient<S extends SchemaStructure> {
84
- private local: LocalDatabaseService;
85
- private remote: RemoteDatabaseService;
86
- private persistenceClient: PersistenceClient;
87
-
88
- private migrator: LocalMigrator;
89
- private cache: CacheModule;
90
- private dataModule: DataModule<S>;
91
- private sync: SpookySync<S>;
92
- private devTools: DevToolsService;
93
-
94
- private logger: ReturnType<typeof createLogger>;
95
- public auth: AuthService<S>;
96
- public streamProcessor: StreamProcessorService;
97
-
98
- get remoteClient() {
99
- return this.remote.getClient();
100
- }
101
-
102
- get localClient() {
103
- return this.local.getClient();
104
- }
105
-
106
- get pendingMutationCount(): number {
107
- return this.sync.pendingMutationCount;
108
- }
109
-
110
- subscribeToPendingMutations(cb: (count: number) => void): () => void {
111
- return this.sync.subscribeToPendingMutations(cb);
112
- }
113
-
114
- constructor(private config: SpookyConfig<S>) {
115
- const logger = createLogger(config.logLevel ?? 'info', config.otelEndpoint);
116
- this.logger = logger.child({ service: 'SpookyClient' });
117
-
118
- this.logger.info(
119
- {
120
- config: { ...config, schema: '[SchemaStructure]' },
121
- Category: 'spooky-client::SpookyClient::constructor',
122
- },
123
- 'SpookyClient initialized'
124
- );
125
-
126
- this.local = new LocalDatabaseService(this.config.database, logger);
127
- this.remote = new RemoteDatabaseService(this.config.database, logger);
128
-
129
- if (config.persistenceClient === 'surrealdb') {
130
- this.persistenceClient = new SurrealDBPersistenceClient(this.local, logger);
131
- } else if (config.persistenceClient === 'localstorage' || !config.persistenceClient) {
132
- this.persistenceClient = new LocalStoragePersistenceClient(logger);
133
- } else {
134
- this.persistenceClient = config.persistenceClient;
135
- }
136
-
137
- this.streamProcessor = new StreamProcessorService(
138
- new EventSystem(['stream_update']),
139
- this.local,
140
- this.persistenceClient,
141
- logger
142
- );
143
- this.migrator = new LocalMigrator(this.local, logger);
144
-
145
- this.cache = new CacheModule(
146
- this.local,
147
- this.streamProcessor,
148
- (update) => {
149
- // Direct callback from cache to data module
150
- this.dataModule.onStreamUpdate(update);
151
- },
152
- logger
153
- );
154
-
155
- this.dataModule = new DataModule(
156
- this.cache,
157
- this.local,
158
- this.config.schema,
159
- logger,
160
- this.config.streamDebounceTime
161
- );
162
-
163
- // Initialize Auth
164
- this.auth = new AuthService(this.config.schema, this.remote, this.persistenceClient, logger);
165
-
166
- // Initialize Sync
167
- this.sync = new SpookySync(this.local, this.remote, this.cache, this.dataModule, this.config.schema, this.logger);
168
-
169
- // Initialize DevTools
170
- this.devTools = new DevToolsService(
171
- this.local,
172
- this.remote,
173
- logger,
174
- this.config.schema,
175
- this.auth,
176
- this.dataModule
177
- );
178
-
179
- // Register DevTools as a receiver for stream updates
180
- this.streamProcessor.addReceiver(this.devTools);
181
-
182
- // Wire up callbacks instead of events
183
- this.setupCallbacks();
184
- }
185
-
186
- /**
187
- * Setup direct callbacks instead of event subscriptions
188
- */
189
- private setupCallbacks() {
190
- // Mutation callback for sync
191
- this.dataModule.onMutation((mutations: UpEvent[]) => {
192
- // Notify DevTools
193
- this.devTools.onMutation(mutations);
194
-
195
- // Enqueue in Sync
196
- if (mutations.length > 0) {
197
- this.sync.enqueueMutation(mutations);
198
- }
199
- });
200
-
201
- // Sync events for incoming updates
202
- this.sync.events.subscribe('SYNC_QUERY_UPDATED', (event: any) => {
203
- this.devTools.logEvent('SYNC_QUERY_UPDATED', event.payload);
204
- });
205
-
206
- // Database events for DevTools
207
- this.local.getEvents().subscribe('DATABASE_LOCAL_QUERY', (event: any) => {
208
- this.devTools.logEvent('LOCAL_QUERY', event.payload);
209
- });
210
-
211
- this.remote.getEvents().subscribe('DATABASE_REMOTE_QUERY', (event: any) => {
212
- this.devTools.logEvent('REMOTE_QUERY', event.payload);
213
- });
214
- }
215
-
216
- async init() {
217
- this.logger.info(
218
- { Category: 'spooky-client::SpookyClient::init' },
219
- 'SpookyClient initialization started'
220
- );
221
- try {
222
- const clientId = this.config.clientId ?? (await this.loadOrGenerateClientId());
223
- this.persistClientId(clientId);
224
- this.logger.debug(
225
- { clientId, Category: 'spooky-client::SpookyClient::init' },
226
- 'Client ID loaded'
227
- );
228
-
229
- await this.local.connect();
230
- this.logger.debug(
231
- { Category: 'spooky-client::SpookyClient::init' },
232
- 'Local database connected'
233
- );
234
-
235
- await this.migrator.provision(this.config.schemaSurql);
236
- this.logger.debug({ Category: 'spooky-client::SpookyClient::init' }, 'Schema provisioned');
237
-
238
- await this.remote.connect();
239
- this.logger.debug(
240
- { Category: 'spooky-client::SpookyClient::init' },
241
- 'Remote database connected'
242
- );
243
-
244
- await this.streamProcessor.init();
245
- this.logger.debug(
246
- { Category: 'spooky-client::SpookyClient::init' },
247
- 'StreamProcessor initialized'
248
- );
249
-
250
- await this.auth.init();
251
- this.logger.debug({ Category: 'spooky-client::SpookyClient::init' }, 'Auth initialized');
252
-
253
- await this.dataModule.init();
254
- this.logger.debug(
255
- { Category: 'spooky-client::SpookyClient::init' },
256
- 'DataModule initialized'
257
- );
258
-
259
- await this.sync.init(clientId);
260
- this.logger.debug({ Category: 'spooky-client::SpookyClient::init' }, 'Sync initialized');
261
-
262
- this.logger.info(
263
- { Category: 'spooky-client::SpookyClient::init' },
264
- 'SpookyClient initialization completed successfully'
265
- );
266
- } catch (e) {
267
- this.logger.error(
268
- { error: e, Category: 'spooky-client::SpookyClient::init' },
269
- 'SpookyClient initialization failed'
270
- );
271
- throw e;
272
- }
273
- }
274
-
275
- async close() {
276
- await this.local.close();
277
- await this.remote.close();
278
- }
279
-
280
- authenticate(token: string) {
281
- return this.remote.getClient().authenticate(token);
282
- }
283
-
284
- deauthenticate() {
285
- return this.remote.getClient().invalidate();
286
- }
287
-
288
- query<Table extends TableNames<S>>(
289
- table: Table,
290
- options: QueryOptions<TableModel<GetTable<S, Table>>, false>,
291
- ttl: QueryTimeToLive = '10m'
292
- ): QueryBuilder<S, Table, SpookyQueryResultPromise> {
293
- return new QueryBuilder<S, Table, SpookyQueryResultPromise>(
294
- this.config.schema,
295
- table,
296
- async (q) => ({
297
- hash: await this.initQuery(table, q, ttl),
298
- }),
299
- options
300
- );
301
- }
302
-
303
- private async initQuery<Table extends TableNames<S>>(
304
- table: Table,
305
- q: InnerQuery<any, any, any>,
306
- ttl: QueryTimeToLive
307
- ) {
308
- const tableSchema = this.config.schema.tables.find((t) => t.name === table);
309
- if (!tableSchema) {
310
- throw new Error(`Table ${table} not found`);
311
- }
312
-
313
- const hash = await this.dataModule.query(
314
- table,
315
- q.selectQuery.query,
316
- parseParams(tableSchema.columns, q.selectQuery.vars ?? {}),
317
- ttl
318
- );
319
-
320
- await this.sync.enqueueDownEvent({
321
- type: 'register',
322
- payload: {
323
- hash,
324
- },
325
- });
326
-
327
- return hash;
328
- }
329
-
330
- async queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive) {
331
- const tableName = sql.split('FROM ')[1].split(' ')[0];
332
- return this.dataModule.query(tableName, sql, params, ttl);
333
- }
334
-
335
- async subscribe(
336
- queryHash: string,
337
- callback: (records: Record<string, any>[]) => void,
338
- options?: { immediate?: boolean }
339
- ): Promise<() => void> {
340
- return this.dataModule.subscribe(queryHash, callback, options);
341
- }
342
-
343
- run<
344
- B extends BackendNames<S>,
345
- R extends BackendRoutes<S, B>,
346
- >(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions) {
347
- return this.dataModule.run(backend, path, payload, options);
348
- }
349
-
350
- bucket<B extends BucketNames<S>>(name: B): BucketHandle {
351
- return new BucketHandle(name, this.remote);
352
- }
353
-
354
- create(id: string, data: Record<string, unknown>) {
355
- return this.dataModule.create(id, data);
356
- }
357
-
358
- update(table: string, id: string, data: Record<string, unknown>, options?: UpdateOptions) {
359
- return this.dataModule.update(table, id, data, options);
360
- }
361
-
362
- delete(table: string, id: string) {
363
- return this.dataModule.delete(table, id);
364
- }
365
-
366
- async useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T> {
367
- return fn(this.remote.getClient());
368
- }
369
-
370
- private persistClientId(id: string) {
371
- try {
372
- this.persistenceClient.set('spooky_client_id', id);
373
- } catch (e) {
374
- this.logger.warn(
375
- { error: e, Category: 'spooky-client::SpookyClient::persistClientId' },
376
- 'Failed to persist client ID'
377
- );
378
- }
379
- }
380
-
381
- private async loadOrGenerateClientId(): Promise<string> {
382
- const clientId = await this.persistenceClient.get<string>('spooky_client_id');
383
-
384
- if (clientId) {
385
- return clientId;
386
- }
387
-
388
- const newId = generateId();
389
- await this.persistClientId(newId);
390
- return newId;
391
- }
392
- }