@syncular/client 0.1.3 → 0.2.0

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 (233) hide show
  1. package/README.md +227 -709
  2. package/dist/apply.d.ts +80 -0
  3. package/dist/apply.js +301 -0
  4. package/dist/blob.d.ts +127 -0
  5. package/dist/blob.js +201 -0
  6. package/dist/bun-database.d.ts +22 -0
  7. package/dist/bun-database.js +61 -0
  8. package/dist/client.d.ts +320 -69
  9. package/dist/client.js +1627 -163
  10. package/dist/content-type.d.ts +2 -0
  11. package/dist/content-type.js +2 -0
  12. package/dist/database.d.ts +35 -80
  13. package/dist/database.js +32 -947
  14. package/dist/encryption.d.ts +47 -0
  15. package/dist/encryption.js +75 -0
  16. package/dist/errors.d.ts +8 -22
  17. package/dist/errors.js +10 -207
  18. package/dist/http.d.ts +32 -0
  19. package/dist/http.js +196 -0
  20. package/dist/index.d.ts +28 -16
  21. package/dist/index.js +25 -12
  22. package/dist/invalidation.d.ts +69 -0
  23. package/dist/invalidation.js +84 -0
  24. package/dist/leader-lock.d.ts +28 -0
  25. package/dist/leader-lock.js +38 -0
  26. package/dist/multi-tab.d.ts +134 -0
  27. package/dist/multi-tab.js +399 -0
  28. package/dist/node-database.d.ts +41 -0
  29. package/dist/node-database.js +133 -0
  30. package/dist/outbox.d.ts +56 -0
  31. package/dist/outbox.js +140 -0
  32. package/dist/schema.d.ts +107 -0
  33. package/dist/schema.js +267 -0
  34. package/dist/state.d.ts +40 -0
  35. package/dist/state.js +77 -0
  36. package/dist/transport.d.ts +44 -0
  37. package/dist/transport.js +7 -0
  38. package/dist/wasm-database.d.ts +30 -0
  39. package/dist/wasm-database.js +170 -0
  40. package/dist/window.d.ts +64 -0
  41. package/dist/window.js +0 -0
  42. package/dist/worker-entry.d.ts +16 -2
  43. package/dist/worker-entry.js +300 -456
  44. package/dist/worker-host.d.ts +174 -0
  45. package/dist/worker-host.js +536 -0
  46. package/dist/worker-protocol.d.ts +173 -61
  47. package/dist/worker-protocol.js +7 -16
  48. package/package.json +45 -112
  49. package/src/apply.ts +435 -0
  50. package/src/blob.ts +333 -0
  51. package/src/bun-database.ts +75 -0
  52. package/src/client.ts +2247 -277
  53. package/src/content-type.ts +2 -0
  54. package/src/database.ts +63 -1389
  55. package/src/encryption.ts +123 -0
  56. package/src/errors.ts +11 -265
  57. package/src/http.ts +254 -0
  58. package/src/index.ts +25 -20
  59. package/src/invalidation.ts +128 -0
  60. package/src/leader-lock.ts +68 -0
  61. package/src/multi-tab.ts +550 -0
  62. package/src/node-database.ts +180 -0
  63. package/src/outbox.ts +206 -0
  64. package/src/schema.ts +397 -0
  65. package/src/state.ts +126 -0
  66. package/src/transport.ts +52 -0
  67. package/src/wasm-database.ts +279 -0
  68. package/src/window.ts +0 -0
  69. package/src/worker-entry.ts +391 -545
  70. package/src/worker-host.ts +800 -0
  71. package/src/worker-protocol.ts +204 -99
  72. package/dist/auth-leases.d.ts +0 -11
  73. package/dist/auth-leases.d.ts.map +0 -1
  74. package/dist/auth-leases.js +0 -140
  75. package/dist/auth-leases.js.map +0 -1
  76. package/dist/blob-limits.d.ts +0 -15
  77. package/dist/blob-limits.d.ts.map +0 -1
  78. package/dist/blob-limits.js +0 -66
  79. package/dist/blob-limits.js.map +0 -1
  80. package/dist/bridge-client.d.ts +0 -69
  81. package/dist/bridge-client.d.ts.map +0 -1
  82. package/dist/bridge-client.js +0 -282
  83. package/dist/bridge-client.js.map +0 -1
  84. package/dist/client-config.d.ts +0 -6
  85. package/dist/client-config.d.ts.map +0 -1
  86. package/dist/client-config.js +0 -18
  87. package/dist/client-config.js.map +0 -1
  88. package/dist/client.d.ts.map +0 -1
  89. package/dist/client.js.map +0 -1
  90. package/dist/command-history.d.ts +0 -35
  91. package/dist/command-history.d.ts.map +0 -1
  92. package/dist/command-history.js +0 -378
  93. package/dist/command-history.js.map +0 -1
  94. package/dist/console-diagnostics.d.ts +0 -33
  95. package/dist/console-diagnostics.d.ts.map +0 -1
  96. package/dist/console-diagnostics.js +0 -496
  97. package/dist/console-diagnostics.js.map +0 -1
  98. package/dist/crdt-yjs/index.d.ts +0 -4
  99. package/dist/crdt-yjs/index.d.ts.map +0 -1
  100. package/dist/crdt-yjs/index.js +0 -4
  101. package/dist/crdt-yjs/index.js.map +0 -1
  102. package/dist/crdt-yjs/webview-host-facade.d.ts +0 -126
  103. package/dist/crdt-yjs/webview-host-facade.d.ts.map +0 -1
  104. package/dist/crdt-yjs/webview-host-facade.js +0 -284
  105. package/dist/crdt-yjs/webview-host-facade.js.map +0 -1
  106. package/dist/crdt-yjs/yjs-document-field-adapter.d.ts +0 -153
  107. package/dist/crdt-yjs/yjs-document-field-adapter.d.ts.map +0 -1
  108. package/dist/crdt-yjs/yjs-document-field-adapter.js +0 -406
  109. package/dist/crdt-yjs/yjs-document-field-adapter.js.map +0 -1
  110. package/dist/crdt-yjs/yjs-prosemirror-bridge.d.ts +0 -73
  111. package/dist/crdt-yjs/yjs-prosemirror-bridge.d.ts.map +0 -1
  112. package/dist/crdt-yjs/yjs-prosemirror-bridge.js +0 -169
  113. package/dist/crdt-yjs/yjs-prosemirror-bridge.js.map +0 -1
  114. package/dist/database.d.ts.map +0 -1
  115. package/dist/database.js.map +0 -1
  116. package/dist/diagnostics.d.ts +0 -10
  117. package/dist/diagnostics.d.ts.map +0 -1
  118. package/dist/diagnostics.js +0 -83
  119. package/dist/diagnostics.js.map +0 -1
  120. package/dist/errors.d.ts.map +0 -1
  121. package/dist/errors.js.map +0 -1
  122. package/dist/generated-bridge.d.ts +0 -365
  123. package/dist/generated-bridge.d.ts.map +0 -1
  124. package/dist/generated-bridge.js +0 -250
  125. package/dist/generated-bridge.js.map +0 -1
  126. package/dist/index.d.ts.map +0 -1
  127. package/dist/index.js.map +0 -1
  128. package/dist/mutations.d.ts +0 -72
  129. package/dist/mutations.d.ts.map +0 -1
  130. package/dist/mutations.js +0 -63
  131. package/dist/mutations.js.map +0 -1
  132. package/dist/network.d.ts +0 -3
  133. package/dist/network.d.ts.map +0 -1
  134. package/dist/network.js +0 -17
  135. package/dist/network.js.map +0 -1
  136. package/dist/react/index.d.ts +0 -169
  137. package/dist/react/index.d.ts.map +0 -1
  138. package/dist/react/index.js +0 -628
  139. package/dist/react/index.js.map +0 -1
  140. package/dist/react-native/index.d.ts +0 -35
  141. package/dist/react-native/index.d.ts.map +0 -1
  142. package/dist/react-native/index.js +0 -49
  143. package/dist/react-native/index.js.map +0 -1
  144. package/dist/runtime-contract.d.ts +0 -13
  145. package/dist/runtime-contract.d.ts.map +0 -1
  146. package/dist/runtime-contract.js +0 -24
  147. package/dist/runtime-contract.js.map +0 -1
  148. package/dist/rust-client.d.ts +0 -106
  149. package/dist/rust-client.d.ts.map +0 -1
  150. package/dist/rust-client.js +0 -938
  151. package/dist/rust-client.js.map +0 -1
  152. package/dist/sentry.d.ts +0 -35
  153. package/dist/sentry.d.ts.map +0 -1
  154. package/dist/sentry.js +0 -155
  155. package/dist/sentry.js.map +0 -1
  156. package/dist/sql-safety.d.ts +0 -3
  157. package/dist/sql-safety.d.ts.map +0 -1
  158. package/dist/sql-safety.js +0 -62
  159. package/dist/sql-safety.js.map +0 -1
  160. package/dist/syncular-runtime-artifacts.json +0 -61
  161. package/dist/tauri/index.d.ts +0 -35
  162. package/dist/tauri/index.d.ts.map +0 -1
  163. package/dist/tauri/index.js +0 -114
  164. package/dist/tauri/index.js.map +0 -1
  165. package/dist/types.d.ts +0 -1096
  166. package/dist/types.d.ts.map +0 -1
  167. package/dist/types.js +0 -2
  168. package/dist/types.js.map +0 -1
  169. package/dist/wasm/.syncular-wasm-profile +0 -1
  170. package/dist/wasm/syncular-runtime-artifact.json +0 -21
  171. package/dist/wasm/syncular.d.ts +0 -207
  172. package/dist/wasm/syncular.js +0 -2341
  173. package/dist/wasm/syncular_bg.wasm +0 -0
  174. package/dist/wasm/syncular_bg.wasm.d.ts +0 -97
  175. package/dist/wasm-bindings/runtime-contract.d.ts +0 -22
  176. package/dist/wasm-bindings/runtime-contract.d.ts.map +0 -1
  177. package/dist/wasm-bindings/runtime-contract.js +0 -112
  178. package/dist/wasm-bindings/runtime-contract.js.map +0 -1
  179. package/dist/wasm-core/.syncular-wasm-profile +0 -1
  180. package/dist/wasm-core/syncular-runtime-artifact.json +0 -17
  181. package/dist/wasm-core/syncular.d.ts +0 -162
  182. package/dist/wasm-core/syncular.js +0 -1847
  183. package/dist/wasm-core/syncular_bg.wasm +0 -0
  184. package/dist/wasm-core/syncular_bg.wasm.d.ts +0 -77
  185. package/dist/wasm-perf/.syncular-wasm-profile +0 -1
  186. package/dist/wasm-perf/syncular-runtime-artifact.json +0 -21
  187. package/dist/wasm-perf/syncular.d.ts +0 -207
  188. package/dist/wasm-perf/syncular.js +0 -2341
  189. package/dist/wasm-perf/syncular_bg.wasm +0 -0
  190. package/dist/wasm-perf/syncular_bg.wasm.d.ts +0 -97
  191. package/dist/wasm-runtime.d.ts +0 -23
  192. package/dist/wasm-runtime.d.ts.map +0 -1
  193. package/dist/wasm-runtime.js +0 -69
  194. package/dist/wasm-runtime.js.map +0 -1
  195. package/dist/worker-client.d.ts +0 -123
  196. package/dist/worker-client.d.ts.map +0 -1
  197. package/dist/worker-client.js +0 -1735
  198. package/dist/worker-client.js.map +0 -1
  199. package/dist/worker-entry.d.ts.map +0 -1
  200. package/dist/worker-entry.js.map +0 -1
  201. package/dist/worker-protocol.d.ts.map +0 -1
  202. package/dist/worker-protocol.js.map +0 -1
  203. package/dist/worker-realtime.d.ts +0 -39
  204. package/dist/worker-realtime.d.ts.map +0 -1
  205. package/dist/worker-realtime.js +0 -677
  206. package/dist/worker-realtime.js.map +0 -1
  207. package/src/auth-leases.ts +0 -251
  208. package/src/blob-limits.ts +0 -98
  209. package/src/bridge-client.ts +0 -512
  210. package/src/client-config.ts +0 -29
  211. package/src/command-history.ts +0 -623
  212. package/src/console-diagnostics.ts +0 -617
  213. package/src/crdt-yjs/index.ts +0 -3
  214. package/src/crdt-yjs/webview-host-facade.ts +0 -477
  215. package/src/crdt-yjs/yjs-document-field-adapter.ts +0 -733
  216. package/src/crdt-yjs/yjs-prosemirror-bridge.ts +0 -272
  217. package/src/diagnostics.ts +0 -116
  218. package/src/generated-bridge.ts +0 -741
  219. package/src/mutations.ts +0 -168
  220. package/src/network.ts +0 -32
  221. package/src/react/index.ts +0 -1036
  222. package/src/react-native/index.ts +0 -152
  223. package/src/runtime-contract.ts +0 -48
  224. package/src/rust-client.ts +0 -1491
  225. package/src/sentry.ts +0 -215
  226. package/src/sql-safety.ts +0 -61
  227. package/src/tauri/index.ts +0 -211
  228. package/src/types.ts +0 -1397
  229. package/src/wasm-bindings/generated-wasm-bindings.d.ts +0 -70
  230. package/src/wasm-bindings/runtime-contract.ts +0 -158
  231. package/src/wasm-runtime.ts +0 -145
  232. package/src/worker-client.ts +0 -2289
  233. package/src/worker-realtime.ts +0 -843
