@spooky-sync/core 0.0.1-canary.13 → 0.0.1-canary.131
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.
- package/AGENTS.md +56 -0
- package/dist/index.d.ts +1171 -372
- package/dist/index.js +5726 -1277
- package/dist/otel/index.d.ts +21 -0
- package/dist/otel/index.js +86 -0
- package/dist/sqlite-worker.d.ts +1 -0
- package/dist/sqlite-worker.js +107 -0
- package/dist/types.d.ts +746 -0
- package/package.json +39 -8
- package/skills/sp00ky-core/SKILL.md +258 -0
- package/skills/sp00ky-core/references/auth.md +98 -0
- package/skills/sp00ky-core/references/config.md +76 -0
- package/src/build-globals.d.ts +12 -0
- package/src/events/events.test.ts +2 -1
- package/src/events/index.ts +3 -0
- package/src/index.ts +9 -2
- package/src/modules/auth/events/index.ts +2 -1
- package/src/modules/auth/index.ts +59 -20
- package/src/modules/cache/index.ts +77 -32
- package/src/modules/cache/types.ts +2 -2
- package/src/modules/crdt/crdt-field.ts +288 -0
- package/src/modules/crdt/crdt-hydration.test.ts +206 -0
- package/src/modules/crdt/index.ts +357 -0
- package/src/modules/data/data.hydration.test.ts +150 -0
- package/src/modules/data/data.rebind.test.ts +147 -0
- package/src/modules/data/data.recurring.test.ts +137 -0
- package/src/modules/data/data.status.test.ts +249 -0
- package/src/modules/data/index.ts +1234 -127
- package/src/modules/data/window-query.test.ts +52 -0
- package/src/modules/data/window-query.ts +154 -0
- package/src/modules/devtools/index.ts +191 -30
- package/src/modules/devtools/versions.test.ts +74 -0
- package/src/modules/devtools/versions.ts +81 -0
- package/src/modules/feature-flag/index.test.ts +120 -0
- package/src/modules/feature-flag/index.ts +209 -0
- package/src/modules/ref-tables.test.ts +91 -0
- package/src/modules/ref-tables.ts +88 -0
- package/src/modules/sync/engine.ts +101 -37
- package/src/modules/sync/events/index.ts +9 -2
- package/src/modules/sync/queue/queue-down.ts +12 -5
- package/src/modules/sync/queue/queue-up.ts +29 -14
- package/src/modules/sync/scheduler.pause.test.ts +109 -0
- package/src/modules/sync/scheduler.ts +73 -7
- package/src/modules/sync/sync.health.test.ts +149 -0
- package/src/modules/sync/sync.subquery.test.ts +82 -0
- package/src/modules/sync/sync.ts +1017 -62
- package/src/modules/sync/utils.test.ts +269 -2
- package/src/modules/sync/utils.ts +182 -17
- package/src/otel/index.ts +127 -0
- package/src/services/database/cache-engine.ts +143 -0
- package/src/services/database/database.ts +11 -11
- package/src/services/database/engine-factory.ts +32 -0
- package/src/services/database/events/index.ts +2 -1
- package/src/services/database/index.ts +6 -0
- package/src/services/database/local-migrator.ts +28 -27
- package/src/services/database/local.test.ts +64 -0
- package/src/services/database/local.ts +452 -66
- package/src/services/database/plan-render.test.ts +133 -0
- package/src/services/database/plan-render.ts +100 -0
- package/src/services/database/relation-resolver.test.ts +413 -0
- package/src/services/database/relation-resolver.ts +0 -0
- package/src/services/database/remote.ts +13 -13
- package/src/services/database/sqlite-cache-engine.test.ts +85 -0
- package/src/services/database/sqlite-cache-engine.ts +699 -0
- package/src/services/database/sqlite-worker.ts +116 -0
- package/src/services/database/surql-translate.ts +291 -0
- package/src/services/database/surreal-cache-engine.ts +139 -0
- package/src/services/logger/index.ts +6 -101
- package/src/services/persistence/localstorage.ts +2 -2
- package/src/services/persistence/resilient.ts +41 -0
- package/src/services/persistence/surrealdb.ts +10 -10
- package/src/services/stream-processor/index.ts +295 -38
- package/src/services/stream-processor/permissions.test.ts +47 -0
- package/src/services/stream-processor/permissions.ts +53 -0
- package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
- package/src/services/stream-processor/stream-processor.reset.test.ts +104 -0
- package/src/services/stream-processor/stream-processor.test.ts +1 -1
- package/src/services/stream-processor/wasm-types.ts +18 -2
- package/src/sp00ky.auth-order.test.ts +92 -0
- package/src/sp00ky.init-query.test.ts +185 -0
- package/src/sp00ky.ts +1016 -0
- package/src/types.ts +258 -15
- package/src/utils/error-classification.test.ts +44 -0
- package/src/utils/error-classification.ts +7 -0
- package/src/utils/index.ts +35 -13
- package/src/utils/parser.ts +3 -2
- package/src/utils/surql.ts +24 -15
- package/src/utils/withRetry.test.ts +1 -1
- package/tsdown.config.ts +77 -1
- package/src/spooky.ts +0 -392
package/tsdown.config.ts
CHANGED
|
@@ -1,9 +1,85 @@
|
|
|
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
|
+
// The SQLite worker URL is written as `./sqlite-worker.ts` in source so Vite's
|
|
57
|
+
// src-bundling consumers (the example app aliases core to `src`) resolve it.
|
|
58
|
+
// In the published build the worker is emitted at `dist/sqlite-worker.js`, so
|
|
59
|
+
// rewrite the reference to `.js` here — otherwise the flat `dist/index.js`
|
|
60
|
+
// carries a dangling `.ts` URL that a consumer's bundler can't resolve.
|
|
61
|
+
const sqliteWorkerUrlPlugin = {
|
|
62
|
+
name: 'sp00ky-sqlite-worker-url',
|
|
63
|
+
transform(code: string) {
|
|
64
|
+
if (!code.includes('sqlite-worker.ts')) return null;
|
|
65
|
+
return code.split('sqlite-worker.ts').join('sqlite-worker.js');
|
|
66
|
+
},
|
|
67
|
+
};
|
|
2
68
|
|
|
3
69
|
export default defineConfig({
|
|
4
|
-
|
|
70
|
+
// `sqlite-worker` is emitted at `dist/sqlite-worker.js` (top level, NOT under
|
|
71
|
+
// services/database) so the `new URL('./sqlite-worker.js', import.meta.url)`
|
|
72
|
+
// in `SqliteCacheEngine` — which gets bundled into the flat `dist/index.js` —
|
|
73
|
+
// resolves correctly. It (and `@sqlite.org/sqlite-wasm`) load lazily in the
|
|
74
|
+
// Worker; never pulled into the main bundle unless `localEngine: 'sqlite'`.
|
|
75
|
+
entry: {
|
|
76
|
+
index: 'src/index.ts',
|
|
77
|
+
'otel/index': 'src/otel/index.ts',
|
|
78
|
+
'sqlite-worker': 'src/services/database/sqlite-worker.ts',
|
|
79
|
+
},
|
|
5
80
|
format: ['esm'],
|
|
6
81
|
dts: true,
|
|
7
82
|
clean: true,
|
|
8
83
|
hash: false,
|
|
84
|
+
plugins: [versionDefinePlugin, sqliteWorkerUrlPlugin],
|
|
9
85
|
});
|
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
|
-
}
|