@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
@@ -1,99 +1,510 @@
1
- import { applyDiagnostics, DateTime, Diagnostic, RecordId, Surreal } from 'surrealdb';
2
- import { createWasmWorkerEngines } from '@surrealdb/wasm';
3
- import { SpookyConfig } from '../../types';
4
- import { Logger } from '../logger/index';
1
+ import type { Diagnostic} from 'surrealdb';
2
+ import { applyDiagnostics, DateTime, RecordId, Surreal } from 'surrealdb';
3
+ import type { Sp00kyConfig } from '../../types';
4
+ import type { Logger } from '../logger/index';
5
5
  import { AbstractDatabaseService } from './database';
6
6
  import { createDatabaseEventSystem, DatabaseEventTypes } from './events/index';
7
- import { encodeRecordId, parseRecordIdString, surql } from '../../utils/index';
7
+ import { encodeRecordId } from '../../utils/index';
8
+ import { ANON_USER_ID } from '../../modules/ref-tables';
9
+ import type { SealedQuery } from '../../utils/surql';
10
+
11
+ /** Thrown when a query carries an `epoch` from before a bucket switch. The
12
+ * caller's chain read from the previous user's store; its write must be
13
+ * dropped, not applied to the new bucket. */
14
+ export class StaleEpochError extends Error {
15
+ constructor() {
16
+ super('Local store epoch changed (bucket switch); stale write dropped');
17
+ this.name = 'StaleEpochError';
18
+ }
19
+ }
20
+
21
+ /** Store URL for a local bucket. One IndexedDB store per user (`anon` for
22
+ * signed-out) so cached rows never leak across accounts on a shared device. */
23
+ export function bucketStoreUrl(bucketId: string): string {
24
+ return `indxdb://${bucketStoreName(bucketId)}`;
25
+ }
26
+
27
+ /** The IndexedDB database name SurrealDB-WASM derives from the store URL. */
28
+ export function bucketStoreName(bucketId: string): string {
29
+ return `sp00ky-${bucketId}`;
30
+ }
31
+
32
+ /** Shared codec: mirrors SurrealDB RecordId/DateTime into our own encodings. */
33
+ const localCodecOptions = {
34
+ valueDecodeVisitor(value: unknown) {
35
+ if (value instanceof RecordId) {
36
+ return encodeRecordId(value);
37
+ }
38
+
39
+ if (value instanceof DateTime) {
40
+ return value.toDate();
41
+ }
42
+
43
+ return value;
44
+ },
45
+ };
46
+
47
+ /**
48
+ * Engine-less Surreal client used as the constructor placeholder. Building this
49
+ * pulls in NO `@surrealdb/wasm` — the ~6 MB wasm engine is deferred to
50
+ * {@link createLocalSurrealClient}, which runs lazily in `connect`/`switchStore`.
51
+ * `connect()` replaces `this.client` with an engine-backed client before any
52
+ * query runs, so this bare client is never actually opened against a store.
53
+ */
54
+ function createBareSurrealClient(): Surreal {
55
+ return new Surreal({ codecOptions: localCodecOptions });
56
+ }
57
+
58
+ /**
59
+ * Engine-backed client. Dynamically imports `@surrealdb/wasm` so the wasm engine
60
+ * only enters the graph as a separate chunk fetched on first connect (module-
61
+ * cached thereafter — `switchStore`'s await is instant).
62
+ */
63
+ async function createLocalSurrealClient(logger: Logger): Promise<Surreal> {
64
+ const { createWasmWorkerEngines } = await import('@surrealdb/wasm');
65
+ return new Surreal({
66
+ codecOptions: localCodecOptions,
67
+ engines: applyDiagnostics(
68
+ createWasmWorkerEngines(),
69
+ ({ key, type, phase, ...other }: Diagnostic) => {
70
+ if (phase === 'progress' || phase === 'after') {
71
+ logger.trace(
72
+ {
73
+ ...other,
74
+ key,
75
+ type,
76
+ phase,
77
+ service: 'surrealdb:local',
78
+ Category: 'sp00ky-client::LocalDatabaseService::diagnostics',
79
+ },
80
+ `Local SurrealDB diagnostics captured ${type}:${phase}`
81
+ );
82
+ }
83
+ }
84
+ ),
85
+ });
86
+ }
8
87
 