package/src/database.ts CHANGED
@@ -1,1396 +1,70 @@
1
- import {
2
- applyCodecsToDbRow,
3
- type BlobRef,
4
- type ColumnCodecDialect,
5
- type ColumnCodecSource,
6
- createColumnCodecsPlugin,
7
- createTableColumnCodecsResolver,
8
- randomId,
9
- type SyncAuthLeaseIssueRequest,
10
- type SyncOperation,
11
- } from '@syncular/core';
12
- import {
13
- type CompiledQuery,
14
- type DatabaseConnection,
15
- type Dialect,
16
- Kysely,
17
- CompiledQuery as KyselyCompiledQuery,
18
- type QueryResult,
19
- } from 'kysely';
20
- import { BaseSqliteDialect, BaseSqliteDriver } from 'kysely-generic-sqlite';
21
- import {
22
- assertSyncularBlobPayloadLimit,
23
- type SyncularBlobLimitInput,
24
- syncularBlobInputSize,
25
- } from './blob-limits';
26
- import {
27
- getSyncularClientStatus,
28
- SyncularClientLifecycle,
29
- type SyncularClientStatus,
30
- type SyncularConflictsClientLike,
31
- type SyncularPresenceClientLike,
32
- } from './client';
33
- import { createSyncularConsoleDiagnosticsPublisher } from './console-diagnostics';
34
- import { isSyncularOfflineError } from './errors';
35
- import {
36
- createMutationsApi,
37
- type MutationsApi,
38
- type MutationsCommitFn,
39
- type MutationsTx,
40
- } from './mutations';
41
- import { browserSyncularNetworkStatusSource } from './network';
42
- import { assertSyncularReadonlySql } from './sql-safety';
43
- import type {
44
- CreateSyncularDatabaseOptions,
45
- SyncularAuthLeaseRecord,
46
- SyncularBlobStoreOptions,
47
- SyncularBlobs,
48
- SyncularClientEventSink,
49
- SyncularClientEventType,
50
- SyncularCrdtYjsFieldConfig,
51
- SyncularDiagnosticSnapshot,
52
- SyncularLiveQueries,
53
- SyncularLiveQueryDependencyHint,
54
- SyncularLiveQueryEvent,
55
- SyncularLiveQueryOptions,
56
- SyncularLiveQuerySubscription,
57
- SyncularNetworkStatusSource,
58
- SyncularRuntimeClient,
59
- SyncularSqlClient,
60
- SyncularSubscriptionSpec,
61
- SyncularSyncRequestOptions,
62
- SyncularSyncResult,
63
- SyncularTableConfigMap,
64
- SyncularUnsafeSqlClient,
65
- } from './types';
66
- import { createSyncularWorkerClient } from './worker-client';
67
-
68
- type SyncularDriverClient = SyncularRuntimeClient &
69
- Partial<SyncularUnsafeSqlClient>;
70
- type SyncularConnectionClient = SyncularSqlClient &
71
- Partial<SyncularUnsafeSqlClient>;
72
-
73
- export interface SyncularDialect extends Dialect, SyncularLiveQueries {
74
- destroyLiveQueries(): Promise<void>;
75
- }
76
-
77
- export interface SyncularDialectOptions {
78
- appTables?: readonly string[];
79
- tableConfig?: SyncularTableConfigMap;
80
- unsafeWrites?: boolean;
81
- }
82
-
83
- export interface SyncularDatabase<DB> extends SyncularLiveQueries {
84
- db: Kysely<DB>;
85
- client: SyncularRuntimeClient;
86
- dialect: SyncularDialect;
87
- mutations: MutationsApi<DB, undefined>;
88
- leasedMutations: MutationsApi<DB, undefined>;
89
- blobs: SyncularBlobs;
1
+ /**
2
+ * Storage abstraction (REVISE B3): the client core runs on any SQLite that
3
+ * implements this minimal synchronous surface. Tests use bun:sqlite
4
+ * (`./bun-database`); browsers use sqlite-wasm + OPFS (`./wasm-database`).
5
+ * Methods are synchronous because both backends execute synchronously once
6
+ * open — only opening a database is async, which lives in the factories.
7
+ */
8
+ export type SqlValue = string | number | bigint | boolean | Uint8Array | null;
9
+
10
+ export type SqlRow = Record<string, SqlValue>;
11
+
12
+ export interface ClientDatabase {
13
+ /** Execute a single statement (no result rows). */
14
+ exec(sql: string, params?: readonly SqlValue[]): void;
15
+ /** Execute a single statement and return its rows as objects. */
16
+ query(sql: string, params?: readonly SqlValue[]): SqlRow[];
90
17
  /**
91
- * The sync lifecycle owned by this database. It starts automatically while
92
- * the database opens (remote mode, unless `lifecycle.autoStart` is false)
93
- * and stops on `close()`. Reach for it directly only for advanced control;
94
- * `start`/`stop`/`sync` proxy to it.
18
+ * Run `fn` atomically. Nested calls are savepoints: an inner failure
19
+ * rolls back only the inner scope.
95
20
  */
96
- lifecycle: SyncularClientLifecycle;
97
- start(): Promise<void>;
98
- stop(): Promise<void>;
99
- sync(): Promise<SyncularSyncResult>;
100
- on<T extends SyncularClientEventType>(
101
- event: T,
102
- listener: SyncularClientEventSink<T>
103
- ): () => void;
104
- getStatus(): SyncularClientStatus;
105
- setSubscriptions(
106
- subscriptions: readonly SyncularSubscriptionSpec[]
107
- ): Promise<void>;
108
- resumeFromBackground(
109
- options?: SyncularSyncRequestOptions
110
- ): Promise<SyncularSyncResult>;
111
- issueAuthLease(
112
- request: SyncAuthLeaseIssueRequest
113
- ): Promise<SyncularAuthLeaseRecord>;
114
- upsertAuthLease(lease: SyncularAuthLeaseRecord): Promise<void>;
115
- authLease(leaseId: string): Promise<SyncularAuthLeaseRecord | null>;
116
- activeAuthLeases(
117
- actorId?: string | null,
118
- nowMs?: number
119
- ): Promise<SyncularAuthLeaseRecord[]>;
120
- diagnosticSnapshot(): Promise<SyncularDiagnosticSnapshot>;
121
- presence: SyncularPresenceClientLike;
122
- conflicts: SyncularConflictsClientLike;
123
- close(): Promise<void>;
124
- }
125
-
126
- export async function withSyncularSchemaWrites<DB, Result>(
127
- database: Pick<SyncularDatabase<DB>, 'client'>,
128
- callback: (db: Kysely<any>) => Promise<Result>
129
- ): Promise<Result> {
130
- const client = assertUnsafeSqlClient(database.client);
131
- const dialect = createSyncularDialect(client, { unsafeWrites: true });
132
- const db = new Kysely<any>({ dialect });
133
- try {
134
- return await callback(db);
135
- } finally {
136
- await dialect.destroyLiveQueries();
137
- await db.destroy();
138
- }
139
- }
140
-
141
- export interface SyncularMutationsMeta {
142
- operations: SyncOperation[];
143
- localMutations: Array<{
144
- table: string;
145
- rowId: string;
146
- op: 'upsert' | 'delete';
147
- }>;
148
- clientCommitIds: string[];
149
- }
150
-
151
- export interface SyncularMutationsOptions {
152
- client: Pick<
153
- SyncularRuntimeClient,
154
- | 'applyMutation'
155
- | 'applyMutationsBatch'
156
- | 'applyMutationsCommit'
157
- | 'applyYjsEnvelopeToPayload'
158
- | 'executeSql'
159
- > &
160
- Partial<
161
- Pick<
162
- SyncularRuntimeClient,
163
- 'applyLeasedMutation' | 'applyLeasedMutationsCommit'
164
- >
165
- >;
166
- requireAuthLease?: boolean;
167
- codecs?: ColumnCodecSource;
168
- codecDialect?: ColumnCodecDialect;
169
- idColumn?: string;
170
- versionColumn?: string | null;
171
- omitColumns?: string[];
172
- tableConfig?: SyncularTableConfigMap;
173
- readBaseVersion?: (args: {
174
- table: string;
175
- rowId: string;
176
- idColumn: string;
177
- versionColumn: string;
178
- }) => Promise<number | null>;
179
- afterCommit?: (meta: SyncularMutationsMeta) => void | Promise<void>;
180
- }
181
-
182
- export async function createSyncularDatabase<DB>(
183
- options: CreateSyncularDatabaseOptions
184
- ): Promise<SyncularDatabase<DB>> {
185
- const client = await createSyncularWorkerClient(options);
186
- const dialect = createSyncularDialect(client, {
187
- appTables: options.appTables,
188
- tableConfig: options.tableConfig,
189
- });
190
- const db = new Kysely<DB>({
191
- dialect,
192
- plugins: options.codecs
193
- ? [
194
- createColumnCodecsPlugin({
195
- codecs: options.codecs,
196
- dialect: 'sqlite',
197
- }),
198
- ]
199
- : undefined,
200
- });
201
- let closed = false;
202
- const localClientMode = (options.config.mode ?? 'remote') !== 'remote';
203
- const mutationSyncScheduler = createMutationSyncScheduler(client, {
204
- enabled: options.sync?.autoSyncAfterMutation ?? !localClientMode,
205
- debounceMs: options.sync?.mutationSyncDebounceMs ?? 10,
206
- network:
207
- options.sync?.network === false
208
- ? undefined
209
- : (options.sync?.network ?? browserSyncularNetworkStatusSource()),
210
- isClosed: () => closed,
211
- });
212
- const blobUploadScheduler = createBlobUploadScheduler(client, {
213
- enabled: options.sync?.autoProcessBlobUploadsAfterStore ?? false,
214
- debounceMs: options.sync?.blobUploadDebounceMs ?? 10,
215
- isClosed: () => closed,
216
- });
217
- const consoleDiagnostics =
218
- options.consoleDiagnostics === undefined ||
219
- options.consoleDiagnostics === false
220
- ? undefined
221
- : createSyncularConsoleDiagnosticsPublisher(client, {
222
- ...(options.consoleDiagnostics === true
223
- ? {}
224
- : options.consoleDiagnostics),
225
- config: options.config,
226
- isClosed: () => closed,
227
- });
228
- const mutations = createSyncularMutations<DB>({
229
- client,
230
- codecs: options.codecs,
231
- codecDialect: 'sqlite',
232
- tableConfig: options.tableConfig,
233
- readBaseVersion: (args) => readCurrentBaseVersion(client, args),
234
- afterCommit: () => mutationSyncScheduler.schedule(),
235
- });
236
- const leasedMutations = createSyncularMutations<DB>({
237
- client,
238
- requireAuthLease: true,
239
- codecs: options.codecs,
240
- codecDialect: 'sqlite',
241
- tableConfig: options.tableConfig,
242
- readBaseVersion: (args) => readCurrentBaseVersion(client, args),
243
- afterCommit: () => mutationSyncScheduler.schedule(),
244
- });
245
- const blobs = createSyncularBlobClient(client, {
246
- diagnostics: options.diagnostics,
247
- limits: options.blobLimits,
248
- afterStore: ({ options }) => {
249
- if (options?.immediate) return;
250
- blobUploadScheduler.schedule();
251
- },
252
- });
253
- const lifecycle = new SyncularClientLifecycle(client, {
254
- realtime: options.realtime ?? true,
255
- initialSync: options.lifecycle?.initialSync,
256
- syncOnRealtimeConnect: options.lifecycle?.syncOnRealtimeConnect,
257
- pollIntervalMs: options.pollIntervalMs,
258
- network: options.sync?.network,
259
- });
260
-
261
- const database: SyncularDatabase<DB> = {
262
- db,
263
- client,
264
- dialect,
265
- mutations,
266
- leasedMutations,
267
- blobs,
268
- lifecycle,
269
- live: (query, liveOptions) => dialect.live(query, liveOptions),
270
- start: () => lifecycle.start(),
271
- stop: () => lifecycle.stop(),
272
- sync: () => lifecycle.sync(),
273
- on: (event, listener) => client.addEventListener(event, listener),
274
- getStatus: () => getSyncularClientStatus(client),
275
- setSubscriptions: (subscriptions) => client.setSubscriptions(subscriptions),
276
- resumeFromBackground: (syncOptions) =>
277
- client.resumeFromBackground(syncOptions),
278
- issueAuthLease: (request) => client.issueAuthLease(request),
279
- upsertAuthLease: (lease) => client.upsertAuthLease(lease),
280
- authLease: (leaseId) => client.authLease(leaseId),
281
- activeAuthLeases: (actorId, nowMs) =>
282
- client.activeAuthLeases(actorId, nowMs),
283
- diagnosticSnapshot: () => client.diagnosticSnapshot(),
284
- presence: {
285
- get: (scopeKey) => client.getPresence(scopeKey),
286
- join: (scopeKey, metadata) => client.joinPresence(scopeKey, metadata),
287
- leave: (scopeKey) => client.leavePresence(scopeKey),
288
- updateMetadata: (scopeKey, metadata) =>
289
- client.updatePresenceMetadata(scopeKey, metadata),
290
- onChange: (listener) => client.addPresenceListener(listener),
291
- },
292
- conflicts: {
293
- list: () => client.conflictSummaries(),
294
- retryKeepLocal: (id) => client.retryConflictKeepLocal(id),
295
- resolve: (id, resolution) => client.resolveConflict(id, resolution),
296
- },
297
- async close() {
298
- if (closed) return;
299
- closed = true;
300
- mutationSyncScheduler.destroy();
301
- blobUploadScheduler.destroy();
302
- consoleDiagnostics?.destroy();
303
- try {
304
- await lifecycle.stop().catch(() => undefined);
305
- await dialect.destroyLiveQueries();
306
- await db.destroy();
307
- } finally {
308
- await client.close();
309
- }
310
- },
311
- };
312
-
21
+ transaction<T>(fn: () => T): T;
22
+ /**
23
+ * Optional sqlite-image capability (SPEC §5.3): expose `bytes` as an
24
+ * attached read-only database schema named `alias` for the duration of
25
+ * `fn`, then detach. Presence of this method is what makes the client
26
+ * advertise `accept` bit 2 (§4.2). MUST be called outside any open
27
+ * transaction (SQLite cannot ATTACH inside one); `fn` may open its own.
28
+ */
29
+ withSqliteImage?<T>(bytes: Uint8Array, alias: string, fn: () => T): T;
30
+ close(): void;
31
+ }
32
+
33
+ /** Attach-schema aliases are code-chosen, never user input — enforce it. */
34
+ export function assertImageAlias(alias: string): void {
35
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(alias)) {
36
+ throw new Error(`invalid sqlite-image alias ${JSON.stringify(alias)}`);
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Savepoint-based transaction helper shared by database implementations.
42
+ * `run` executes a parameterless statement.
43
+ */
44
+ export function runTransaction<T>(
45
+ depthHolder: { depth: number },
46
+ run: (sql: string) => void,
47
+ fn: () => T,
48
+ ): T {
49
+ const depth = depthHolder.depth;
50
+ const savepoint = `syncular_sp_${depth}`;
51
+ if (depth === 0) run('BEGIN');
52
+ else run(`SAVEPOINT ${savepoint}`);
53
+ depthHolder.depth = depth + 1;
313
54
  try {
314
- if (options.subscriptions) {
315
- await client.setSubscriptions(options.subscriptions);
316
- }
317
- if (options.lifecycle?.autoStart ?? !localClientMode) {
318
- await lifecycle.start();
319
- }
55
+ const result = fn();
56
+ depthHolder.depth = depth;
57
+ if (depth === 0) run('COMMIT');
58
+ else run(`RELEASE ${savepoint}`);
59
+ return result;
320
60
  } catch (error) {
321
- await database.close().catch(() => undefined);
322
- throw error;
323
- }
324
-
325
- return database;
326
- }
327
-
328
- function createMutationSyncScheduler(
329
- client: Pick<SyncularRuntimeClient, 'syncOnce'>,
330
- options: {
331
- enabled: boolean;
332
- debounceMs: number | false;
333
- network: SyncularNetworkStatusSource | undefined;
334
- isClosed: () => boolean;
335
- }
336
- ): { schedule(): void; destroy(): void } {
337
- let timer: ReturnType<typeof setTimeout> | undefined;
338
- let inFlight: Promise<void> | undefined;
339
- let queued = false;
340
- const isOnline = () => options.network?.isOnline() !== false;
341
- const clear = () => {
342
- if (timer) clearTimeout(timer);
343
- timer = undefined;
344
- };
345
- const run = async () => {
346
- if (options.isClosed()) return;
347
- if (!isOnline()) {
348
- queued = true;
349
- return;
350
- }
351
- if (inFlight) {
352
- queued = true;
353
- return;
354
- }
355
- inFlight = client
356
- .syncOnce()
357
- .then(() => undefined)
358
- .catch((error) => {
359
- if (!isOnline() || isSyncularOfflineError(error)) queued = true;
360
- })
361
- .finally(() => {
362
- inFlight = undefined;
363
- if (queued && !options.isClosed() && isOnline()) {
364
- queued = false;
365
- schedule();
366
- }
367
- });
368
- await inFlight;
369
- };
370
- const schedule = () => {
371
- if (!options.enabled || options.isClosed()) return;
372
- if (!isOnline()) {
373
- queued = true;
374
- clear();
375
- return;
376
- }
377
- if (inFlight) {
378
- queued = true;
379
- return;
380
- }
381
- clear();
382
- if (options.debounceMs === false || options.debounceMs <= 0) {
383
- queueMicrotask(() => void run());
384
- return;
385
- }
386
- timer = setTimeout(() => void run(), options.debounceMs);
387
- };
388
- const handleOnline = () => {
389
- if (!queued || options.isClosed()) return;
390
- queued = false;
391
- schedule();
392
- };
393
- options.network?.addEventListener?.('online', handleOnline);
394
- return {
395
- schedule,
396
- destroy() {
397
- clear();
398
- queued = false;
399
- options.network?.removeEventListener?.('online', handleOnline);
400
- },
401
- };
402
- }
403
-
404
- function createBlobUploadScheduler(
405
- client: Pick<SyncularRuntimeClient, 'processBlobUploadQueue'>,
406
- options: {
407
- enabled: boolean;
408
- debounceMs: number | false;
409
- isClosed: () => boolean;
410
- }
411
- ): { schedule(): void; destroy(): void } {
412
- let timer: ReturnType<typeof setTimeout> | undefined;
413
- let inFlight: Promise<void> | undefined;
414
- let queued = false;
415
- const clear = () => {
416
- if (timer) clearTimeout(timer);
417
- timer = undefined;
418
- };
419
- const run = async () => {
420
- if (options.isClosed()) return;
421
- if (inFlight) {
422
- queued = true;
423
- return;
424
- }
425
- inFlight = client
426
- .processBlobUploadQueue()
427
- .then(() => undefined)
428
- .catch(() => undefined)
429
- .finally(() => {
430
- inFlight = undefined;
431
- if (queued && !options.isClosed()) {
432
- queued = false;
433
- schedule();
434
- }
435
- });
436
- await inFlight;
437
- };
438
- const schedule = () => {
439
- if (!options.enabled || options.isClosed()) return;
440
- if (inFlight) {
441
- queued = true;
442
- return;
443
- }
444
- clear();
445
- if (options.debounceMs === false || options.debounceMs <= 0) {
446
- queueMicrotask(() => void run());
447
- return;
448
- }
449
- timer = setTimeout(() => void run(), options.debounceMs);
450
- };
451
- return {
452
- schedule,
453
- destroy() {
454
- clear();
455
- queued = false;
456
- },
457
- };
458
- }
459
-
460
- export function createSyncularBlobClient(
461
- client: Pick<
462
- SyncularRuntimeClient,
463
- | 'storeBlob'
464
- | 'retrieveBlob'
465
- | 'isBlobLocal'
466
- | 'processBlobUploadQueue'
467
- | 'blobUploadQueueStats'
468
- | 'blobCacheStats'
469
- | 'pruneBlobCache'
470
- | 'clearBlobCache'
471
- >,
472
- hooks: {
473
- limits?: CreateSyncularDatabaseOptions['blobLimits'];
474
- diagnostics?: CreateSyncularDatabaseOptions['diagnostics'];
475
- afterStore?: (args: {
476
- ref: BlobRef;
477
- options?: SyncularBlobStoreOptions;
478
- }) => void | Promise<void>;
479
- } = {}
480
- ): SyncularBlobs {
481
- const assertRetrieveWithinLimit = (ref: BlobRef) =>
482
- assertSyncularBlobPayloadLimit({
483
- operation: 'retrieve',
484
- size: ref.size,
485
- limits: hooks.limits,
486
- refHash: ref.hash,
487
- diagnostics: hooks.diagnostics,
488
- });
489
- return {
490
- async store(data, storeOptions) {
491
- assertSyncularBlobPayloadLimit({
492
- operation: 'store',
493
- size: syncularBlobInputSize(data as SyncularBlobLimitInput),
494
- limits: hooks.limits,
495
- options: storeOptions,
496
- diagnostics: hooks.diagnostics,
497
- });
498
- const ref = await client.storeBlob(
499
- await toUint8Array(data),
500
- storeOptions
501
- );
502
- await hooks.afterStore?.({
503
- ref,
504
- ...(storeOptions === undefined ? {} : { options: storeOptions }),
505
- });
506
- return ref;
507
- },
508
- async retrieve(ref) {
509
- assertRetrieveWithinLimit(ref);
510
- return client.retrieveBlob(ref);
511
- },
512
- isLocal(hash) {
513
- return client.isBlobLocal(hash);
514
- },
515
- async preload(refs) {
516
- for (const ref of refs) assertRetrieveWithinLimit(ref);
517
- await Promise.all(refs.map((ref) => client.retrieveBlob(ref)));
518
- },
519
- processUploadQueue(options) {
520
- return client.processBlobUploadQueue(options);
521
- },
522
- getUploadQueueStats() {
523
- return client.blobUploadQueueStats();
524
- },
525
- getCacheStats() {
526
- return client.blobCacheStats();
527
- },
528
- pruneCache(maxBytes) {
529
- return client.pruneBlobCache(maxBytes);
530
- },
531
- clearCache() {
532
- return client.clearBlobCache();
533
- },
534
- };
535
- }
536
-
537
- export function createSyncularDialect(
538
- client: SyncularRuntimeClient,
539
- options: SyncularDialectOptions = {}
540
- ): SyncularDialect {
541
- const driver = new SyncularDriver(client, options);
542
- const dialect = new BaseSqliteDialect(() => driver) as SyncularDialect;
543
- dialect.live = (query, liveOptions) => driver.live(query, liveOptions);
544
- dialect.destroyLiveQueries = () => driver.destroy();
545
- return dialect;
546
- }
547
-
548
- export function createSyncularMutations<DB>(
549
- options: SyncularMutationsOptions
550
- ): MutationsApi<DB, undefined> {
551
- return createMutationsApi(createSyncularCommit<DB>(options));
552
- }
553
-
554
- export function createSyncularCommit<DB>(
555
- options: SyncularMutationsOptions
556
- ): MutationsCommitFn<DB, SyncularMutationsMeta, undefined> {
557
- const idColumn = options.idColumn ?? 'id';
558
- const versionColumn = options.versionColumn ?? 'server_version';
559
- const omitColumns = options.omitColumns ?? [];
560
- const codecDialect = options.codecDialect ?? 'sqlite';
561
- const resolveTableCodecs = createTableColumnCodecsResolver(options.codecs, {
562
- dialect: codecDialect,
563
- });
564
-
565
- return async (fn) => {
566
- const operations: SyncOperation[] = [];
567
- const batch: Array<{
568
- operation: SyncOperation;
569
- localRow?: unknown | null;
570
- }> = [];
571
- const localMutations: SyncularMutationsMeta['localMutations'] = [];
572
- const txTableCache = new Map<string, unknown>();
573
-
574
- const makeTxTable = (table: string) => {
575
- const cached = txTableCache.get(table);
576
- if (cached) return cached;
577
- const tableConfig = options.tableConfig?.[table];
578
- const tableIdColumn = tableConfig?.primaryKeyColumn ?? idColumn;
579
- const tableVersionColumn =
580
- tableConfig?.serverVersionColumn === undefined
581
- ? versionColumn
582
- : tableConfig.serverVersionColumn;
583
- const softDeleteColumn = tableConfig?.softDeleteColumn ?? null;
584
- const crdtYjsFields = serverMergeCrdtYjsFields(
585
- tableConfig?.crdtYjsFields ?? []
586
- );
587
-
588
- const prepareInsert = async (values: unknown) => {
589
- const raw = objectRecord(values);
590
- const rawId = raw[tableIdColumn];
591
- const id = typeof rawId === 'string' && rawId ? rawId : randomId();
592
- const row = { ...raw, [tableIdColumn]: id };
593
- const payload = sanitizeOperationPayload(row, {
594
- omit: [
595
- tableIdColumn,
596
- ...(tableVersionColumn ? [tableVersionColumn] : []),
597
- ...omitColumns,
598
- ],
599
- });
600
- const syncPayload = stripCrdtYjsMaterializedPayloadFields(
601
- payload,
602
- crdtYjsFields
603
- );
604
- const localPayload = sanitizeOperationPayload(row, {
605
- omit: [
606
- tableIdColumn,
607
- ...(tableVersionColumn ? [tableVersionColumn] : []),
608
- ],
609
- });
610
- const transformedLocalPayload = await transformCrdtYjsMutationPayload({
611
- client: options.client,
612
- table,
613
- rowId: id,
614
- payload: localPayload,
615
- crdtYjsFields,
616
- });
617
- const localDbPayload = applyCodecsToDbRow(
618
- transformedLocalPayload,
619
- resolveTableCodecs(table, transformedLocalPayload),
620
- codecDialect
621
- );
622
- const operation: SyncOperation = {
623
- table,
624
- row_id: id,
625
- op: 'upsert',
626
- payload: syncPayload,
627
- base_version: null,
628
- };
629
- return {
630
- id,
631
- operation,
632
- localRow: { ...localDbPayload, [tableIdColumn]: id },
633
- };
634
- };
635
-
636
- const tableApi = {
637
- async insert(values: unknown) {
638
- const prepared = await prepareInsert(values);
639
- const { id, operation, localRow } = prepared;
640
- operations.push(operation);
641
- batch.push({ operation, localRow });
642
- localMutations.push({ table, rowId: id, op: 'upsert' });
643
- return id;
644
- },
645
- async insertMany(rows: unknown[]) {
646
- if (rows.length === 0) {
647
- throw new Error('insertMany requires at least one row');
648
- }
649
- const ids: string[] = [];
650
- for (const row of rows) {
651
- const { id, operation, localRow } = await prepareInsert(row);
652
- ids.push(id);
653
- operations.push(operation);
654
- batch.push({ operation, localRow });
655
- localMutations.push({ table, rowId: id, op: 'upsert' });
656
- }
657
- return ids;
658
- },
659
- async update(
660
- id: string,
661
- patch: unknown,
662
- opts?: { baseVersion?: number | null }
663
- ) {
664
- await applyUpsert(id, patch, opts, { mergeExistingLocalRow: true });
665
- },
666
- async delete(id: string, opts?: { baseVersion?: number | null }) {
667
- const baseVersion = await resolveBaseVersion({
668
- options,
669
- table,
670
- rowId: id,
671
- idColumn: tableIdColumn,
672
- versionColumn: tableVersionColumn,
673
- explicit: opts?.baseVersion,
674
- });
675
- if (softDeleteColumn) {
676
- const payload = { [softDeleteColumn]: 1 };
677
- const localDbPayload = applyCodecsToDbRow(
678
- payload,
679
- resolveTableCodecs(table, payload),
680
- codecDialect
681
- );
682
- const operation: SyncOperation = {
683
- table,
684
- row_id: id,
685
- op: 'upsert',
686
- payload,
687
- base_version: baseVersion,
688
- };
689
- operations.push(operation);
690
- batch.push({
691
- operation,
692
- localRow: { ...localDbPayload, [tableIdColumn]: id },
693
- });
694
- localMutations.push({ table, rowId: id, op: 'upsert' });
695
- return;
696
- }
697
- const operation: SyncOperation = {
698
- table,
699
- row_id: id,
700
- op: 'delete',
701
- payload: null,
702
- base_version: baseVersion,
703
- };
704
- operations.push(operation);
705
- batch.push({ operation, localRow: null });
706
- localMutations.push({ table, rowId: id, op: 'delete' });
707
- },
708
- async upsert(
709
- id: string,
710
- patch: unknown,
711
- opts?: { baseVersion?: number | null }
712
- ) {
713
- await applyUpsert(id, patch, opts, { mergeExistingLocalRow: false });
714
- },
715
- };
716
-
717
- const applyUpsert = async (
718
- id: string,
719
- patch: unknown,
720
- opts: { baseVersion?: number | null } | undefined,
721
- behavior: { mergeExistingLocalRow: boolean }
722
- ) => {
723
- const rawPatch = objectRecord(patch);
724
- const payload = sanitizeOperationPayload(rawPatch, {
725
- omit: [
726
- tableIdColumn,
727
- ...(tableVersionColumn ? [tableVersionColumn] : []),
728
- ...omitColumns,
729
- ],
730
- });
731
- const syncPayload = stripCrdtYjsMaterializedPayloadFields(
732
- payload,
733
- crdtYjsFields
734
- );
735
- const existingLocalRow = behavior.mergeExistingLocalRow
736
- ? await readExistingLocalRow({
737
- client: options.client,
738
- table,
739
- rowId: id,
740
- idColumn: tableIdColumn,
741
- })
742
- : null;
743
- const rawLocalPayload = existingLocalRow
744
- ? { ...existingLocalRow, ...rawPatch }
745
- : rawPatch;
746
- const localPayload = sanitizeOperationPayload(rawLocalPayload, {
747
- omit: [
748
- tableIdColumn,
749
- ...(tableVersionColumn ? [tableVersionColumn] : []),
750
- ],
751
- });
752
- const existingRow = await readCrdtYjsExistingRow({
753
- client: options.client,
754
- table,
755
- rowId: id,
756
- idColumn: tableIdColumn,
757
- crdtYjsFields,
758
- });
759
- const transformedLocalPayload = await transformCrdtYjsMutationPayload({
760
- client: options.client,
761
- table,
762
- rowId: id,
763
- payload: localPayload,
764
- existingRow,
765
- crdtYjsFields,
766
- });
767
- const localDbPayload = applyCodecsToDbRow(
768
- transformedLocalPayload,
769
- resolveTableCodecs(table, transformedLocalPayload),
770
- codecDialect
771
- );
772
- const operation: SyncOperation = {
773
- table,
774
- row_id: id,
775
- op: 'upsert',
776
- payload: syncPayload,
777
- base_version: await resolveBaseVersion({
778
- options,
779
- table,
780
- rowId: id,
781
- idColumn: tableIdColumn,
782
- versionColumn: tableVersionColumn,
783
- explicit: opts?.baseVersion,
784
- }),
785
- };
786
- operations.push(operation);
787
- batch.push({
788
- operation,
789
- localRow: { ...localDbPayload, [tableIdColumn]: id },
790
- });
791
- localMutations.push({ table, rowId: id, op: 'upsert' });
792
- };
793
-
794
- txTableCache.set(table, tableApi);
795
- return tableApi;
796
- };
797
-
798
- const tx = new Proxy(
799
- {},
800
- {
801
- get(_target, prop) {
802
- if (prop === 'then') return undefined;
803
- if (typeof prop !== 'string') return undefined;
804
- return makeTxTable(prop);
805
- },
806
- }
807
- );
808
-
809
- const result = await fn(tx as MutationsTx<DB>);
810
- if (operations.length === 0) throw new Error('No mutations were enqueued');
811
- const clientCommitId = options.requireAuthLease
812
- ? await requireLeasedMutationClient(
813
- options.client
814
- ).applyLeasedMutationsCommit(batch)
815
- : await options.client.applyMutationsCommit(batch);
816
- const meta = {
817
- operations,
818
- localMutations,
819
- clientCommitIds: [clientCommitId],
820
- };
821
- await options.afterCommit?.(meta);
822
- return {
823
- result,
824
- receipt: { commitId: clientCommitId, clientCommitId },
825
- meta,
826
- };
827
- };
828
- }
829
-
830
- function requireLeasedMutationClient(
831
- client: SyncularMutationsOptions['client']
832
- ): Required<
833
- Pick<
834
- SyncularRuntimeClient,
835
- 'applyLeasedMutation' | 'applyLeasedMutationsCommit'
836
- >
837
- > {
838
- if (typeof client.applyLeasedMutationsCommit !== 'function') {
839
- throw new Error(
840
- 'Syncular leased mutations require applyLeasedMutationsCommit support'
841
- );
842
- }
843
- if (typeof client.applyLeasedMutation !== 'function') {
844
- throw new Error(
845
- 'Syncular leased mutations require applyLeasedMutation support'
846
- );
847
- }
848
- return client as Required<
849
- Pick<
850
- SyncularRuntimeClient,
851
- 'applyLeasedMutation' | 'applyLeasedMutationsCommit'
852
- >
853
- >;
854
- }
855
-
856
- class SyncularDriver extends BaseSqliteDriver {
857
- #listeners = new Map<
858
- string,
859
- (event: SyncularLiveQueryEvent<Record<string, unknown>>) => void
860
- >();
861
- readonly #appTables: Set<string> | undefined;
862
- readonly #tableConfig: SyncularTableConfigMap | undefined;
863
-
864
- constructor(
865
- private readonly client: SyncularDriverClient,
866
- options: SyncularDialectOptions = {}
867
- ) {
868
- super(async () => {
869
- this.conn = new SyncularConnection(client, options.unsafeWrites ?? false);
870
- });
871
- this.#appTables =
872
- options.appTables == null
873
- ? undefined
874
- : new Set(normalizeLiveQueryTables(options.appTables));
875
- this.#tableConfig = options.tableConfig;
876
- }
877
-
878
- async live<Row extends Record<string, unknown>>(
879
- query: { compile(): CompiledQuery },
880
- options: SyncularLiveQueryOptions<Row>
881
- ): Promise<SyncularLiveQuerySubscription> {
882
- const compiled = query.compile();
883
- const tables = normalizeLiveQueryTables(
884
- options.tables ?? inferTablesFromCompiledQuery(compiled, this.#appTables),
885
- this.#appTables
886
- );
887
- if (tables.length === 0) {
888
- throw new Error(
889
- 'Could not infer live query table dependencies. Pass { tables: [...] } explicitly.'
890
- );
61
+ depthHolder.depth = depth;
62
+ if (depth === 0) {
63
+ run('ROLLBACK');
64
+ } else {
65
+ run(`ROLLBACK TO ${savepoint}`);
66
+ run(`RELEASE ${savepoint}`);
891
67
  }
892
- const dependencyHints = normalizeLiveQueryDependencyHints(
893
- options.dependencyHints ??
894
- inferDependencyHintsFromCompiledQuery(
895
- compiled,
896
- tables,
897
- this.#tableConfig
898
- ),
899
- tables,
900
- this.#appTables
901
- );
902
- const snapshot = await this.client.subscribeQuery<Row>(
903
- compiled.sql,
904
- compiled.parameters,
905
- tables,
906
- dependencyHints
907
- );
908
- const listener = (
909
- event: SyncularLiveQueryEvent<Record<string, unknown>>
910
- ) => {
911
- const typed = event as SyncularLiveQueryEvent<Row>;
912
- options.onChange(typed.rows, { ...typed, initial: false });
913
- };
914
- this.#listeners.set(snapshot.id, listener);
915
- this.client.addLiveQueryListener(snapshot.id, listener);
916
- options.onChange(snapshot.rows, {
917
- queryId: snapshot.id,
918
- version: Date.now(),
919
- changedRows: [],
920
- rows: snapshot.rows,
921
- initial: true,
922
- });
923
-
924
- return {
925
- id: snapshot.id,
926
- unsubscribe: () => {
927
- void this.#unsubscribeQuery(snapshot.id).catch(() => undefined);
928
- },
929
- };
930
- }
931
-
932
- async beginTransaction(connection: DatabaseConnection): Promise<void> {
933
- await connection.executeQuery(KyselyCompiledQuery.raw('begin'));
934
- }
935
-
936
- override async destroy(): Promise<void> {
937
- const ids = [...this.#listeners.keys()];
938
- for (const id of ids) this.client.removeLiveQueryListener(id);
939
- this.#listeners.clear();
940
- await Promise.allSettled(ids.map((id) => this.client.unsubscribeQuery(id)));
941
- }
942
-
943
- async #unsubscribeQuery(id: string): Promise<void> {
944
- if (!this.#listeners.has(id)) return;
945
- this.#listeners.delete(id);
946
- this.client.removeLiveQueryListener(id);
947
- await this.client.unsubscribeQuery(id);
948
- }
949
- }
950
-
951
- class SyncularConnection implements DatabaseConnection {
952
- constructor(
953
- private readonly client: SyncularConnectionClient,
954
- private readonly unsafeWrites: boolean
955
- ) {}
956
-
957
- async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
958
- if (!this.unsafeWrites) assertSyncularReadonlySql(compiledQuery.sql);
959
- const result = this.unsafeWrites
960
- ? await assertUnsafeSqlClient(this.client).executeUnsafeSql<
961
- R & Record<string, unknown>
962
- >(compiledQuery.sql, compiledQuery.parameters)
963
- : await this.client.executeSql<R & Record<string, unknown>>(
964
- compiledQuery.sql,
965
- compiledQuery.parameters
966
- );
967
- return {
968
- rows: result.rows as R[],
969
- numAffectedRows:
970
- result.numAffectedRows == null
971
- ? undefined
972
- : BigInt(result.numAffectedRows),
973
- insertId: result.insertId == null ? undefined : BigInt(result.insertId),
974
- };
975
- }
976
-
977
- streamQuery<R>(
978
- _compiledQuery: CompiledQuery,
979
- _chunkSize?: number
980
- ): AsyncIterableIterator<QueryResult<R>> {
981
- throw new Error('syncular sqlite dialect does not support streaming');
982
- }
983
- }
984
-
985
- function assertUnsafeSqlClient<Client extends SyncularSqlClient>(
986
- client: Client
987
- ): Client & SyncularUnsafeSqlClient {
988
- const maybe = client as Partial<SyncularUnsafeSqlClient>;
989
- if (typeof maybe.executeUnsafeSql === 'function') {
990
- return client as Client & SyncularUnsafeSqlClient;
991
- }
992
- throw new Error(
993
- 'Syncular schema installation requires an internal unsafe SQL client.'
994
- );
995
- }
996
-
997
- function objectRecord(value: unknown): Record<string, unknown> {
998
- if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
999
- return { ...(value as Record<string, unknown>) };
1000
- }
1001
-
1002
- async function toUint8Array(
1003
- data: Blob | File | Uint8Array
1004
- ): Promise<Uint8Array> {
1005
- if (data instanceof Uint8Array) return data;
1006
- return new Uint8Array(await data.arrayBuffer());
1007
- }
1008
-
1009
- function sanitizeOperationPayload(
1010
- payload: Record<string, unknown>,
1011
- args: { omit: readonly string[] }
1012
- ): Record<string, unknown> {
1013
- if (args.omit.length === 0) return payload;
1014
- const omit = new Set(args.omit);
1015
- const out: Record<string, unknown> = {};
1016
- for (const [key, value] of Object.entries(payload)) {
1017
- if (!omit.has(key)) out[key] = value;
1018
- }
1019
- return out;
1020
- }
1021
-
1022
- function serverMergeCrdtYjsFields(
1023
- fields: readonly SyncularCrdtYjsFieldConfig[]
1024
- ): readonly SyncularCrdtYjsFieldConfig[] {
1025
- return fields.filter(
1026
- (field) => field.syncMode === undefined || field.syncMode === 'server-merge'
1027
- );
1028
- }
1029
-
1030
- async function transformCrdtYjsMutationPayload(args: {
1031
- client: Pick<SyncularRuntimeClient, 'applyYjsEnvelopeToPayload'>;
1032
- table: string;
1033
- rowId: string;
1034
- payload: Record<string, unknown>;
1035
- existingRow?: Record<string, unknown> | null;
1036
- crdtYjsFields: readonly SyncularCrdtYjsFieldConfig[];
1037
- }): Promise<Record<string, unknown>> {
1038
- if (args.crdtYjsFields.length === 0 || !('__yjs' in args.payload)) {
1039
- return args.payload;
1040
- }
1041
- return args.client.applyYjsEnvelopeToPayload({
1042
- table: args.table,
1043
- rowId: args.rowId,
1044
- payload: args.payload,
1045
- existingRow: args.existingRow ?? null,
1046
- rules: args.crdtYjsFields.map((field) => ({
1047
- table: args.table,
1048
- field: field.field,
1049
- stateColumn: field.stateColumn,
1050
- containerKey: field.containerKey ?? field.field,
1051
- rowIdField: field.rowIdField ?? 'id',
1052
- kind: field.kind ?? 'text',
1053
- })),
1054
- stripEnvelope: true,
1055
- });
1056
- }
1057
-
1058
- function stripCrdtYjsMaterializedPayloadFields(
1059
- payload: Record<string, unknown>,
1060
- crdtYjsFields: readonly SyncularCrdtYjsFieldConfig[]
1061
- ): Record<string, unknown> {
1062
- const envelope = objectRecord(payload.__yjs);
1063
- if (crdtYjsFields.length === 0 || Object.keys(envelope).length === 0) {
1064
- return payload;
1065
- }
1066
- let next: Record<string, unknown> | null = null;
1067
- const ensureNext = () => {
1068
- next ??= { ...payload };
1069
- return next;
1070
- };
1071
- for (const field of crdtYjsFields) {
1072
- if (!(field.field in envelope)) continue;
1073
- delete ensureNext()[field.field];
1074
- delete ensureNext()[field.stateColumn];
1075
- }
1076
- return next ?? payload;
1077
- }
1078
-
1079
- async function readCrdtYjsExistingRow(args: {
1080
- client: Pick<SyncularRuntimeClient, 'executeSql'>;
1081
- table: string;
1082
- rowId: string;
1083
- idColumn: string;
1084
- crdtYjsFields: readonly SyncularCrdtYjsFieldConfig[];
1085
- }): Promise<Record<string, unknown> | null> {
1086
- if (args.crdtYjsFields.length === 0) return null;
1087
- const columns = new Set<string>([args.idColumn]);
1088
- for (const field of args.crdtYjsFields) {
1089
- columns.add(field.field);
1090
- columns.add(field.stateColumn);
1091
- }
1092
- const result = await args.client.executeSql(
1093
- `select ${[...columns].map(quoteSqlIdentifier).join(', ')} from ${quoteSqlIdentifier(args.table)} where ${quoteSqlIdentifier(args.idColumn)} = ? limit 1`,
1094
- [args.rowId]
1095
- );
1096
- return result.rows[0] ?? null;
1097
- }
1098
-
1099
- async function readExistingLocalRow(args: {
1100
- client: Pick<SyncularRuntimeClient, 'executeSql'>;
1101
- table: string;
1102
- rowId: string;
1103
- idColumn: string;
1104
- }): Promise<Record<string, unknown> | null> {
1105
- const result = await args.client.executeSql(
1106
- `select * from ${quoteSqlIdentifier(args.table)} where ${quoteSqlIdentifier(args.idColumn)} = ? limit 1`,
1107
- [args.rowId]
1108
- );
1109
- return result.rows[0] ?? null;
1110
- }
1111
-
1112
- function quoteSqlIdentifier(identifier: string): string {
1113
- if (!identifier) throw new Error('SQLite identifier cannot be empty');
1114
- return `"${identifier.replace(/"/g, '""')}"`;
1115
- }
1116
-
1117
- async function readCurrentBaseVersion(
1118
- client: Pick<SyncularRuntimeClient, 'executeSql'>,
1119
- args: {
1120
- table: string;
1121
- rowId: string;
1122
- idColumn: string;
1123
- versionColumn: string;
1124
- }
1125
- ): Promise<number | null> {
1126
- const result = await client.executeSql(
1127
- `select ${quoteSqlIdentifier(args.versionColumn)} as version from ${quoteSqlIdentifier(args.table)} where ${quoteSqlIdentifier(args.idColumn)} = ? limit 1`,
1128
- [args.rowId]
1129
- );
1130
- return coerceBaseVersion(result.rows[0]?.version);
1131
- }
1132
-
1133
- function coerceBaseVersion(value: unknown): number | null {
1134
- if (value == null) return null;
1135
- const numeric = typeof value === 'number' ? value : Number(value);
1136
- if (!Number.isFinite(numeric) || numeric < 0) return null;
1137
- return numeric;
1138
- }
1139
-
1140
- async function resolveBaseVersion(args: {
1141
- options: SyncularMutationsOptions;
1142
- table: string;
1143
- rowId: string;
1144
- idColumn: string;
1145
- versionColumn: string | null;
1146
- explicit?: number | null;
1147
- }): Promise<number | null> {
1148
- if (args.explicit !== undefined) return coerceBaseVersion(args.explicit);
1149
- if (!args.versionColumn) return null;
1150
- const readBaseVersion =
1151
- args.options.readBaseVersion ??
1152
- ((readArgs: {
1153
- table: string;
1154
- rowId: string;
1155
- idColumn: string;
1156
- versionColumn: string;
1157
- }) => readCurrentBaseVersion(args.options.client, readArgs));
1158
- return readBaseVersion({
1159
- table: args.table,
1160
- rowId: args.rowId,
1161
- idColumn: args.idColumn,
1162
- versionColumn: args.versionColumn,
1163
- });
1164
- }
1165
-
1166
- function inferTablesFromCompiledQuery(
1167
- query: CompiledQuery,
1168
- appTables?: ReadonlySet<string>
1169
- ): string[] {
1170
- const tables = new Set<string>();
1171
- collectTables(query.query as OperationNodeLike, tables);
1172
- return [...tables].filter(
1173
- (table) => appTables == null || appTables.has(table)
1174
- );
1175
- }
1176
-
1177
- function inferDependencyHintsFromCompiledQuery(
1178
- query: CompiledQuery,
1179
- tables: readonly string[],
1180
- tableConfig?: SyncularTableConfigMap
1181
- ): SyncularLiveQueryDependencyHint[] {
1182
- if (tables.length !== 1) return [];
1183
- const table = tables[0]!;
1184
- const primaryKey = tableConfig?.[table]?.primaryKeyColumn ?? 'id';
1185
- const rowIds = primaryKeyEqualityValues(query.query, table, primaryKey);
1186
- return rowIds.length > 0 ? [{ table, rowIds }] : [];
1187
- }
1188
-
1189
- function normalizeLiveQueryDependencyHints(
1190
- hints: readonly SyncularLiveQueryDependencyHint[],
1191
- tables: readonly string[],
1192
- appTables?: ReadonlySet<string>
1193
- ): SyncularLiveQueryDependencyHint[] {
1194
- const observedTables = new Set(tables);
1195
- const normalized: SyncularLiveQueryDependencyHint[] = [];
1196
- for (const hint of hints) {
1197
- if (hint.table.length === 0) {
1198
- throw new Error('Live query dependency hint tables must not be empty.');
1199
- }
1200
- if (!observedTables.has(hint.table)) {
1201
- throw new Error(
1202
- `Live query dependency hint table ${hint.table} is not one of the observed tables.`
1203
- );
1204
- }
1205
- if (appTables != null && !appTables.has(hint.table)) {
1206
- throw new Error(
1207
- `Live query dependency hint table ${hint.table} is not part of the generated app schema.`
1208
- );
1209
- }
1210
- const rowIds = uniqueDefinedStrings(hint.rowIds);
1211
- const fields = uniqueDefinedStrings(hint.fields);
1212
- normalized.push({
1213
- table: hint.table,
1214
- ...(rowIds.length > 0 ? { rowIds } : {}),
1215
- ...(fields.length > 0 ? { fields } : {}),
1216
- });
1217
- }
1218
- return normalized;
1219
- }
1220
-
1221
- function primaryKeyEqualityValues(
1222
- query: unknown,
1223
- table: string,
1224
- primaryKey: string
1225
- ): string[] {
1226
- if (!isOperationNode(query) || query.kind !== 'SelectQueryNode') return [];
1227
- const where = query.where;
1228
- if (!isOperationNode(where) || where.kind !== 'WhereNode') return [];
1229
- return collectConjunctivePrimaryKeyValues(where.where, table, primaryKey);
1230
- }
1231
-
1232
- function collectConjunctivePrimaryKeyValues(
1233
- node: unknown,
1234
- table: string,
1235
- primaryKey: string
1236
- ): string[] {
1237
- if (!isOperationNode(node)) return [];
1238
- if (node.kind === 'AndNode') {
1239
- return uniqueStrings([
1240
- ...collectConjunctivePrimaryKeyValues(node.left, table, primaryKey),
1241
- ...collectConjunctivePrimaryKeyValues(node.right, table, primaryKey),
1242
- ]);
1243
- }
1244
- const equality = primaryKeyEqualityValue(node, table, primaryKey);
1245
- return equality == null ? [] : [equality];
1246
- }
1247
-
1248
- function primaryKeyEqualityValue(
1249
- node: unknown,
1250
- table: string,
1251
- primaryKey: string
1252
- ): string | undefined {
1253
- if (!isOperationNode(node) || node.kind !== 'BinaryOperationNode') {
1254
- return undefined;
1255
- }
1256
- const operator = node.operator;
1257
- if (
1258
- !isOperationNode(operator) ||
1259
- operator.kind !== 'OperatorNode' ||
1260
- operator.operator !== '='
1261
- ) {
1262
- return undefined;
1263
- }
1264
- return (
1265
- equalityValueForReference(
1266
- node.leftOperand,
1267
- node.rightOperand,
1268
- table,
1269
- primaryKey
1270
- ) ??
1271
- equalityValueForReference(
1272
- node.rightOperand,
1273
- node.leftOperand,
1274
- table,
1275
- primaryKey
1276
- )
1277
- );
1278
- }
1279
-
1280
- function equalityValueForReference(
1281
- reference: unknown,
1282
- value: unknown,
1283
- table: string,
1284
- primaryKey: string
1285
- ): string | undefined {
1286
- if (!referenceMatchesColumn(reference, table, primaryKey)) return undefined;
1287
- if (!isOperationNode(value) || value.kind !== 'ValueNode') return undefined;
1288
- if (typeof value.value === 'string') return value.value;
1289
- if (typeof value.value === 'number' && Number.isFinite(value.value)) {
1290
- return String(value.value);
1291
- }
1292
- return undefined;
1293
- }
1294
-
1295
- function referenceMatchesColumn(
1296
- reference: unknown,
1297
- table: string,
1298
- column: string
1299
- ): boolean {
1300
- if (!isOperationNode(reference) || reference.kind !== 'ReferenceNode') {
1301
- return false;
1302
- }
1303
- if (
1304
- reference.table != null &&
1305
- tableNameFromTableNode(reference.table) !== table
1306
- ) {
1307
- return false;
1308
- }
1309
- const columnNode = reference.column;
1310
- if (!isOperationNode(columnNode) || columnNode.kind !== 'ColumnNode') {
1311
- return false;
1312
- }
1313
- const identifier = columnNode.column;
1314
- return (
1315
- isOperationNode(identifier) &&
1316
- identifier.kind === 'IdentifierNode' &&
1317
- identifier.name === column
1318
- );
1319
- }
1320
-
1321
- function uniqueStrings(values: readonly string[]): string[] {
1322
- return [...new Set(values)];
1323
- }
1324
-
1325
- function uniqueDefinedStrings(values: readonly string[] | undefined): string[] {
1326
- if (values == null) return [];
1327
- const unique: string[] = [];
1328
- for (const value of values) {
1329
- if (value.length === 0) {
1330
- throw new Error('Live query dependency hint values must not be empty.');
1331
- }
1332
- if (!unique.includes(value)) unique.push(value);
1333
- }
1334
- return unique;
1335
- }
1336
-
1337
- interface OperationNodeLike {
1338
- kind?: string;
1339
- [key: string]: unknown;
1340
- }
1341
-
1342
- function collectTables(node: unknown, tables: Set<string>): void {
1343
- if (Array.isArray(node)) {
1344
- for (const item of node) collectTables(item, tables);
1345
- return;
1346
- }
1347
- if (!isOperationNode(node)) return;
1348
-
1349
- if (node.kind === 'TableNode') collectTableNode(node, tables);
1350
- for (const value of Object.values(node)) collectTables(value, tables);
1351
- }
1352
-
1353
- function collectTableNode(node: unknown, tables: Set<string>): void {
1354
- const table = tableNameFromTableNode(node);
1355
- if (table != null) tables.add(table);
1356
- }
1357
-
1358
- function tableNameFromTableNode(node: unknown): string | undefined {
1359
- if (!isOperationNode(node)) return undefined;
1360
- if (node.kind === 'AliasNode') return tableNameFromTableNode(node.node);
1361
- if (node.kind !== 'TableNode') return undefined;
1362
- const table = node.table;
1363
- if (!isOperationNode(table) || table.kind !== 'SchemableIdentifierNode') {
1364
- return undefined;
1365
- }
1366
- const identifier = table.identifier;
1367
- if (!isOperationNode(identifier) || identifier.kind !== 'IdentifierNode') {
1368
- return undefined;
1369
- }
1370
- return typeof identifier.name === 'string' ? identifier.name : undefined;
1371
- }
1372
-
1373
- function isOperationNode(value: unknown): value is OperationNodeLike {
1374
- return Boolean(value && typeof value === 'object' && 'kind' in value);
1375
- }
1376
-
1377
- function normalizeLiveQueryTables(
1378
- tables: readonly string[],
1379
- appTables?: ReadonlySet<string>
1380
- ): string[] {
1381
- const normalized: string[] = [];
1382
- for (const table of tables) {
1383
- if (table.length === 0) {
1384
- throw new Error(
1385
- 'Live query table dependencies must not contain empty names.'
1386
- );
1387
- }
1388
- if (appTables != null && !appTables.has(table)) {
1389
- throw new Error(
1390
- `Live query table ${table} is not part of the generated app schema.`
1391
- );
1392
- }
1393
- if (!normalized.includes(table)) normalized.push(table);
68
+ throw error;
1394
69
  }
1395
- return normalized;
1396
70
  }