@spooky-sync/core 0.0.1-canary.9 → 0.0.1-canary.91

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 (65) hide show
  1. package/AGENTS.md +56 -0
  2. package/dist/index.d.ts +907 -339
  3. package/dist/index.js +2837 -402
  4. package/dist/otel/index.d.ts +21 -0
  5. package/dist/otel/index.js +86 -0
  6. package/dist/types.d.ts +543 -0
  7. package/package.json +39 -9
  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 +12 -0
  12. package/src/events/events.test.ts +2 -1
  13. package/src/events/index.ts +3 -0
  14. package/src/index.ts +9 -2
  15. package/src/modules/auth/events/index.ts +2 -1
  16. package/src/modules/auth/index.ts +59 -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 +732 -109
  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 +115 -21
  27. package/src/modules/devtools/versions.test.ts +74 -0
  28. package/src/modules/devtools/versions.ts +81 -0
  29. package/src/modules/feature-flag/index.ts +166 -0
  30. package/src/modules/ref-tables.test.ts +66 -0
  31. package/src/modules/ref-tables.ts +69 -0
  32. package/src/modules/sync/engine.ts +101 -37
  33. package/src/modules/sync/events/index.ts +9 -2
  34. package/src/modules/sync/queue/queue-down.ts +5 -4
  35. package/src/modules/sync/queue/queue-up.ts +14 -13
  36. package/src/modules/sync/scheduler.ts +40 -3
  37. package/src/modules/sync/sync.ts +893 -59
  38. package/src/modules/sync/utils.test.ts +269 -2
  39. package/src/modules/sync/utils.ts +182 -17
  40. package/src/otel/index.ts +127 -0
  41. package/src/services/database/database.ts +11 -11
  42. package/src/services/database/events/index.ts +2 -1
  43. package/src/services/database/local-migrator.ts +21 -21
  44. package/src/services/database/local.test.ts +33 -0
  45. package/src/services/database/local.ts +192 -32
  46. package/src/services/database/remote.ts +13 -13
  47. package/src/services/logger/index.ts +6 -101
  48. package/src/services/persistence/localstorage.ts +2 -2
  49. package/src/services/persistence/resilient.ts +41 -0
  50. package/src/services/persistence/surrealdb.ts +9 -9
  51. package/src/services/stream-processor/index.ts +248 -37
  52. package/src/services/stream-processor/permissions.test.ts +47 -0
  53. package/src/services/stream-processor/permissions.ts +53 -0
  54. package/src/services/stream-processor/stream-processor.batch.test.ts +136 -0
  55. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  56. package/src/services/stream-processor/wasm-types.ts +18 -2
  57. package/src/sp00ky.auth-order.test.ts +65 -0
  58. package/src/sp00ky.ts +648 -0
  59. package/src/types.ts +192 -15
  60. package/src/utils/index.ts +35 -13
  61. package/src/utils/parser.ts +3 -2
  62. package/src/utils/surql.ts +24 -15
  63. package/src/utils/withRetry.test.ts +1 -1
  64. package/tsdown.config.ts +55 -1
  65. package/src/spooky.ts +0 -392