9
88
  export class LocalDatabaseService extends AbstractDatabaseService {
10
- private config: SpookyConfig<any>['database'];
89
+ private config: Sp00kyConfig<any>['database'];
11
90
  protected eventType = DatabaseEventTypes.LocalQuery;
12
91
 
13
- constructor(config: SpookyConfig<any>['database'], logger: Logger) {
92
+ /** Bucket currently open. Set by `connect`/`switchStore`. */
93
+ private bucketId: string = ANON_USER_ID;
94
+ /**
95
+ * Monotonic store generation. Bumped on every `switchStore`. Async chains
96
+ * that read from the store, await something remote, and then write back
97
+ * (sync poll, SSP stream updates) capture this at chain start and drop
98
+ * their write when it no longer matches — a stale-epoch write would land
99
+ * another user's data in the new bucket.
100
+ */
101
+ private storeEpoch = 0;
102
+ /** Gate that `query()`/`execute()` await; closed for the switch window. */
103
+ private gate: Promise<void> = Promise.resolve();
104
+ /** The incoming client while a switch is in flight (for unload cleanup). */
105
+ private pendingSwitchClient: Surreal | null = null;
106
+
107
+ constructor(config: Sp00kyConfig<any>['database'], logger: Logger) {
14
108
  const events = createDatabaseEventSystem();
15
- super(
16
- new Surreal({
17
- codecOptions: {
18
- valueDecodeVisitor(value) {
19
- if (value instanceof RecordId) {
20
- return encodeRecordId(value);
21
- }
22
-
23
- if (value instanceof DateTime) {
24
- return value.toDate();
25
- }
26
-
27
- return value;
28
- },
29
- },
30
- engines: applyDiagnostics(
31
- createWasmWorkerEngines(),
32
- ({ key, type, phase, ...other }: Diagnostic) => {
33
- if (phase === 'progress' || phase === 'after') {
34
- logger.trace(
35
- {
36
- ...other,
37
- key,
38
- type,
39
- phase,
40
- service: 'surrealdb:local',
41
- Category: 'spooky-client::LocalDatabaseService::diagnostics',
42
- },
43
- `Local SurrealDB diagnostics captured ${type}:${phase}`
44
- );
45
- }
46
- }
47
- ),
48
- }),
49
- logger,
50
- events
51
- );
109
+ // Placeholder client with no wasm engine; `connect()` swaps in the real
110
+ // engine-backed client (built lazily) before any query is issued.
111
+ super(createBareSurrealClient(), logger, events);
52
112
  this.config = config;
53
113
  }
54
114
 
55
- getConfig(): SpookyConfig<any>['database'] {
115
+ getConfig(): Sp00kyConfig<any>['database'] {
56
116
  return this.config;
57
117
  }
58
118
 
59
- async connect(): Promise<void> {
119
+ get currentBucketId(): string {
120
+ return this.bucketId;
121
+ }
122
+
123
+ get epoch(): number {
124
+ return this.storeEpoch;
125
+ }
126
+
127
+ /**
128
+ * Close the query gate for a bucket switch. Every `query()`/`execute()`
129
+ * issued after this waits until the returned release fn runs — so work
130
+ * triggered mid-switch (sibling auth subscribers registering queries)
131
+ * lands on the NEW bucket instead of racing the swap. The migrator uses
132
+ * `queryUngated()` to provision the new bucket while the gate is closed.
133
+ */
134
+ beginSwitch(): () => void {
135
+ let release!: () => void;
136
+ this.gate = new Promise<void>((resolve) => {
137
+ release = resolve;
138
+ });
139
+ return release;
140
+ }
141
+
142
+ override async query<T extends unknown[]>(
143
+ query: string,
144
+ vars?: Record<string, unknown>,
145
+ opts?: { epoch?: number }
146
+ ): Promise<T> {
147
+ await this.gate;
148
+ // A write whose async chain started before a bucket switch must not land
149
+ // in the new bucket — that would be another user's data. Callers on such
150
+ // chains pass the epoch they captured at chain start; mismatches throw.
151
+ if (opts?.epoch !== undefined && opts.epoch !== this.storeEpoch) {
152
+ throw new StaleEpochError();
153
+ }
154
+ return super.query(query, vars);
155
+ }
156
+
157
+ override async execute<T>(
158
+ query: SealedQuery<T>,
159
+ vars?: Record<string, unknown>,
160
+ opts?: { epoch?: number }
161
+ ): Promise<T> {
162
+ const raw = await this.query<unknown[]>(query.sql, vars, opts);
163
+ return query.extract(raw);
164
+ }
165
+
166
+ /** Gate-bypassing query — ONLY for the switch path itself (schema
167
+ * provisioning must run while the gate is closed, or it deadlocks). */
168
+ queryUngated<T extends unknown[]>(query: string, vars?: Record<string, unknown>): Promise<T> {
169
+ return super.query(query, vars);
170
+ }
171
+
172
+ async connect(bucketId: string = ANON_USER_ID): Promise<void> {
60
173
  const { namespace, database } = this.getConfig();
174
+ const store = this.getConfig().store ?? 'memory';
175
+ this.bucketId = bucketId;
176
+ const storeUrl = store === 'memory' ? 'mem://' : bucketStoreUrl(bucketId);
61
177
  this.logger.info(
62
- { namespace, database, Category: 'spooky-client::LocalDatabaseService::connect' },
178
+ { namespace, database, storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
63
179
  'Connecting to local database'
64
180
  );
65
- try {
66
- const store = this.getConfig().store ?? 'memory';
67
- const storeUrl = store === 'memory' ? 'mem://' : 'indxdb://spooky';
68
- this.logger.debug(
69
- { storeUrl, Category: 'spooky-client::LocalDatabaseService::connect' },
70
- '[LocalDatabaseService] Calling client.connect'
71
- );
72
- await this.client.connect(storeUrl, {});
73
- this.logger.debug(
74
- { namespace, database, Category: 'spooky-client::LocalDatabaseService::connect' },
75
- '[LocalDatabaseService] client.connect returned. Calling client.use'
181
+
182
+ this.registerUnloadClose();
183
+ // Build the real engine-backed client lazily here (first `@surrealdb/wasm`
184
+ // load), replacing the constructor's engine-less placeholder before any
185
+ // query runs.
186
+ this.client = await createLocalSurrealClient(this.logger);
187
+ await this.openWithRecovery(this.client, storeUrl, namespace, database, bucketId, store);
188
+ }
189
+
190
+ /**
191
+ * Switch the local store to another user's bucket. Opens the NEW bucket on a
192
+ * second client first (with the same 3-tier recovery), then atomically swaps
193
+ * `this.client` and closes the old one — a failed open never leaves the
194
+ * service on a dead client. Bumps the store epoch so in-flight old-bucket
195
+ * async chains can detect they're stale.
196
+ *
197
+ * Callers own the drain/rebind choreography (close the gate, quiesce sync +
198
+ * timers BEFORE calling this; re-provision + rebind AFTER).
199
+ */
200
+ async switchStore(bucketId: string): Promise<void> {
201
+ if (bucketId === this.bucketId) return;
202
+ const { namespace, database } = this.getConfig();
203
+ const store = this.getConfig().store ?? 'memory';
204
+ this.storeEpoch++;
205
+
206
+ if (store === 'memory') {
207
+ // mem:// has no per-user persistence; close + reopen the same client
208
+ // yields a fresh empty store, which is exactly the reset we want.
209
+ try {
210
+ await this.client.close();
211
+ } catch {
212
+ /* ignore */
213
+ }
214
+ await this.openStore(this.client, 'mem://', namespace, database);
215
+ this.bucketId = bucketId;
216
+ this.logger.info(
217
+ { bucketId, Category: 'sp00ky-client::LocalDatabaseService::switchStore' },
218
+ 'Reset in-memory local store for bucket switch'
76
219
  );
220
+ return;
221
+ }
77
222
 
78
- await this.client.use({
223
+ const next = await createLocalSurrealClient(this.logger);
224
+ this.pendingSwitchClient = next;
225
+ try {
226
+ await this.openWithRecovery(
227
+ next,
228
+ bucketStoreUrl(bucketId),
79
229
  namespace,
80
230
  database,
81
- });
82
- this.logger.debug(
83
- { Category: 'spooky-client::LocalDatabaseService::connect' },
84
- '[LocalDatabaseService] client.use returned'
231
+ bucketId,
232
+ store
85
233
  );
234
+ } finally {
235
+ this.pendingSwitchClient = null;
236
+ }
86
237
 
238
+ const old = this.client;
239
+ this.client = next;
240
+ this.bucketId = bucketId;
241
+ try {
242
+ await old.close();
243
+ } catch {
244
+ /* best-effort — the old store's handle is released on unload regardless */
245
+ }
246
+ this.logger.info(
247
+ { bucketId, Category: 'sp00ky-client::LocalDatabaseService::switchStore' },
248
+ 'Switched local store bucket'
249
+ );
250
+ }
251
+
252
+ /**
253
+ * Open `storeUrl` on `client` with tiered recovery:
254
+ * tier 1 retries the same store (transient idb-handle races — preserves the
255
+ * cache), tier 2 drops THIS bucket's IndexedDB store and reconnects fresh,
256
+ * tier 3 falls back to `mem://` for the session. Only ever drops the bucket
257
+ * being opened — other users' buckets hold their own caches AND un-pushed
258
+ * mutation outboxes, which must survive another bucket's corruption.
259
+ */
260
+ private async openWithRecovery(
261
+ client: Surreal,
262
+ storeUrl: string,
263
+ namespace: string,
264
+ database: string,
265
+ bucketId: string,
266
+ store: string
267
+ ): Promise<void> {
268
+ try {
269
+ await this.openStore(client, storeUrl, namespace, database);
87
270
  this.logger.info(
88
- { Category: 'spooky-client::LocalDatabaseService::connect' },
271
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
89
272
  'Connected to local database'
90
273
  );
274
+ return;
91
275
  } catch (err) {
276
+ // A persistent (IndexedDB) local store can fail to open if it was left
277
+ // corrupt or version-incompatible by a prior session/crash/engine bump.
278
+ // The local store is only a cache (everything re-syncs from the server),
279
+ // so recover by dropping it and reconnecting rather than bricking startup.
280
+ if (store === 'memory' || !isLocalStoreOpenError(err)) {
281
+ this.logger.error(
282
+ { err, Category: 'sp00ky-client::LocalDatabaseService::connect' },
283
+ 'Failed to connect to local database'
284
+ );
285
+ throw err;
286
+ }
287
+ this.logger.warn(
288
+ { err, Category: 'sp00ky-client::LocalDatabaseService::connect' },
289
+ 'Local IndexedDB store failed to open; retrying before clearing'
290
+ );
291
+ }
292
+
293
+ // Tier 1 — RETRY the SAME store WITHOUT dropping. The idb open/`use` failure
294
+ // is often transient (a not-yet-released handle from the previous page, or a
295
+ // first-open WAL-recovery race), not real corruption. Closing and reopening
296
+ // frequently succeeds — and crucially PRESERVES the cache, so a warm load
297
+ // stays warm. Dropping the store every time (the old behavior) silently wiped
298
+ // the cache on every reload, making warm loads as slow as cold ones.
299
+ for (let attempt = 1; attempt <= 2; attempt++) {
300
+ try {
301
+ await client.close();
302
+ } catch {
303
+ /* ignore */
304
+ }
305
+ await delay(150 * attempt);
306
+ try {
307
+ await this.openStore(client, storeUrl, namespace, database);
308
+ this.logger.info(
309
+ { attempt, Category: 'sp00ky-client::LocalDatabaseService::connect' },
310
+ 'Connected to local database on retry (cache preserved)'
311
+ );
312
+ return;
313
+ } catch (retryErr) {
314
+ this.logger.warn(
315
+ { err: retryErr, attempt, Category: 'sp00ky-client::LocalDatabaseService::connect' },
316
+ 'Local store retry failed'
317
+ );
318
+ }
319
+ }
320
+
321
+ // Tier 2 — the store is genuinely unopenable; drop THIS bucket and reconnect
322
+ // fresh. This loses the bucket's cache (re-syncs from the server), so it's
323
+ // the last resort before in-memory.
324
+ try {
325
+ await client.close();
326
+ } catch {
327
+ /* ignore — closing a half-open connection is best-effort */
328
+ }
329
+ await dropLocalIndexedDbStores(this.logger, bucketStoreName(bucketId));
330
+
331
+ try {
332
+ await this.openStore(client, storeUrl, namespace, database);
333
+ this.logger.info(
334
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
335
+ 'Reconnected to local database after clearing the corrupt store'
336
+ );
337
+ } catch (retryErr) {
338
+ // Last resort: run in-memory so the app still loads. No local persistence
339
+ // this session; the freshly-dropped IndexedDB is recreated cleanly next
340
+ // load, and all data re-syncs from the server regardless.
92
341
  this.logger.error(
93
- { err, Category: 'spooky-client::LocalDatabaseService::connect' },
94
- 'Failed to connect to local database'
342
+ { err: retryErr, Category: 'sp00ky-client::LocalDatabaseService::connect' },
343
+ 'Local store still failing after clear; falling back to in-memory'
344
+ );
345
+ try {
346
+ await client.close();
347
+ } catch {
348
+ /* ignore */
349
+ }
350
+ await this.openStore(client, 'mem://', namespace, database);
351
+ this.logger.warn(
352
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
353
+ 'Connected to local database (in-memory fallback)'
95
354
  );
96
- throw err;
97
355
  }
98
356
  }
357
+
358
+ private unloadCloseRegistered = false;
359
+
360
+ /**
361
+ * Close the local DB on page unload so the SurrealDB-WASM worker releases its
362
+ * IndexedDB connection cleanly. Without this, the previous page's connection
363
+ * lingers; the next load's `client.connect` opens the store but the first
364
+ * write transaction in `client.use` hits an "IndexedDB error" — which then
365
+ * (mis)triggered the corrupt-store recovery and WIPED the cache on every
366
+ * reload, making warm loads as slow as cold ones. `pagehide` is the reliable
367
+ * unload signal (fires on bfcache + normal navigation); `close()` is async but
368
+ * the WASM worker initiates the IndexedDB connection teardown synchronously.
369
+ * Also closes a mid-switch incoming client so its fresh handle doesn't linger.
370
+ */
371
+ private registerUnloadClose(): void {
372
+ if (this.unloadCloseRegistered || typeof window === 'undefined') return;
373
+ this.unloadCloseRegistered = true;
374
+ const close = () => {
375
+ try {
376
+ void this.client.close();
377
+ } catch {
378
+ /* best-effort */
379
+ }
380
+ try {
381
+ void this.pendingSwitchClient?.close();
382
+ } catch {
383
+ /* best-effort */
384
+ }
385
+ };
386
+ window.addEventListener('pagehide', close);
387
+ window.addEventListener('beforeunload', close);
388
+ }
389
+
390
+ private async openStore(
391
+ client: Surreal,
392
+ storeUrl: string,
393
+ namespace: string,
394
+ database: string
395
+ ): Promise<void> {
396
+ this.logger.debug(
397
+ { storeUrl, Category: 'sp00ky-client::LocalDatabaseService::connect' },
398
+ '[LocalDatabaseService] Calling client.connect'
399
+ );
400
+ await client.connect(storeUrl, {});
401
+ this.logger.debug(
402
+ { namespace, database, Category: 'sp00ky-client::LocalDatabaseService::connect' },
403
+ '[LocalDatabaseService] client.connect returned. Calling client.use'
404
+ );
405
+ await client.use({ namespace, database });
406
+ this.logger.debug(
407
+ { Category: 'sp00ky-client::LocalDatabaseService::connect' },
408
+ '[LocalDatabaseService] client.use returned'
409
+ );
410
+ }
411
+ }
412
+
413
+ function delay(ms: number): Promise<void> {
414
+ return new Promise((resolve) => setTimeout(resolve, ms));
415
+ }
416
+
417
+ /** True for the SurrealDB-WASM error raised when its IndexedDB-backed key-value
418
+ * store can't be opened (corrupt / version-incompatible / blocked). Exported
419
+ * for unit testing the error-message match. */
420
+ export function isLocalStoreOpenError(err: unknown): boolean {
421
+ const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
422
+ return (
423
+ msg.includes('indexeddb') ||
424
+ msg.includes('idb error') ||
425
+ msg.includes('key-value store')
426
+ );
427
+ }
428
+
429
+ /** Best-effort delete of ONE bucket's IndexedDB store(s). SurrealDB-WASM backs
430
+ * `indxdb://<name>` with one or more IndexedDB databases whose names include
431
+ * `<name>`. Scoped to the given store name — never wipe by the bare `sp00ky`
432
+ * substring, that would take every user's bucket (and their un-pushed mutation
433
+ * outboxes) down with one corrupt store. Resolves even on error/blocked so
434
+ * startup can proceed. No-op outside a browser. Exported for unit tests. */
435
+ export async function dropLocalIndexedDbStores(logger: Logger, storeName: string): Promise<void> {
436
+ if (typeof indexedDB === 'undefined') return;
437
+ try {
438
+ let names: string[] = [];
439
+ if (typeof indexedDB.databases === 'function') {
440
+ const dbs = await indexedDB.databases();
441
+ names = dbs
442
+ .map((d) => d.name)
443
+ .filter((n): n is string => !!n && matchesBucketStore(n, storeName));
444
+ }
445
+ // Fall back to the known store name if enumeration is unavailable/empty.
446
+ if (names.length === 0) names = [storeName];
447
+ await Promise.all(names.map(deleteIndexedDb));
448
+ logger.info(
449
+ { names, Category: 'sp00ky-client::LocalDatabaseService::connect' },
450
+ 'Cleared local IndexedDB store(s)'
451
+ );
452
+ } catch (e) {
453
+ logger.warn(
454
+ { err: e, Category: 'sp00ky-client::LocalDatabaseService::connect' },
455
+ 'Failed to enumerate/clear IndexedDB; proceeding anyway'
456
+ );
457
+ }
458
+ }
459
+
460
+ /** True when idb database `name` belongs to the bucket store `storeName` —
461
+ * exact match or a derived name (`<storeName>`, `<storeName>-*`, `*<storeName>*`
462
+ * with a non-alphanumeric boundary so `sp00ky-abc` never matches
463
+ * `sp00ky-abcdef`'s store). Exported for unit tests. */
464
+ export function matchesBucketStore(name: string, storeName: string): boolean {
465
+ const lower = name.toLowerCase();
466
+ const target = storeName.toLowerCase();
467
+ const idx = lower.indexOf(target);
468
+ if (idx === -1) return false;
469
+ const after = lower[idx + target.length];
470
+ return after === undefined || !/[a-z0-9_]/.test(after);
471
+ }
472
+
473
+ /** Nuke EVERY sp00ky local bucket on this device (manual full reset only —
474
+ * the automated corruption recovery is scoped to one bucket). */
475
+ export async function dropAllSp00kyIndexedDbStores(logger: Logger): Promise<void> {
476
+ if (typeof indexedDB === 'undefined') return;
477
+ try {
478
+ let names: string[] = [];
479
+ if (typeof indexedDB.databases === 'function') {
480
+ const dbs = await indexedDB.databases();
481
+ names = dbs
482
+ .map((d) => d.name)
483
+ .filter((n): n is string => !!n && n.toLowerCase().includes('sp00ky'));
484
+ }
485
+ if (names.length === 0) names = ['sp00ky'];
486
+ await Promise.all(names.map(deleteIndexedDb));
487
+ logger.info(
488
+ { names, Category: 'sp00ky-client::LocalDatabaseService::reset' },
489
+ 'Cleared ALL sp00ky IndexedDB stores'
490
+ );
491
+ } catch (e) {
492
+ logger.warn(
493
+ { err: e, Category: 'sp00ky-client::LocalDatabaseService::reset' },
494
+ 'Failed to enumerate/clear IndexedDB; proceeding anyway'
495
+ );
496
+ }
497
+ }
498
+
499
+ function deleteIndexedDb(name: string): Promise<void> {
500
+ return new Promise((resolve) => {
501
+ try {
502
+ const req = indexedDB.deleteDatabase(name);
503
+ req.onsuccess = () => resolve();
504
+ req.onerror = () => resolve();
505
+ req.onblocked = () => resolve();
506
+ } catch {
507
+ resolve();
508
+ }
509
+ });
99
510
  }