@@ -0,0 +1,21 @@
1
+ import { u as PinoTransmit } from "../types.js";
2
+ import { Level } from "pino";
3
+
4
+ //#region src/otel/index.d.ts
5
+
6
+ /**
7
+ * Creates a pino browser transmit object that forwards logs to an OpenTelemetry collector.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { createOtelTransmit } from '@spooky-sync/core/otel';
12
+ *
13
+ * new Sp00kyClient({
14
+ * // ...
15
+ * otelTransmit: createOtelTransmit('http://localhost:4318/v1/logs'),
16
+ * });
17
+ * ```
18
+ */
19
+ declare function createOtelTransmit(endpoint: string, level?: Level): PinoTransmit;
20
+ //#endregion
21
+ export { createOtelTransmit };
@@ -0,0 +1,86 @@
1
+ //#region src/otel/index.ts
2
+ function mapLevelToSeverityNumber(level) {
3
+ switch (level) {
4
+ case "trace": return 1;
5
+ case "debug": return 5;
6
+ case "info": return 9;
7
+ case "warn": return 13;
8
+ case "error": return 17;
9
+ case "fatal": return 21;
10
+ default: return 9;
11
+ }
12
+ }
13
+ async function loadOtelModules(otelEndpoint) {
14
+ const [{ LoggerProvider, BatchLogRecordProcessor }, { OTLPLogExporter }, { resourceFromAttributes }, { ATTR_SERVICE_NAME }] = await Promise.all([
15
+ import("@opentelemetry/sdk-logs"),
16
+ import("@opentelemetry/exporter-logs-otlp-proto"),
17
+ import("@opentelemetry/resources"),
18
+ import("@opentelemetry/semantic-conventions")
19
+ ]);
20
+ const loggerProvider = new LoggerProvider({
21
+ resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: "sp00ky-client" }),
22
+ processors: [new BatchLogRecordProcessor(new OTLPLogExporter({ url: otelEndpoint }))]
23
+ });
24
+ const otelLoggerCache = {};
25
+ return (category) => {
26
+ if (!otelLoggerCache[category]) otelLoggerCache[category] = loggerProvider.getLogger(category);
27
+ return otelLoggerCache[category];
28
+ };
29
+ }
30
+ /**
31
+ * Creates a pino browser transmit object that forwards logs to an OpenTelemetry collector.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * import { createOtelTransmit } from '@spooky-sync/core/otel';
36
+ *
37
+ * new Sp00kyClient({
38
+ * // ...
39
+ * otelTransmit: createOtelTransmit('http://localhost:4318/v1/logs'),
40
+ * });
41
+ * ```
42
+ */
43
+ function createOtelTransmit(endpoint, level = "info") {
44
+ const otelReady = loadOtelModules(endpoint);
45
+ return {
46
+ level,
47
+ send: (levelLabel, logEvent) => {
48
+ otelReady.then((getOtelLogger) => {
49
+ try {
50
+ const messages = [...logEvent.messages];
51
+ const severityNumber = mapLevelToSeverityNumber(levelLabel);
52
+ let body = "";
53
+ const lastMsg = messages.pop();
54
+ if (typeof lastMsg === "string") body = lastMsg;
55
+ else if (lastMsg) body = JSON.stringify(lastMsg);
56
+ let category = "sp00ky-client::unknown";
57
+ const attributes = {};
58
+ for (const msg of messages) if (typeof msg === "object") {
59
+ if (msg.Category) {
60
+ category = msg.Category;
61
+ delete msg.Category;
62
+ }
63
+ Object.assign(attributes, msg);
64
+ }
65
+ getOtelLogger(category).emit({
66
+ severityNumber,
67
+ severityText: levelLabel.toUpperCase(),
68
+ body,
69
+ attributes: {
70
+ ...logEvent.bindings[0],
71
+ ...attributes
72
+ },
73
+ timestamp: new Date(logEvent.ts)
74
+ });
75
+ } catch (e) {
76
+ console.warn("Failed to transmit log to OTEL endpoint", e);
77
+ }
78
+ }).catch((e) => {
79
+ console.warn("Failed to load OpenTelemetry modules", e);
80
+ });
81
+ }
82
+ };
83
+ }
84
+
85
+ //#endregion
86
+ export { createOtelTransmit };
@@ -0,0 +1,543 @@
1
+ import { RecordId } from "surrealdb";
2
+ import { RecordId as RecordId$1, SchemaStructure } from "@spooky-sync/query-builder";
3
+ import { Level, Level as Level$1, Logger, LoggerOptions } from "pino";
4
+
5
+ //#region src/events/index.d.ts
6
+ /**
7
+ * Utility type to define the payload structure of an event.
8
+ * If the payload type P is never, it defines payload as undefined.
9
+ */
10
+ type EventPayloadDefinition<P> = [P] extends [never] ? {
11
+ payload: undefined;
12
+ } : {
13
+ payload: P;
14
+ };
15
+ /**
16
+ * Defines the structure of an event with a specific type and payload.
17
+ * @template T The string literal type of the event.
18
+ * @template P The type of the event payload.
19
+ */
20
+ type EventDefinition<T extends string, P> = {
21
+ type: T;
22
+ } & EventPayloadDefinition<P>;
23
+ /**
24
+ * A map of event types to their definitions.
25
+ * Keys are event names, values are EventDefinitions.
26
+ */
27
+ type EventTypeMap = Record<string, EventDefinition<any, unknown> | EventDefinition<any, never>>;
28
+ /**
29
+ * Options for pushing/emitting events.
30
+ */
31
+ interface PushEventOptions {
32
+ /** Configuration for debouncing the event. */
33
+ debounced?: {
34
+ key: string;
35
+ delay: number;
36
+ };
37
+ }
38
+ /**
39
+ * Extracts the full Event object type from the map for a given key.
40
+ */
41
+ type Event<E extends EventTypeMap, T extends EventType<E>> = E[T];
42
+ /**
43
+ * Extracts the payload type from the map for a given key.
44
+ */
45
+ type EventPayload<E extends EventTypeMap, T extends EventType<E>> = E[T]['payload'];
46
+ /**
47
+ * Array of available event type keys.
48
+ */
49
+ type EventTypes<E extends EventTypeMap> = (keyof E)[];
50
+ /**
51
+ * Represents a valid key (event name) from the EventTypeMap.
52
+ */
53
+ type EventType<E extends EventTypeMap> = keyof E;
54
+ /**
55
+ * Function signature for an event handler.
56
+ */
57
+ type EventHandler<E extends EventTypeMap, T extends EventType<E>> = (event: Event<E, T>) => void;
58
+ /**
59
+ * Options when subscribing to an event.
60
+ */
61
+ type EventSubscriptionOptions$1 = {
62
+ /** If true, the handler will be called immediately with the last emitted event of this type (if any). */
63
+ immediately?: boolean;
64
+ /** If true, the subscription will be automatically removed after the first event is handled. */
65
+ once?: boolean;
66
+ };
67
+ /**
68
+ * A type-safe event system that handles subscription, emission (including debouncing), and buffering of events.
69
+ * @template E The EventTypeMap defining all supported events.
70
+ */
71
+ declare class EventSystem<E extends EventTypeMap> {
72
+ private _eventTypes;
73
+ private subscriberId;
74
+ private isProcessing;
75
+ private buffer;
76
+ private subscribers;
77
+ private subscribersTypeMap;
78
+ private lastEvents;
79
+ private debouncedEvents;
80
+ constructor(_eventTypes: EventTypes<E>);
81
+ get eventTypes(): EventTypes<E>;
82
+ /**
83
+ * Subscribes a handler to a specific event type.
84
+ * @param type The event type to subscribe to.
85
+ * @param handler The function to call when the event occurs.
86
+ * @param options Subscription options (once, immediately).
87
+ * @returns A subscription ID that can be used to unsubscribe.
88
+ */
89
+ subscribe<T extends EventType<E>>(type: T, handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number;
90
+ /**
91
+ * Subscribes a handler to multiple event types.
92
+ * @param types An array of event types to subscribe to.
93
+ * @param handler The function to call when any of the events occur.
94
+ * @param options Subscription options.
95
+ * @returns An array of subscription IDs.
96
+ */
97
+ subscribeMany<T extends EventType<E>>(types: T[], handler: EventHandler<E, T>, options?: EventSubscriptionOptions$1): number[];
98
+ /**
99
+ * Unsubscribes a specific subscription by ID.
100
+ * @param id The subscription ID returned by subscribe().
101
+ * @returns True if the subscription was found and removed, false otherwise.
102
+ */
103
+ unsubscribe(id: number): boolean;
104
+ /**
105
+ * Emits an event with the given type and payload.
106
+ * @param type The type of event to emit.
107
+ * @param payload The data associated with the event.
108
+ */
109
+ emit<T extends EventType<E>, P extends EventPayload<E, T>>(type: T, payload: P): void;
110
+ /**
111
+ * Adds a fully constructed event object to the system.
112
+ * Similar to emit, but takes the full event object directly.
113
+ * Supports debouncing if options are provided.
114
+ * @param event The event object.
115
+ * @param options Options for the event push (e.g., debouncing).
116
+ */
117
+ addEvent<T extends EventType<E>>(event: Event<E, T>, options?: PushEventOptions): void;
118
+ private handleDebouncedEvent;
119
+ private scheduleProcessing;
120
+ private processEvents;
121
+ private dequeue;
122
+ private setLastEvent;
123
+ private broadcastEvent;
124
+ }
125
+ //#endregion
126
+ //#region src/modules/sync/events/index.d.ts
127
+ declare const SyncEventTypes: {
128
+ readonly QueryUpdated: "SYNC_QUERY_UPDATED";
129
+ readonly RemoteDataIngested: "SYNC_REMOTE_DATA_INGESTED";
130
+ readonly MutationRolledBack: "SYNC_MUTATION_ROLLED_BACK";
131
+ readonly SyncHealthChanged: "SYNC_HEALTH_CHANGED";
132
+ };
133
+ type SyncEventTypeMap = {
134
+ [SyncEventTypes.QueryUpdated]: EventDefinition<typeof SyncEventTypes.QueryUpdated, {
135
+ queryId: any;
136
+ localHash?: string;
137
+ localArray?: RecordVersionArray;
138
+ remoteHash?: string;
139
+ remoteArray?: RecordVersionArray;
140
+ records: Record<string, any>[];
141
+ }>;
142
+ [SyncEventTypes.RemoteDataIngested]: EventDefinition<typeof SyncEventTypes.RemoteDataIngested, {
143
+ records: Record<string, any>[];
144
+ }>;
145
+ [SyncEventTypes.MutationRolledBack]: EventDefinition<typeof SyncEventTypes.MutationRolledBack, {
146
+ eventType: string;
147
+ recordId: string;
148
+ error: string;
149
+ }>;
150
+ [SyncEventTypes.SyncHealthChanged]: EventDefinition<typeof SyncEventTypes.SyncHealthChanged, SyncHealth>;
151
+ };
152
+ type SyncEventSystem = EventSystem<SyncEventTypeMap>;
153
+ //#endregion
154
+ //#region src/services/logger/index.d.ts
155
+ type Logger$1 = Logger;
156
+ //#endregion
157
+ //#region src/modules/sync/queue/queue-up.d.ts
158
+ type CreateEvent = {
159
+ type: 'create';
160
+ mutation_id: RecordId;
161
+ record_id: RecordId;
162
+ data: Record<string, unknown>;
163
+ record?: Record<string, unknown>;
164
+ tableName?: string;
165
+ options?: PushEventOptions;
166
+ };
167
+ type UpdateEvent = {
168
+ type: 'update';
169
+ mutation_id: RecordId;
170
+ record_id: RecordId;
171
+ data: Record<string, unknown>;
172
+ record?: Record<string, unknown>;
173
+ beforeRecord?: Record<string, unknown>;
174
+ options?: PushEventOptions;
175
+ };
176
+ type DeleteEvent = {
177
+ type: 'delete';
178
+ mutation_id: RecordId;
179
+ record_id: RecordId;
180
+ options?: PushEventOptions;
181
+ };
182
+ type UpEvent = CreateEvent | UpdateEvent | DeleteEvent;
183
+ //#endregion
184
+ //#region src/types.d.ts
185
+ /**
186
+ * A pino browser transmit object for forwarding logs to an external sink (e.g. OpenTelemetry).
187
+ */
188
+ type PinoTransmit = NonNullable<NonNullable<LoggerOptions['browser']>['transmit']>;
189
+ /**
190
+ * The type of storage backend to use for the local database.
191
+ * - 'memory': In-memory storage (transient).
192
+ * - 'indexeddb': IndexedDB storage (persistent).
193
+ */
194
+ type StoreType = 'memory' | 'indexeddb';
195
+ /**
196
+ * Interface for a custom persistence client.
197
+ * Allows providing a custom storage mechanism for the local database.
198
+ */
199
+ interface PersistenceClient {
200
+ /**
201
+ * Sets a value in the storage.
202
+ * @param key The key to set.
203
+ * @param value The value to store.
204
+ */
205
+ set<T>(key: string, value: T): Promise<void>;
206
+ /**
207
+ * Gets a value from the storage.
208
+ * @param key The key to retrieve.
209
+ * @returns The stored value or null if not found.
210
+ */
211
+ get<T>(key: string): Promise<T | null>;
212
+ /**
213
+ * Removes a value from the storage.
214
+ * @param key The key to remove.
215
+ */
216
+ remove(key: string): Promise<void>;
217
+ }
218
+ /**
219
+ * Supported Time-To-Live (TTL) values for cached queries.
220
+ * Format: number + unit (m=minutes, h=hours, d=days).
221
+ */
222
+ type QueryTimeToLive = '1m' | '5m' | '10m' | '15m' | '20m' | '25m' | '30m' | '1h' | '2h' | '3h' | '4h' | '5h' | '6h' | '7h' | '8h' | '9h' | '10h' | '11h' | '12h' | '1d';
223
+ /**
224
+ * Result object returned when a query is registered or executed.
225
+ */
226
+ interface Sp00kyQueryResult {
227
+ /** The unique hash identifier for the query. */
228
+ hash: string;
229
+ }
230
+ type Sp00kyQueryResultPromise = Promise<Sp00kyQueryResult>;
231
+ interface EventSubscriptionOptions {
232
+ priority?: number;
233
+ }
234
+ /**
235
+ * Configuration options for the Sp00ky client.
236
+ * @template S The schema structure type.
237
+ */
238
+ interface Sp00kyConfig<S extends SchemaStructure> {
239
+ /** Database connection configuration. */
240
+ database: {
241
+ /** The SurrealDB endpoint URL. */
242
+ endpoint?: string;
243
+ /** The namespace to use. */
244
+ namespace: string;
245
+ /** The database name. */
246
+ database: string;
247
+ /** The local store type implementation. */
248
+ store?: StoreType;
249
+ /** Authentication token. */
250
+ token?: string;
251
+ };
252
+ /** The schema definition. */
253
+ schema: S;
254
+ /** The compiled SURQL schema string. */
255
+ schemaSurql: string;
256
+ /** Logging level. */
257
+ logLevel: Level$1;
258
+ /**
259
+ * Persistence client to use.
260
+ * Can be a custom implementation, 'surrealdb' (default), or 'localstorage'.
261
+ */
262
+ persistenceClient?: PersistenceClient | 'surrealdb' | 'localstorage';
263
+ /** A pino browser transmit object for forwarding logs (e.g. via @spooky-sync/core/otel). */
264
+ otelTransmit?: PinoTransmit;
265
+ /**
266
+ * Debounce time in milliseconds for stream updates (the client-side SSP
267
+ * aggregation throttle — coalesces the in-browser StreamProcessor's
268
+ * per-record updates per query before notifying readers).
269
+ * Defaults to 50ms.
270
+ */
271
+ streamDebounceTime?: number;
272
+ /**
273
+ * Debounce time in milliseconds for syncing collaborative (CRDT) field
274
+ * changes to the remote database. Local writes happen immediately on
275
+ * every keystroke (so reload/offline works), but the remote UPSERT is
276
+ * coalesced over this window. Lower = snappier remote propagation +
277
+ * more network traffic; higher = less traffic + more lag for other
278
+ * collaborators. Defaults to 500ms.
279
+ */
280
+ crdtDebounceMs?: number;
281
+ /**
282
+ * Cadence (ms) for the `_00_list_ref` poll that catches cross-session
283
+ * UPDATEs the SurrealDB v3 LIVE-permission gap drops. Lower = faster
284
+ * convergence + more query load; higher = the inverse. Non-positive
285
+ * values fall back to the default (500ms).
286
+ */
287
+ refSyncIntervalMs?: number;
288
+ /**
289
+ * Instant-hydrate cold queries: when a query is registered with no local
290
+ * data yet, first run its surql directly on the remote (one-shot) and display
291
+ * the result immediately, THEN do the full realtime registration in the
292
+ * background. The hydrated rows are ingested with their versions so the
293
+ * registration's `syncRecords` skips re-pulling unchanged bodies. Cuts cold
294
+ * first-paint from ~one full registration round-trip to ~one query.
295
+ * Defaults to `true`; set `false` to keep the old wait-for-registration path.
296
+ */
297
+ instantHydrate?: boolean;
298
+ /**
299
+ * Enable realtime sync while signed out. When `true`, the client starts its
300
+ * `_00_list_ref` poll (and a LIVE subscription) against the shared
301
+ * `_00_list_ref_anon` table even with no authenticated user, so a logged-out
302
+ * page gets live `useQuery` updates over world-readable tables. Requires the
303
+ * server to be deployed with `anonymousLiveQueries: true` in `sp00ky.yml`
304
+ * (this flag must match it). Defaults to `false`: anonymous clients can read
305
+ * one-shot but never sync live.
306
+ */
307
+ enableAnonymousLiveQueries?: boolean;
308
+ /**
309
+ * Surface sustained sync failures as a "degraded" health status that the app
310
+ * can observe via `subscribeToSyncHealth` (or the client-solid
311
+ * `useSyncStatus` hook) to render a "can't reach the server" banner.
312
+ *
313
+ * Individual failures — a transient remote 500 on query registration, a
314
+ * dropped WebSocket, etc. — are always swallowed and retried; they never
315
+ * throw at the app. This only controls when a *run* of consecutive failures
316
+ * is reported. Status flips back to `healthy` on the next successful sync
317
+ * round. Defaults to `{ degradeAfterConsecutiveFailures: 3 }`; pass `false`
318
+ * (or `degradeAfterConsecutiveFailures: 0`) to never report degraded.
319
+ */
320
+ syncHealth?: SyncHealthConfig | false;
321
+ }
322
+ /** Tunables for sync-health reporting. See {@link Sp00kyConfig.syncHealth}. */
323
+ interface SyncHealthConfig {
324
+ /**
325
+ * Number of consecutive failed sync rounds (up or down) before the status
326
+ * flips from `healthy` to `degraded`. A single transient failure is absorbed
327
+ * by the retry; only a sustained run trips the banner. Defaults to `3`. `0`
328
+ * disables degraded reporting entirely.
329
+ */
330
+ degradeAfterConsecutiveFailures?: number;
331
+ }
332
+ type SyncHealthStatus = 'healthy' | 'degraded';
333
+ /** Snapshot of sync health delivered to `subscribeToSyncHealth` subscribers. */
334
+ interface SyncHealth {
335
+ /** `'degraded'` once consecutive failures cross the configured threshold. */
336
+ status: SyncHealthStatus;
337
+ /** Consecutive failed sync rounds at the moment of this report. */
338
+ consecutiveFailures: number;
339
+ /** Classification of the most recent failure (only set while `degraded`). */
340
+ kind?: 'network' | 'application';
341
+ /** Message of the most recent failure (only set while `degraded`). */
342
+ error?: string;
343
+ }
344
+ type QueryHash = string;
345
+ type RecordVersionArray = Array<[string, number]>;
346
+ /**
347
+ * Represents the difference between two record version sets.
348
+ * Used for synchronizing local and remote states.
349
+ */
350
+ interface RecordVersionDiff {
351
+ /** List of records added. */
352
+ added: Array<{
353
+ id: RecordId$1<string>;
354
+ version: number;
355
+ }>;
356
+ /** List of records updated. */
357
+ updated: Array<{
358
+ id: RecordId$1<string>;
359
+ version: number;
360
+ }>;
361
+ /** List of record IDs removed. */
362
+ removed: RecordId$1<string>[];
363
+ }
364
+ /**
365
+ * Configuration for a specific query instance.
366
+ * Stores metadata about the query's state, parameters, and versioning.
367
+ */
368
+ interface QueryConfig {
369
+ /** The unique ID of the query config record. */
370
+ id: RecordId$1<string>;
371
+ /** The SURQL query string. */
372
+ surql: string;
373
+ /** Parameters used in the query. */
374
+ params: Record<string, any>;
375
+ /** The version array representing the local state of results. */
376
+ localArray: RecordVersionArray;
377
+ /** The version array representing the remote (server) state of results. */
378
+ remoteArray: RecordVersionArray;
379
+ /**
380
+ * In-memory only (never persisted to `_00_query`): version array of the
381
+ * subquery CHILD rows pulled via `parent IS NOT NONE` edges, so the
382
+ * child-body sync is idempotent across polls. Kept separate from
383
+ * `remoteArray` so related child rows never enter the primary window /
384
+ * `rowCount` / `localArray`.
385
+ */
386
+ subqueryRemoteArray?: RecordVersionArray;
387
+ /** Time-To-Live for this query. */
388
+ ttl: QueryTimeToLive;
389
+ /** Timestamp when the query was last accessed/active. */
390
+ lastActiveAt: Date;
391
+ /** The name of the table this query targets (if applicable). */
392
+ tableName: string;
393
+ }
394
+ type QueryConfigRecord = QueryConfig & {
395
+ id: string;
396
+ };
397
+ /**
398
+ * Runtime fetch status of a live query.
399
+ * - `idle`: not currently fetching missing records.
400
+ * - `fetching`: the sync engine is fetching/ingesting missing records for this
401
+ * query. UI notifications are coalesced so the result lands as a single
402
+ * update once fetching completes.
403
+ */
404
+ type QueryStatus = 'idle' | 'fetching';
405
+ /**
406
+ * Internal state of a live query.
407
+ */
408
+ interface QueryState {
409
+ /** The configuration for this query. */
410
+ config: QueryConfig;
411
+ /** The current cached records for this query. */
412
+ records: Record<string, any>[];
413
+ /** Set once `applyHydration` has run for this query, so the cold instant-hydrate
414
+ * path fires at most once per query (see DataModule.isCold/applyHydration). */
415
+ hydrated?: boolean;
416
+ /** Timer for TTL expiration. */
417
+ ttlTimer: NodeJS.Timeout | null;
418
+ /** TTL duration in milliseconds. */
419
+ ttlDurationMs: number;
420
+ /** Number of times the query has been updated. */
421
+ updateCount: number;
422
+ /**
423
+ * Rolling window of the most recent materialization-step latencies (ms).
424
+ * Capped at MATERIALIZATION_SAMPLE_WINDOW; used to recompute p55/p90/p99
425
+ * before each persist to `_00_query`. Samples themselves are not persisted.
426
+ */
427
+ materializationSamples: number[];
428
+ /** Most recent end-to-end ingest latency in ms, or null until the first ingest. */
429
+ lastIngestLatencyMs: number | null;
430
+ /** Cumulative count of ingest/materialization errors observed for this query. */
431
+ errorCount: number;
432
+ /**
433
+ * Ephemeral runtime fetch status. Not persisted to `_00_query`; observable
434
+ * via DevTools and the `useQuery` hook. `fetching` while the sync engine is
435
+ * pulling missing records for this query, otherwise `idle`.
436
+ */
437
+ status: QueryStatus;
438
+ /**
439
+ * Rolling per-phase timing samples (ms), in addition to `materializationSamples`
440
+ * (which holds the SSP whole-ingest wall time). Keyed by `TimingPhase` minus
441
+ * `ssp`. Not persisted — surfaced live to DevTools + MCP via `phaseTimings`.
442
+ */
443
+ phaseSamples: Record<string, number[]>;
444
+ /** Most recent sample (ms) per phase, or null. */
445
+ phaseLast: Record<string, number | null>;
446
+ /** One-shot SSP registration timings (ms). */
447
+ registrationTimings: RegistrationTimings;
448
+ }
449
+ /** Cap on the rolling materialization-sample window kept per query in memory. */
450
+ declare const MATERIALIZATION_SAMPLE_WINDOW = 100;
451
+ /** Timed processing phases surfaced per query. `ssp` is the WASM-ingest wall
452
+ * time; the `ssp*` phases are its internal breakdown from the SSP binding. */
453
+ type TimingPhase = 'ssp' | 'sspStoreApply' | 'sspCircuitStep' | 'sspTransform' | 'localFetch' | 'remoteFetch' | 'frontend';
454
+ /** One-shot registration timings (ms), captured once when a query registers. */
455
+ interface RegistrationTimings {
456
+ /** SSP surql→plan parse + permission injection. */
457
+ parseMs: number | null;
458
+ /** SSP operator-DAG build. */
459
+ planMs: number | null;
460
+ /** SSP initial snapshot evaluation. */
461
+ snapshotMs: number | null;
462
+ /** Wall time of `cache.registerQuery` (register_view round-trip). */
463
+ wallMs: number | null;
464
+ }
465
+ /** Percentile summary for one timed phase, surfaced to DevTools + MCP. */
466
+ interface PhaseStat {
467
+ lastMs: number | null;
468
+ p50: number | null;
469
+ p90: number | null;
470
+ p99: number | null;
471
+ count: number;
472
+ }
473
+ /** Per-query processing-time breakdown surfaced via DevTools panel + MCP. */
474
+ interface QueryTimings {
475
+ ssp: PhaseStat;
476
+ sspStoreApply: PhaseStat;
477
+ sspCircuitStep: PhaseStat;
478
+ sspTransform: PhaseStat;
479
+ localFetch: PhaseStat;
480
+ remoteFetch: PhaseStat;
481
+ frontend: PhaseStat;
482
+ registration: RegistrationTimings;
483
+ updateCount: number;
484
+ errorCount: number;
485
+ }
486
+ type QueryUpdateCallback = (records: Record<string, any>[]) => void;
487
+ type QueryStatusCallback = (status: QueryStatus) => void;
488
+ type MutationCallback = (mutations: UpEvent[]) => void;
489
+ type MutationEventType = 'create' | 'update' | 'delete';
490
+ /**
491
+ * Represents a mutation event (create, update, delete) to be synchronized.
492
+ */
493
+ interface MutationEvent {
494
+ /** Example: 'create', 'update', or 'delete'. */
495
+ type: MutationEventType;
496
+ /** unique id of the mutation */
497
+ mutation_id: RecordId$1<string>;
498
+ /** The ID of the record being mutated. */
499
+ record_id: RecordId$1<string>;
500
+ /** The data payload for create/update operations. */
501
+ data?: any;
502
+ /** The full record data (optional context). */
503
+ record?: any;
504
+ /** Options for the mutation event (e.g., debounce settings). */
505
+ options?: PushEventOptions;
506
+ /** Timestamp when the event was created. */
507
+ createdAt: Date;
508
+ }
509
+ /**
510
+ * Options for run operations.
511
+ */
512
+ interface RunOptions {
513
+ assignedTo?: string;
514
+ max_retries?: number;
515
+ retry_strategy?: 'linear' | 'exponential';
516
+ /** Timeout in seconds for the backend HTTP call. Only used if the backend allows timeout override. */
517
+ timeout?: number;
518
+ }
519
+ /**
520
+ * Options for update operations.
521
+ */
522
+ interface UpdateOptions {
523
+ /**
524
+ * Debounce configuration for the update.
525
+ * If boolean, enables default debounce behavior.
526
+ */
527
+ debounced?: boolean | DebounceOptions;
528
+ }
529
+ /**
530
+ * Configuration options for debouncing updates.
531
+ */
532
+ interface DebounceOptions {
533
+ /**
534
+ * The key to use for debouncing.
535
+ * - 'recordId': Debounce based on the specific record ID. WARNING: IT WILL ONLY ACCEPT THE LATEST CHANGE AND DOES *NOT* MERGE THE PREVIOUS ONCES. IF YOU ARE UNSURE JUST USE 'recordId_x_fields'.
536
+ * - 'recordId_x_fields': Debounce based on record ID and specific fields.
537
+ */
538
+ key?: 'recordId' | 'recordId_x_fields';
539
+ /** The debounce delay in milliseconds. */
540
+ delay?: number;
541
+ }
542
+ //#endregion
543
+ export { SyncHealthStatus as A, RunOptions as C, StoreType as D, Sp00kyQueryResultPromise as E, SyncEventSystem as F, EventDefinition as I, EventSystem as L, UpdateOptions as M, UpEvent as N, SyncHealth as O, Logger$1 as P, RegistrationTimings as S, Sp00kyQueryResult as T, QueryTimeToLive as _, MutationCallback as a, RecordVersionArray as b, PersistenceClient as c, QueryConfig as d, QueryConfigRecord as f, QueryStatusCallback as g, QueryStatus as h, MATERIALIZATION_SAMPLE_WINDOW as i, TimingPhase as j, SyncHealthConfig as k, PhaseStat as l, QueryState as m, EventSubscriptionOptions as n, MutationEvent as o, QueryHash as p, Level$1 as r, MutationEventType as s, DebounceOptions as t, PinoTransmit as u, QueryTimings as v, Sp00kyConfig as w, RecordVersionDiff as x, QueryUpdateCallback as y };