@syncular/client 0.0.6-95 → 0.1.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 (356) hide show
  1. package/README.md +713 -11
  2. package/dist/auth-leases.d.ts +11 -0
  3. package/dist/auth-leases.d.ts.map +1 -0
  4. package/dist/auth-leases.js +140 -0
  5. package/dist/auth-leases.js.map +1 -0
  6. package/dist/blob-limits.d.ts +15 -0
  7. package/dist/blob-limits.d.ts.map +1 -0
  8. package/dist/blob-limits.js +66 -0
  9. package/dist/blob-limits.js.map +1 -0
  10. package/dist/bridge-client.d.ts +69 -0
  11. package/dist/bridge-client.d.ts.map +1 -0
  12. package/dist/bridge-client.js +282 -0
  13. package/dist/bridge-client.js.map +1 -0
  14. package/dist/client-config.d.ts +6 -0
  15. package/dist/client-config.d.ts.map +1 -0
  16. package/dist/client-config.js +18 -0
  17. package/dist/client-config.js.map +1 -0
  18. package/dist/client.d.ts +65 -397
  19. package/dist/client.d.ts.map +1 -1
  20. package/dist/client.js +150 -960
  21. package/dist/client.js.map +1 -1
  22. package/dist/command-history.d.ts +35 -0
  23. package/dist/command-history.d.ts.map +1 -0
  24. package/dist/command-history.js +378 -0
  25. package/dist/command-history.js.map +1 -0
  26. package/dist/console-diagnostics.d.ts +33 -0
  27. package/dist/console-diagnostics.d.ts.map +1 -0
  28. package/dist/console-diagnostics.js +496 -0
  29. package/dist/console-diagnostics.js.map +1 -0
  30. package/dist/crdt-yjs/index.d.ts +4 -0
  31. package/dist/crdt-yjs/index.d.ts.map +1 -0
  32. package/dist/crdt-yjs/index.js +4 -0
  33. package/dist/crdt-yjs/index.js.map +1 -0
  34. package/dist/crdt-yjs/webview-host-facade.d.ts +126 -0
  35. package/dist/crdt-yjs/webview-host-facade.d.ts.map +1 -0
  36. package/dist/crdt-yjs/webview-host-facade.js +284 -0
  37. package/dist/crdt-yjs/webview-host-facade.js.map +1 -0
  38. package/dist/crdt-yjs/yjs-document-field-adapter.d.ts +153 -0
  39. package/dist/crdt-yjs/yjs-document-field-adapter.d.ts.map +1 -0
  40. package/dist/crdt-yjs/yjs-document-field-adapter.js +406 -0
  41. package/dist/crdt-yjs/yjs-document-field-adapter.js.map +1 -0
  42. package/dist/crdt-yjs/yjs-prosemirror-bridge.d.ts +73 -0
  43. package/dist/crdt-yjs/yjs-prosemirror-bridge.d.ts.map +1 -0
  44. package/dist/crdt-yjs/yjs-prosemirror-bridge.js +169 -0
  45. package/dist/crdt-yjs/yjs-prosemirror-bridge.js.map +1 -0
  46. package/dist/database.d.ts +83 -0
  47. package/dist/database.d.ts.map +1 -0
  48. package/dist/database.js +916 -0
  49. package/dist/database.js.map +1 -0
  50. package/dist/diagnostics.d.ts +10 -0
  51. package/dist/diagnostics.d.ts.map +1 -0
  52. package/dist/diagnostics.js +83 -0
  53. package/dist/diagnostics.js.map +1 -0
  54. package/dist/errors.d.ts +24 -0
  55. package/dist/errors.d.ts.map +1 -0
  56. package/dist/errors.js +211 -0
  57. package/dist/errors.js.map +1 -0
  58. package/dist/generated-bridge.d.ts +365 -0
  59. package/dist/generated-bridge.d.ts.map +1 -0
  60. package/dist/generated-bridge.js +250 -0
  61. package/dist/generated-bridge.js.map +1 -0
  62. package/dist/index.d.ts +13 -23
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +14 -25
  65. package/dist/index.js.map +1 -1
  66. package/dist/mutations.d.ts +4 -72
  67. package/dist/mutations.d.ts.map +1 -1
  68. package/dist/mutations.js +2 -568
  69. package/dist/mutations.js.map +1 -1
  70. package/dist/network.d.ts +3 -0
  71. package/dist/network.d.ts.map +1 -0
  72. package/dist/network.js +17 -0
  73. package/dist/network.js.map +1 -0
  74. package/dist/react/index.d.ts +169 -0
  75. package/dist/react/index.d.ts.map +1 -0
  76. package/dist/react/index.js +628 -0
  77. package/dist/react/index.js.map +1 -0
  78. package/dist/react-native/index.d.ts +35 -0
  79. package/dist/react-native/index.d.ts.map +1 -0
  80. package/dist/react-native/index.js +49 -0
  81. package/dist/react-native/index.js.map +1 -0
  82. package/dist/runtime-contract.d.ts +13 -0
  83. package/dist/runtime-contract.d.ts.map +1 -0
  84. package/dist/runtime-contract.js +24 -0
  85. package/dist/runtime-contract.js.map +1 -0
  86. package/dist/rust-client.d.ts +106 -0
  87. package/dist/rust-client.d.ts.map +1 -0
  88. package/dist/rust-client.js +936 -0
  89. package/dist/rust-client.js.map +1 -0
  90. package/dist/sentry.d.ts +35 -0
  91. package/dist/sentry.d.ts.map +1 -0
  92. package/dist/sentry.js +155 -0
  93. package/dist/sentry.js.map +1 -0
  94. package/dist/sql-safety.d.ts +3 -0
  95. package/dist/sql-safety.d.ts.map +1 -0
  96. package/dist/sql-safety.js +62 -0
  97. package/dist/sql-safety.js.map +1 -0
  98. package/dist/syncular-runtime-artifacts.json +61 -0
  99. package/dist/tauri/index.d.ts +35 -0
  100. package/dist/tauri/index.d.ts.map +1 -0
  101. package/dist/tauri/index.js +114 -0
  102. package/dist/tauri/index.js.map +1 -0
  103. package/dist/types.d.ts +1059 -0
  104. package/dist/types.d.ts.map +1 -0
  105. package/dist/types.js +2 -0
  106. package/dist/types.js.map +1 -0
  107. package/dist/wasm/.syncular-wasm-profile +1 -0
  108. package/dist/wasm/syncular-runtime-artifact.json +21 -0
  109. package/dist/wasm/syncular.d.ts +207 -0
  110. package/dist/wasm/syncular.js +2341 -0
  111. package/dist/wasm/syncular_bg.wasm +0 -0
  112. package/dist/wasm/syncular_bg.wasm.d.ts +97 -0
  113. package/dist/wasm-bindings/runtime-contract.d.ts +22 -0
  114. package/dist/wasm-bindings/runtime-contract.d.ts.map +1 -0
  115. package/dist/wasm-bindings/runtime-contract.js +112 -0
  116. package/dist/wasm-bindings/runtime-contract.js.map +1 -0
  117. package/dist/wasm-core/.syncular-wasm-profile +1 -0
  118. package/dist/wasm-core/syncular-runtime-artifact.json +17 -0
  119. package/dist/wasm-core/syncular.d.ts +162 -0
  120. package/dist/wasm-core/syncular.js +1847 -0
  121. package/dist/wasm-core/syncular_bg.wasm +0 -0
  122. package/dist/wasm-core/syncular_bg.wasm.d.ts +77 -0
  123. package/dist/wasm-perf/.syncular-wasm-profile +1 -0
  124. package/dist/wasm-perf/syncular-runtime-artifact.json +21 -0
  125. package/dist/wasm-perf/syncular.d.ts +207 -0
  126. package/dist/wasm-perf/syncular.js +2341 -0
  127. package/dist/wasm-perf/syncular_bg.wasm +0 -0
  128. package/dist/wasm-perf/syncular_bg.wasm.d.ts +97 -0
  129. package/dist/wasm-runtime.d.ts +18 -0
  130. package/dist/wasm-runtime.d.ts.map +1 -0
  131. package/dist/wasm-runtime.js +28 -0
  132. package/dist/wasm-runtime.js.map +1 -0
  133. package/dist/worker-client.d.ts +123 -0
  134. package/dist/worker-client.d.ts.map +1 -0
  135. package/dist/worker-client.js +1686 -0
  136. package/dist/worker-client.js.map +1 -0
  137. package/dist/worker-entry.d.ts +2 -0
  138. package/dist/worker-entry.d.ts.map +1 -0
  139. package/dist/worker-entry.js +479 -0
  140. package/dist/worker-entry.js.map +1 -0
  141. package/dist/worker-protocol.d.ts +64 -0
  142. package/dist/worker-protocol.d.ts.map +1 -0
  143. package/dist/worker-protocol.js +16 -0
  144. package/dist/worker-protocol.js.map +1 -0
  145. package/dist/worker-realtime.d.ts +39 -0
  146. package/dist/worker-realtime.d.ts.map +1 -0
  147. package/dist/worker-realtime.js +677 -0
  148. package/dist/worker-realtime.js.map +1 -0
  149. package/package.json +124 -17
  150. package/src/auth-leases.ts +251 -0
  151. package/src/blob-limits.ts +98 -0
  152. package/src/bridge-client.ts +512 -0
  153. package/src/client-config.ts +29 -0
  154. package/src/client.ts +256 -1414
  155. package/src/command-history.ts +623 -0
  156. package/src/console-diagnostics.ts +617 -0
  157. package/src/crdt-yjs/index.ts +3 -0
  158. package/src/crdt-yjs/webview-host-facade.ts +477 -0
  159. package/src/crdt-yjs/yjs-document-field-adapter.ts +733 -0
  160. package/src/crdt-yjs/yjs-prosemirror-bridge.ts +272 -0
  161. package/src/database.ts +1342 -0
  162. package/src/diagnostics.ts +116 -0
  163. package/src/errors.ts +269 -0
  164. package/src/generated-bridge.ts +741 -0
  165. package/src/index.ts +21 -25
  166. package/src/mutations.ts +12 -821
  167. package/src/network.ts +32 -0
  168. package/src/react/index.ts +1036 -0
  169. package/src/react-native/index.ts +152 -0
  170. package/src/runtime-contract.ts +48 -0
  171. package/src/rust-client.ts +1488 -0
  172. package/src/sentry.ts +215 -0
  173. package/src/sql-safety.ts +61 -0
  174. package/src/tauri/index.ts +211 -0
  175. package/src/types.ts +1356 -0
  176. package/src/wasm-bindings/generated-wasm-bindings.d.ts +70 -0
  177. package/src/wasm-bindings/runtime-contract.ts +158 -0
  178. package/src/wasm-runtime.ts +76 -0
  179. package/src/worker-client.ts +2215 -0
  180. package/src/worker-entry.ts +584 -0
  181. package/src/worker-protocol.ts +109 -0
  182. package/src/worker-realtime.ts +843 -0
  183. package/dist/blobs/index.d.ts +0 -7
  184. package/dist/blobs/index.d.ts.map +0 -1
  185. package/dist/blobs/index.js +0 -7
  186. package/dist/blobs/index.js.map +0 -1
  187. package/dist/blobs/manager.d.ts +0 -345
  188. package/dist/blobs/manager.d.ts.map +0 -1
  189. package/dist/blobs/manager.js +0 -749
  190. package/dist/blobs/manager.js.map +0 -1
  191. package/dist/blobs/migrate.d.ts +0 -14
  192. package/dist/blobs/migrate.d.ts.map +0 -1
  193. package/dist/blobs/migrate.js +0 -59
  194. package/dist/blobs/migrate.js.map +0 -1
  195. package/dist/blobs/types.d.ts +0 -62
  196. package/dist/blobs/types.d.ts.map +0 -1
  197. package/dist/blobs/types.js +0 -5
  198. package/dist/blobs/types.js.map +0 -1
  199. package/dist/conflicts.d.ts +0 -31
  200. package/dist/conflicts.d.ts.map +0 -1
  201. package/dist/conflicts.js +0 -112
  202. package/dist/conflicts.js.map +0 -1
  203. package/dist/create-client.d.ts +0 -118
  204. package/dist/create-client.d.ts.map +0 -1
  205. package/dist/create-client.js +0 -178
  206. package/dist/create-client.js.map +0 -1
  207. package/dist/engine/SyncEngine.d.ts +0 -272
  208. package/dist/engine/SyncEngine.d.ts.map +0 -1
  209. package/dist/engine/SyncEngine.js +0 -1860
  210. package/dist/engine/SyncEngine.js.map +0 -1
  211. package/dist/engine/index.d.ts +0 -6
  212. package/dist/engine/index.d.ts.map +0 -1
  213. package/dist/engine/index.js +0 -6
  214. package/dist/engine/index.js.map +0 -1
  215. package/dist/engine/types.d.ts +0 -345
  216. package/dist/engine/types.d.ts.map +0 -1
  217. package/dist/engine/types.js +0 -7
  218. package/dist/engine/types.js.map +0 -1
  219. package/dist/handlers/collection.d.ts +0 -6
  220. package/dist/handlers/collection.d.ts.map +0 -1
  221. package/dist/handlers/collection.js +0 -21
  222. package/dist/handlers/collection.js.map +0 -1
  223. package/dist/handlers/create-handler.d.ts +0 -120
  224. package/dist/handlers/create-handler.d.ts.map +0 -1
  225. package/dist/handlers/create-handler.js +0 -145
  226. package/dist/handlers/create-handler.js.map +0 -1
  227. package/dist/handlers/types.d.ts +0 -83
  228. package/dist/handlers/types.d.ts.map +0 -1
  229. package/dist/handlers/types.js +0 -5
  230. package/dist/handlers/types.js.map +0 -1
  231. package/dist/migrate.d.ts +0 -19
  232. package/dist/migrate.d.ts.map +0 -1
  233. package/dist/migrate.js +0 -238
  234. package/dist/migrate.js.map +0 -1
  235. package/dist/outbox.d.ts +0 -112
  236. package/dist/outbox.d.ts.map +0 -1
  237. package/dist/outbox.js +0 -294
  238. package/dist/outbox.js.map +0 -1
  239. package/dist/plugins/incrementing-version.d.ts +0 -34
  240. package/dist/plugins/incrementing-version.d.ts.map +0 -1
  241. package/dist/plugins/incrementing-version.js +0 -83
  242. package/dist/plugins/incrementing-version.js.map +0 -1
  243. package/dist/plugins/index.d.ts +0 -3
  244. package/dist/plugins/index.d.ts.map +0 -1
  245. package/dist/plugins/index.js +0 -3
  246. package/dist/plugins/index.js.map +0 -1
  247. package/dist/plugins/types.d.ts +0 -49
  248. package/dist/plugins/types.d.ts.map +0 -1
  249. package/dist/plugins/types.js +0 -15
  250. package/dist/plugins/types.js.map +0 -1
  251. package/dist/proxy/connection.d.ts +0 -33
  252. package/dist/proxy/connection.d.ts.map +0 -1
  253. package/dist/proxy/connection.js +0 -153
  254. package/dist/proxy/connection.js.map +0 -1
  255. package/dist/proxy/dialect.d.ts +0 -46
  256. package/dist/proxy/dialect.d.ts.map +0 -1
  257. package/dist/proxy/dialect.js +0 -58
  258. package/dist/proxy/dialect.js.map +0 -1
  259. package/dist/proxy/driver.d.ts +0 -42
  260. package/dist/proxy/driver.d.ts.map +0 -1
  261. package/dist/proxy/driver.js +0 -78
  262. package/dist/proxy/driver.js.map +0 -1
  263. package/dist/proxy/index.d.ts +0 -10
  264. package/dist/proxy/index.d.ts.map +0 -1
  265. package/dist/proxy/index.js +0 -10
  266. package/dist/proxy/index.js.map +0 -1
  267. package/dist/proxy/mutations.d.ts +0 -9
  268. package/dist/proxy/mutations.d.ts.map +0 -1
  269. package/dist/proxy/mutations.js +0 -11
  270. package/dist/proxy/mutations.js.map +0 -1
  271. package/dist/pull-engine.d.ts +0 -48
  272. package/dist/pull-engine.d.ts.map +0 -1
  273. package/dist/pull-engine.js +0 -648
  274. package/dist/pull-engine.js.map +0 -1
  275. package/dist/push-engine.d.ts +0 -18
  276. package/dist/push-engine.d.ts.map +0 -1
  277. package/dist/push-engine.js +0 -167
  278. package/dist/push-engine.js.map +0 -1
  279. package/dist/query/FingerprintCollector.d.ts +0 -18
  280. package/dist/query/FingerprintCollector.d.ts.map +0 -1
  281. package/dist/query/FingerprintCollector.js +0 -28
  282. package/dist/query/FingerprintCollector.js.map +0 -1
  283. package/dist/query/QueryContext.d.ts +0 -33
  284. package/dist/query/QueryContext.d.ts.map +0 -1
  285. package/dist/query/QueryContext.js +0 -16
  286. package/dist/query/QueryContext.js.map +0 -1
  287. package/dist/query/fingerprint.d.ts +0 -61
  288. package/dist/query/fingerprint.d.ts.map +0 -1
  289. package/dist/query/fingerprint.js +0 -91
  290. package/dist/query/fingerprint.js.map +0 -1
  291. package/dist/query/index.d.ts +0 -7
  292. package/dist/query/index.d.ts.map +0 -1
  293. package/dist/query/index.js +0 -7
  294. package/dist/query/index.js.map +0 -1
  295. package/dist/query/tracked-select.d.ts +0 -18
  296. package/dist/query/tracked-select.d.ts.map +0 -1
  297. package/dist/query/tracked-select.js +0 -90
  298. package/dist/query/tracked-select.js.map +0 -1
  299. package/dist/schema.d.ts +0 -83
  300. package/dist/schema.d.ts.map +0 -1
  301. package/dist/schema.js +0 -7
  302. package/dist/schema.js.map +0 -1
  303. package/dist/subscription-state.d.ts +0 -46
  304. package/dist/subscription-state.d.ts.map +0 -1
  305. package/dist/subscription-state.js +0 -185
  306. package/dist/subscription-state.js.map +0 -1
  307. package/dist/sync-loop.d.ts +0 -34
  308. package/dist/sync-loop.d.ts.map +0 -1
  309. package/dist/sync-loop.js +0 -253
  310. package/dist/sync-loop.js.map +0 -1
  311. package/dist/sync.d.ts +0 -32
  312. package/dist/sync.d.ts.map +0 -1
  313. package/dist/sync.js +0 -55
  314. package/dist/sync.js.map +0 -1
  315. package/dist/utils/id.d.ts +0 -17
  316. package/dist/utils/id.d.ts.map +0 -1
  317. package/dist/utils/id.js +0 -46
  318. package/dist/utils/id.js.map +0 -1
  319. package/src/blobs/index.ts +0 -7
  320. package/src/blobs/manager.ts +0 -1027
  321. package/src/blobs/migrate.ts +0 -67
  322. package/src/blobs/types.ts +0 -84
  323. package/src/client.test.ts +0 -417
  324. package/src/conflicts.ts +0 -171
  325. package/src/create-client.test.ts +0 -83
  326. package/src/create-client.ts +0 -330
  327. package/src/engine/SyncEngine.test.ts +0 -254
  328. package/src/engine/SyncEngine.ts +0 -2375
  329. package/src/engine/index.ts +0 -6
  330. package/src/engine/types.ts +0 -419
  331. package/src/handlers/collection.ts +0 -36
  332. package/src/handlers/create-handler.ts +0 -330
  333. package/src/handlers/types.ts +0 -108
  334. package/src/migrate.ts +0 -318
  335. package/src/outbox.ts +0 -383
  336. package/src/plugins/incrementing-version.ts +0 -133
  337. package/src/plugins/index.ts +0 -2
  338. package/src/plugins/types.ts +0 -63
  339. package/src/proxy/connection.ts +0 -191
  340. package/src/proxy/dialect.ts +0 -76
  341. package/src/proxy/driver.ts +0 -126
  342. package/src/proxy/index.ts +0 -10
  343. package/src/proxy/mutations.ts +0 -18
  344. package/src/pull-engine.test.ts +0 -151
  345. package/src/pull-engine.ts +0 -855
  346. package/src/push-engine.ts +0 -216
  347. package/src/query/FingerprintCollector.ts +0 -29
  348. package/src/query/QueryContext.ts +0 -54
  349. package/src/query/fingerprint.ts +0 -109
  350. package/src/query/index.ts +0 -10
  351. package/src/query/tracked-select.ts +0 -139
  352. package/src/schema.ts +0 -94
  353. package/src/subscription-state.ts +0 -259
  354. package/src/sync-loop.ts +0 -379
  355. package/src/sync.ts +0 -170
  356. package/src/utils/id.ts +0 -55
@@ -0,0 +1,916 @@
1
+ import { applyCodecsToDbRow, createColumnCodecsPlugin, createTableColumnCodecsResolver, randomId, } from '@syncular/core';
2
+ import { Kysely, CompiledQuery as KyselyCompiledQuery, } from 'kysely';
3
+ import { BaseSqliteDialect, BaseSqliteDriver } from 'kysely-generic-sqlite';
4
+ import { assertSyncularBlobPayloadLimit, syncularBlobInputSize, } from './blob-limits';
5
+ import { getSyncularClientStatus, SyncularClientLifecycle, } from './client';
6
+ import { createSyncularConsoleDiagnosticsPublisher } from './console-diagnostics';
7
+ import { isSyncularOfflineError } from './errors';
8
+ import { createMutationsApi, } from './mutations';
9
+ import { browserSyncularNetworkStatusSource } from './network';
10
+ import { assertSyncularReadonlySql } from './sql-safety';
11
+ import { createSyncularWorkerClient } from './worker-client';
12
+ export async function withSyncularSchemaWrites(database, callback) {
13
+ const client = assertUnsafeSqlClient(database.client);
14
+ const dialect = createSyncularDialect(client, { unsafeWrites: true });
15
+ const db = new Kysely({ dialect });
16
+ try {
17
+ return await callback(db);
18
+ }
19
+ finally {
20
+ await dialect.destroyLiveQueries();
21
+ await db.destroy();
22
+ }
23
+ }
24
+ export async function createSyncularDatabase(options) {
25
+ const client = await createSyncularWorkerClient(options);
26
+ const dialect = createSyncularDialect(client, {
27
+ appTables: options.appTables,
28
+ tableConfig: options.tableConfig,
29
+ });
30
+ const db = new Kysely({
31
+ dialect,
32
+ plugins: options.codecs
33
+ ? [
34
+ createColumnCodecsPlugin({
35
+ codecs: options.codecs,
36
+ dialect: 'sqlite',
37
+ }),
38
+ ]
39
+ : undefined,
40
+ });
41
+ let closed = false;
42
+ const localClientMode = (options.config.mode ?? 'remote') !== 'remote';
43
+ const mutationSyncScheduler = createMutationSyncScheduler(client, {
44
+ enabled: options.sync?.autoSyncAfterMutation ?? !localClientMode,
45
+ debounceMs: options.sync?.mutationSyncDebounceMs ?? 10,
46
+ network: options.sync?.network === false
47
+ ? undefined
48
+ : (options.sync?.network ?? browserSyncularNetworkStatusSource()),
49
+ isClosed: () => closed,
50
+ });
51
+ const blobUploadScheduler = createBlobUploadScheduler(client, {
52
+ enabled: options.sync?.autoProcessBlobUploadsAfterStore ?? false,
53
+ debounceMs: options.sync?.blobUploadDebounceMs ?? 10,
54
+ isClosed: () => closed,
55
+ });
56
+ const consoleDiagnostics = options.consoleDiagnostics === undefined ||
57
+ options.consoleDiagnostics === false
58
+ ? undefined
59
+ : createSyncularConsoleDiagnosticsPublisher(client, {
60
+ ...(options.consoleDiagnostics === true
61
+ ? {}
62
+ : options.consoleDiagnostics),
63
+ config: options.config,
64
+ isClosed: () => closed,
65
+ });
66
+ const mutations = createSyncularMutations({
67
+ client,
68
+ codecs: options.codecs,
69
+ codecDialect: 'sqlite',
70
+ tableConfig: options.tableConfig,
71
+ readBaseVersion: (args) => readCurrentBaseVersion(client, args),
72
+ afterCommit: () => mutationSyncScheduler.schedule(),
73
+ });
74
+ const leasedMutations = createSyncularMutations({
75
+ client,
76
+ requireAuthLease: true,
77
+ codecs: options.codecs,
78
+ codecDialect: 'sqlite',
79
+ tableConfig: options.tableConfig,
80
+ readBaseVersion: (args) => readCurrentBaseVersion(client, args),
81
+ afterCommit: () => mutationSyncScheduler.schedule(),
82
+ });
83
+ const blobs = createSyncularBlobClient(client, {
84
+ diagnostics: options.diagnostics,
85
+ limits: options.blobLimits,
86
+ afterStore: ({ options }) => {
87
+ if (options?.immediate)
88
+ return;
89
+ blobUploadScheduler.schedule();
90
+ },
91
+ });
92
+ const lifecycle = new SyncularClientLifecycle(client, {
93
+ realtime: options.realtime ?? true,
94
+ initialSync: options.lifecycle?.initialSync,
95
+ syncOnRealtimeConnect: options.lifecycle?.syncOnRealtimeConnect,
96
+ pollIntervalMs: options.pollIntervalMs,
97
+ network: options.sync?.network,
98
+ });
99
+ const database = {
100
+ db,
101
+ client,
102
+ dialect,
103
+ mutations,
104
+ leasedMutations,
105
+ blobs,
106
+ lifecycle,
107
+ live: (query, liveOptions) => dialect.live(query, liveOptions),
108
+ start: () => lifecycle.start(),
109
+ stop: () => lifecycle.stop(),
110
+ sync: () => lifecycle.sync(),
111
+ on: (event, listener) => client.addEventListener(event, listener),
112
+ getStatus: () => getSyncularClientStatus(client),
113
+ setSubscriptions: (subscriptions) => client.setSubscriptions(subscriptions),
114
+ resumeFromBackground: (syncOptions) => client.resumeFromBackground(syncOptions),
115
+ issueAuthLease: (request) => client.issueAuthLease(request),
116
+ upsertAuthLease: (lease) => client.upsertAuthLease(lease),
117
+ authLease: (leaseId) => client.authLease(leaseId),
118
+ activeAuthLeases: (actorId, nowMs) => client.activeAuthLeases(actorId, nowMs),
119
+ diagnosticSnapshot: () => client.diagnosticSnapshot(),
120
+ presence: {
121
+ get: (scopeKey) => client.getPresence(scopeKey),
122
+ join: (scopeKey, metadata) => client.joinPresence(scopeKey, metadata),
123
+ leave: (scopeKey) => client.leavePresence(scopeKey),
124
+ updateMetadata: (scopeKey, metadata) => client.updatePresenceMetadata(scopeKey, metadata),
125
+ onChange: (listener) => client.addPresenceListener(listener),
126
+ },
127
+ conflicts: {
128
+ list: () => client.conflictSummaries(),
129
+ retryKeepLocal: (id) => client.retryConflictKeepLocal(id),
130
+ resolve: (id, resolution) => client.resolveConflict(id, resolution),
131
+ },
132
+ async close() {
133
+ if (closed)
134
+ return;
135
+ closed = true;
136
+ mutationSyncScheduler.destroy();
137
+ blobUploadScheduler.destroy();
138
+ consoleDiagnostics?.destroy();
139
+ try {
140
+ await lifecycle.stop().catch(() => undefined);
141
+ await dialect.destroyLiveQueries();
142
+ await db.destroy();
143
+ }
144
+ finally {
145
+ await client.close();
146
+ }
147
+ },
148
+ };
149
+ try {
150
+ if (options.subscriptions) {
151
+ await client.setSubscriptions(options.subscriptions);
152
+ }
153
+ if (options.lifecycle?.autoStart ?? !localClientMode) {
154
+ await lifecycle.start();
155
+ }
156
+ }
157
+ catch (error) {
158
+ await database.close().catch(() => undefined);
159
+ throw error;
160
+ }
161
+ return database;
162
+ }
163
+ function createMutationSyncScheduler(client, options) {
164
+ let timer;
165
+ let inFlight;
166
+ let queued = false;
167
+ const isOnline = () => options.network?.isOnline() !== false;
168
+ const clear = () => {
169
+ if (timer)
170
+ clearTimeout(timer);
171
+ timer = undefined;
172
+ };
173
+ const run = async () => {
174
+ if (options.isClosed())
175
+ return;
176
+ if (!isOnline()) {
177
+ queued = true;
178
+ return;
179
+ }
180
+ if (inFlight) {
181
+ queued = true;
182
+ return;
183
+ }
184
+ inFlight = client
185
+ .syncOnce()
186
+ .then(() => undefined)
187
+ .catch((error) => {
188
+ if (!isOnline() || isSyncularOfflineError(error))
189
+ queued = true;
190
+ })
191
+ .finally(() => {
192
+ inFlight = undefined;
193
+ if (queued && !options.isClosed() && isOnline()) {
194
+ queued = false;
195
+ schedule();
196
+ }
197
+ });
198
+ await inFlight;
199
+ };
200
+ const schedule = () => {
201
+ if (!options.enabled || options.isClosed())
202
+ return;
203
+ if (!isOnline()) {
204
+ queued = true;
205
+ clear();
206
+ return;
207
+ }
208
+ if (inFlight) {
209
+ queued = true;
210
+ return;
211
+ }
212
+ clear();
213
+ if (options.debounceMs === false || options.debounceMs <= 0) {
214
+ queueMicrotask(() => void run());
215
+ return;
216
+ }
217
+ timer = setTimeout(() => void run(), options.debounceMs);
218
+ };
219
+ const handleOnline = () => {
220
+ if (!queued || options.isClosed())
221
+ return;
222
+ queued = false;
223
+ schedule();
224
+ };
225
+ options.network?.addEventListener?.('online', handleOnline);
226
+ return {
227
+ schedule,
228
+ destroy() {
229
+ clear();
230
+ queued = false;
231
+ options.network?.removeEventListener?.('online', handleOnline);
232
+ },
233
+ };
234
+ }
235
+ function createBlobUploadScheduler(client, options) {
236
+ let timer;
237
+ let inFlight;
238
+ let queued = false;
239
+ const clear = () => {
240
+ if (timer)
241
+ clearTimeout(timer);
242
+ timer = undefined;
243
+ };
244
+ const run = async () => {
245
+ if (options.isClosed())
246
+ return;
247
+ if (inFlight) {
248
+ queued = true;
249
+ return;
250
+ }
251
+ inFlight = client
252
+ .processBlobUploadQueue()
253
+ .then(() => undefined)
254
+ .catch(() => undefined)
255
+ .finally(() => {
256
+ inFlight = undefined;
257
+ if (queued && !options.isClosed()) {
258
+ queued = false;
259
+ schedule();
260
+ }
261
+ });
262
+ await inFlight;
263
+ };
264
+ const schedule = () => {
265
+ if (!options.enabled || options.isClosed())
266
+ return;
267
+ if (inFlight) {
268
+ queued = true;
269
+ return;
270
+ }
271
+ clear();
272
+ if (options.debounceMs === false || options.debounceMs <= 0) {
273
+ queueMicrotask(() => void run());
274
+ return;
275
+ }
276
+ timer = setTimeout(() => void run(), options.debounceMs);
277
+ };
278
+ return {
279
+ schedule,
280
+ destroy() {
281
+ clear();
282
+ queued = false;
283
+ },
284
+ };
285
+ }
286
+ export function createSyncularBlobClient(client, hooks = {}) {
287
+ const assertRetrieveWithinLimit = (ref) => assertSyncularBlobPayloadLimit({
288
+ operation: 'retrieve',
289
+ size: ref.size,
290
+ limits: hooks.limits,
291
+ refHash: ref.hash,
292
+ diagnostics: hooks.diagnostics,
293
+ });
294
+ return {
295
+ async store(data, storeOptions) {
296
+ assertSyncularBlobPayloadLimit({
297
+ operation: 'store',
298
+ size: syncularBlobInputSize(data),
299
+ limits: hooks.limits,
300
+ options: storeOptions,
301
+ diagnostics: hooks.diagnostics,
302
+ });
303
+ const ref = await client.storeBlob(await toUint8Array(data), storeOptions);
304
+ await hooks.afterStore?.({
305
+ ref,
306
+ ...(storeOptions === undefined ? {} : { options: storeOptions }),
307
+ });
308
+ return ref;
309
+ },
310
+ async retrieve(ref) {
311
+ assertRetrieveWithinLimit(ref);
312
+ return client.retrieveBlob(ref);
313
+ },
314
+ isLocal(hash) {
315
+ return client.isBlobLocal(hash);
316
+ },
317
+ async preload(refs) {
318
+ for (const ref of refs)
319
+ assertRetrieveWithinLimit(ref);
320
+ await Promise.all(refs.map((ref) => client.retrieveBlob(ref)));
321
+ },
322
+ processUploadQueue(options) {
323
+ return client.processBlobUploadQueue(options);
324
+ },
325
+ getUploadQueueStats() {
326
+ return client.blobUploadQueueStats();
327
+ },
328
+ getCacheStats() {
329
+ return client.blobCacheStats();
330
+ },
331
+ pruneCache(maxBytes) {
332
+ return client.pruneBlobCache(maxBytes);
333
+ },
334
+ clearCache() {
335
+ return client.clearBlobCache();
336
+ },
337
+ };
338
+ }
339
+ export function createSyncularDialect(client, options = {}) {
340
+ const driver = new SyncularDriver(client, options);
341
+ const dialect = new BaseSqliteDialect(() => driver);
342
+ dialect.live = (query, liveOptions) => driver.live(query, liveOptions);
343
+ dialect.destroyLiveQueries = () => driver.destroy();
344
+ return dialect;
345
+ }
346
+ export function createSyncularMutations(options) {
347
+ return createMutationsApi(createSyncularCommit(options));
348
+ }
349
+ export function createSyncularCommit(options) {
350
+ const idColumn = options.idColumn ?? 'id';
351
+ const versionColumn = options.versionColumn ?? 'server_version';
352
+ const omitColumns = options.omitColumns ?? [];
353
+ const codecDialect = options.codecDialect ?? 'sqlite';
354
+ const resolveTableCodecs = createTableColumnCodecsResolver(options.codecs, {
355
+ dialect: codecDialect,
356
+ });
357
+ return async (fn) => {
358
+ const operations = [];
359
+ const batch = [];
360
+ const localMutations = [];
361
+ const txTableCache = new Map();
362
+ const makeTxTable = (table) => {
363
+ const cached = txTableCache.get(table);
364
+ if (cached)
365
+ return cached;
366
+ const tableConfig = options.tableConfig?.[table];
367
+ const tableIdColumn = tableConfig?.primaryKeyColumn ?? idColumn;
368
+ const tableVersionColumn = tableConfig?.serverVersionColumn === undefined
369
+ ? versionColumn
370
+ : tableConfig.serverVersionColumn;
371
+ const softDeleteColumn = tableConfig?.softDeleteColumn ?? null;
372
+ const crdtYjsFields = serverMergeCrdtYjsFields(tableConfig?.crdtYjsFields ?? []);
373
+ const prepareInsert = async (values) => {
374
+ const raw = objectRecord(values);
375
+ const rawId = raw[tableIdColumn];
376
+ const id = typeof rawId === 'string' && rawId ? rawId : randomId();
377
+ const row = { ...raw, [tableIdColumn]: id };
378
+ const payload = sanitizeOperationPayload(row, {
379
+ omit: [
380
+ tableIdColumn,
381
+ ...(tableVersionColumn ? [tableVersionColumn] : []),
382
+ ...omitColumns,
383
+ ],
384
+ });
385
+ const syncPayload = stripCrdtYjsMaterializedPayloadFields(payload, crdtYjsFields);
386
+ const localPayload = sanitizeOperationPayload(row, {
387
+ omit: [
388
+ tableIdColumn,
389
+ ...(tableVersionColumn ? [tableVersionColumn] : []),
390
+ ],
391
+ });
392
+ const transformedLocalPayload = await transformCrdtYjsMutationPayload({
393
+ client: options.client,
394
+ table,
395
+ rowId: id,
396
+ payload: localPayload,
397
+ crdtYjsFields,
398
+ });
399
+ const localDbPayload = applyCodecsToDbRow(transformedLocalPayload, resolveTableCodecs(table, transformedLocalPayload), codecDialect);
400
+ const operation = {
401
+ table,
402
+ row_id: id,
403
+ op: 'upsert',
404
+ payload: syncPayload,
405
+ base_version: null,
406
+ };
407
+ return {
408
+ id,
409
+ operation,
410
+ localRow: { ...localDbPayload, [tableIdColumn]: id },
411
+ };
412
+ };
413
+ const tableApi = {
414
+ async insert(values) {
415
+ const prepared = await prepareInsert(values);
416
+ const { id, operation, localRow } = prepared;
417
+ operations.push(operation);
418
+ batch.push({ operation, localRow });
419
+ localMutations.push({ table, rowId: id, op: 'upsert' });
420
+ return id;
421
+ },
422
+ async insertMany(rows) {
423
+ if (rows.length === 0) {
424
+ throw new Error('insertMany requires at least one row');
425
+ }
426
+ const ids = [];
427
+ for (const row of rows) {
428
+ const { id, operation, localRow } = await prepareInsert(row);
429
+ ids.push(id);
430
+ operations.push(operation);
431
+ batch.push({ operation, localRow });
432
+ localMutations.push({ table, rowId: id, op: 'upsert' });
433
+ }
434
+ return ids;
435
+ },
436
+ async update(id, patch, opts) {
437
+ await applyUpsert(id, patch, opts, { mergeExistingLocalRow: true });
438
+ },
439
+ async delete(id, opts) {
440
+ const baseVersion = await resolveBaseVersion({
441
+ options,
442
+ table,
443
+ rowId: id,
444
+ idColumn: tableIdColumn,
445
+ versionColumn: tableVersionColumn,
446
+ explicit: opts?.baseVersion,
447
+ });
448
+ if (softDeleteColumn) {
449
+ const payload = { [softDeleteColumn]: 1 };
450
+ const localDbPayload = applyCodecsToDbRow(payload, resolveTableCodecs(table, payload), codecDialect);
451
+ const operation = {
452
+ table,
453
+ row_id: id,
454
+ op: 'upsert',
455
+ payload,
456
+ base_version: baseVersion,
457
+ };
458
+ operations.push(operation);
459
+ batch.push({
460
+ operation,
461
+ localRow: { ...localDbPayload, [tableIdColumn]: id },
462
+ });
463
+ localMutations.push({ table, rowId: id, op: 'upsert' });
464
+ return;
465
+ }
466
+ const operation = {
467
+ table,
468
+ row_id: id,
469
+ op: 'delete',
470
+ payload: null,
471
+ base_version: baseVersion,
472
+ };
473
+ operations.push(operation);
474
+ batch.push({ operation, localRow: null });
475
+ localMutations.push({ table, rowId: id, op: 'delete' });
476
+ },
477
+ async upsert(id, patch, opts) {
478
+ await applyUpsert(id, patch, opts, { mergeExistingLocalRow: false });
479
+ },
480
+ };
481
+ const applyUpsert = async (id, patch, opts, behavior) => {
482
+ const rawPatch = objectRecord(patch);
483
+ const payload = sanitizeOperationPayload(rawPatch, {
484
+ omit: [
485
+ tableIdColumn,
486
+ ...(tableVersionColumn ? [tableVersionColumn] : []),
487
+ ...omitColumns,
488
+ ],
489
+ });
490
+ const syncPayload = stripCrdtYjsMaterializedPayloadFields(payload, crdtYjsFields);
491
+ const existingLocalRow = behavior.mergeExistingLocalRow
492
+ ? await readExistingLocalRow({
493
+ client: options.client,
494
+ table,
495
+ rowId: id,
496
+ idColumn: tableIdColumn,
497
+ })
498
+ : null;
499
+ const rawLocalPayload = existingLocalRow
500
+ ? { ...existingLocalRow, ...rawPatch }
501
+ : rawPatch;
502
+ const localPayload = sanitizeOperationPayload(rawLocalPayload, {
503
+ omit: [
504
+ tableIdColumn,
505
+ ...(tableVersionColumn ? [tableVersionColumn] : []),
506
+ ],
507
+ });
508
+ const existingRow = await readCrdtYjsExistingRow({
509
+ client: options.client,
510
+ table,
511
+ rowId: id,
512
+ idColumn: tableIdColumn,
513
+ crdtYjsFields,
514
+ });
515
+ const transformedLocalPayload = await transformCrdtYjsMutationPayload({
516
+ client: options.client,
517
+ table,
518
+ rowId: id,
519
+ payload: localPayload,
520
+ existingRow,
521
+ crdtYjsFields,
522
+ });
523
+ const localDbPayload = applyCodecsToDbRow(transformedLocalPayload, resolveTableCodecs(table, transformedLocalPayload), codecDialect);
524
+ const operation = {
525
+ table,
526
+ row_id: id,
527
+ op: 'upsert',
528
+ payload: syncPayload,
529
+ base_version: await resolveBaseVersion({
530
+ options,
531
+ table,
532
+ rowId: id,
533
+ idColumn: tableIdColumn,
534
+ versionColumn: tableVersionColumn,
535
+ explicit: opts?.baseVersion,
536
+ }),
537
+ };
538
+ operations.push(operation);
539
+ batch.push({
540
+ operation,
541
+ localRow: { ...localDbPayload, [tableIdColumn]: id },
542
+ });
543
+ localMutations.push({ table, rowId: id, op: 'upsert' });
544
+ };
545
+ txTableCache.set(table, tableApi);
546
+ return tableApi;
547
+ };
548
+ const tx = new Proxy({}, {
549
+ get(_target, prop) {
550
+ if (prop === 'then')
551
+ return undefined;
552
+ if (typeof prop !== 'string')
553
+ return undefined;
554
+ return makeTxTable(prop);
555
+ },
556
+ });
557
+ const result = await fn(tx);
558
+ if (operations.length === 0)
559
+ throw new Error('No mutations were enqueued');
560
+ const clientCommitId = options.requireAuthLease
561
+ ? await requireLeasedMutationClient(options.client).applyLeasedMutationsCommit(batch)
562
+ : await options.client.applyMutationsCommit(batch);
563
+ const meta = {
564
+ operations,
565
+ localMutations,
566
+ clientCommitIds: [clientCommitId],
567
+ };
568
+ await options.afterCommit?.(meta);
569
+ return {
570
+ result,
571
+ receipt: { commitId: clientCommitId, clientCommitId },
572
+ meta,
573
+ };
574
+ };
575
+ }
576
+ function requireLeasedMutationClient(client) {
577
+ if (typeof client.applyLeasedMutationsCommit !== 'function') {
578
+ throw new Error('Syncular leased mutations require applyLeasedMutationsCommit support');
579
+ }
580
+ if (typeof client.applyLeasedMutation !== 'function') {
581
+ throw new Error('Syncular leased mutations require applyLeasedMutation support');
582
+ }
583
+ return client;
584
+ }
585
+ class SyncularDriver extends BaseSqliteDriver {
586
+ client;
587
+ #listeners = new Map();
588
+ #appTables;
589
+ #tableConfig;
590
+ constructor(client, options = {}) {
591
+ super(async () => {
592
+ this.conn = new SyncularConnection(client, options.unsafeWrites ?? false);
593
+ });
594
+ this.client = client;
595
+ this.#appTables =
596
+ options.appTables == null
597
+ ? undefined
598
+ : new Set(normalizeLiveQueryTables(options.appTables));
599
+ this.#tableConfig = options.tableConfig;
600
+ }
601
+ async live(query, options) {
602
+ const compiled = query.compile();
603
+ const tables = normalizeLiveQueryTables(options.tables ?? inferTablesFromCompiledQuery(compiled, this.#appTables), this.#appTables);
604
+ if (tables.length === 0) {
605
+ throw new Error('Could not infer live query table dependencies. Pass { tables: [...] } explicitly.');
606
+ }
607
+ const snapshot = await this.client.subscribeQuery(compiled.sql, compiled.parameters, tables, inferDependencyHintsFromCompiledQuery(compiled, tables, this.#tableConfig));
608
+ const listener = (event) => {
609
+ const typed = event;
610
+ options.onChange(typed.rows, { ...typed, initial: false });
611
+ };
612
+ this.#listeners.set(snapshot.id, listener);
613
+ this.client.addLiveQueryListener(snapshot.id, listener);
614
+ options.onChange(snapshot.rows, {
615
+ queryId: snapshot.id,
616
+ version: Date.now(),
617
+ changedRows: [],
618
+ rows: snapshot.rows,
619
+ initial: true,
620
+ });
621
+ return {
622
+ id: snapshot.id,
623
+ unsubscribe: () => {
624
+ void this.#unsubscribeQuery(snapshot.id).catch(() => undefined);
625
+ },
626
+ };
627
+ }
628
+ async beginTransaction(connection) {
629
+ await connection.executeQuery(KyselyCompiledQuery.raw('begin'));
630
+ }
631
+ async destroy() {
632
+ const ids = [...this.#listeners.keys()];
633
+ for (const id of ids)
634
+ this.client.removeLiveQueryListener(id);
635
+ this.#listeners.clear();
636
+ await Promise.allSettled(ids.map((id) => this.client.unsubscribeQuery(id)));
637
+ }
638
+ async #unsubscribeQuery(id) {
639
+ if (!this.#listeners.has(id))
640
+ return;
641
+ this.#listeners.delete(id);
642
+ this.client.removeLiveQueryListener(id);
643
+ await this.client.unsubscribeQuery(id);
644
+ }
645
+ }
646
+ class SyncularConnection {
647
+ client;
648
+ unsafeWrites;
649
+ constructor(client, unsafeWrites) {
650
+ this.client = client;
651
+ this.unsafeWrites = unsafeWrites;
652
+ }
653
+ async executeQuery(compiledQuery) {
654
+ if (!this.unsafeWrites)
655
+ assertSyncularReadonlySql(compiledQuery.sql);
656
+ const result = this.unsafeWrites
657
+ ? await assertUnsafeSqlClient(this.client).executeUnsafeSql(compiledQuery.sql, compiledQuery.parameters)
658
+ : await this.client.executeSql(compiledQuery.sql, compiledQuery.parameters);
659
+ return {
660
+ rows: result.rows,
661
+ numAffectedRows: result.numAffectedRows == null
662
+ ? undefined
663
+ : BigInt(result.numAffectedRows),
664
+ insertId: result.insertId == null ? undefined : BigInt(result.insertId),
665
+ };
666
+ }
667
+ streamQuery(_compiledQuery, _chunkSize) {
668
+ throw new Error('syncular sqlite dialect does not support streaming');
669
+ }
670
+ }
671
+ function assertUnsafeSqlClient(client) {
672
+ const maybe = client;
673
+ if (typeof maybe.executeUnsafeSql === 'function') {
674
+ return client;
675
+ }
676
+ throw new Error('Syncular schema installation requires an internal unsafe SQL client.');
677
+ }
678
+ function objectRecord(value) {
679
+ if (!value || typeof value !== 'object' || Array.isArray(value))
680
+ return {};
681
+ return { ...value };
682
+ }
683
+ async function toUint8Array(data) {
684
+ if (data instanceof Uint8Array)
685
+ return data;
686
+ return new Uint8Array(await data.arrayBuffer());
687
+ }
688
+ function sanitizeOperationPayload(payload, args) {
689
+ if (args.omit.length === 0)
690
+ return payload;
691
+ const omit = new Set(args.omit);
692
+ const out = {};
693
+ for (const [key, value] of Object.entries(payload)) {
694
+ if (!omit.has(key))
695
+ out[key] = value;
696
+ }
697
+ return out;
698
+ }
699
+ function serverMergeCrdtYjsFields(fields) {
700
+ return fields.filter((field) => field.syncMode === undefined || field.syncMode === 'server-merge');
701
+ }
702
+ async function transformCrdtYjsMutationPayload(args) {
703
+ if (args.crdtYjsFields.length === 0 || !('__yjs' in args.payload)) {
704
+ return args.payload;
705
+ }
706
+ return args.client.applyYjsEnvelopeToPayload({
707
+ table: args.table,
708
+ rowId: args.rowId,
709
+ payload: args.payload,
710
+ existingRow: args.existingRow ?? null,
711
+ rules: args.crdtYjsFields.map((field) => ({
712
+ table: args.table,
713
+ field: field.field,
714
+ stateColumn: field.stateColumn,
715
+ containerKey: field.containerKey ?? field.field,
716
+ rowIdField: field.rowIdField ?? 'id',
717
+ kind: field.kind ?? 'text',
718
+ })),
719
+ stripEnvelope: true,
720
+ });
721
+ }
722
+ function stripCrdtYjsMaterializedPayloadFields(payload, crdtYjsFields) {
723
+ const envelope = objectRecord(payload.__yjs);
724
+ if (crdtYjsFields.length === 0 || Object.keys(envelope).length === 0) {
725
+ return payload;
726
+ }
727
+ let next = null;
728
+ const ensureNext = () => {
729
+ next ??= { ...payload };
730
+ return next;
731
+ };
732
+ for (const field of crdtYjsFields) {
733
+ if (!(field.field in envelope))
734
+ continue;
735
+ delete ensureNext()[field.field];
736
+ delete ensureNext()[field.stateColumn];
737
+ }
738
+ return next ?? payload;
739
+ }
740
+ async function readCrdtYjsExistingRow(args) {
741
+ if (args.crdtYjsFields.length === 0)
742
+ return null;
743
+ const columns = new Set([args.idColumn]);
744
+ for (const field of args.crdtYjsFields) {
745
+ columns.add(field.field);
746
+ columns.add(field.stateColumn);
747
+ }
748
+ const result = await args.client.executeSql(`select ${[...columns].map(quoteSqlIdentifier).join(', ')} from ${quoteSqlIdentifier(args.table)} where ${quoteSqlIdentifier(args.idColumn)} = ? limit 1`, [args.rowId]);
749
+ return result.rows[0] ?? null;
750
+ }
751
+ async function readExistingLocalRow(args) {
752
+ const result = await args.client.executeSql(`select * from ${quoteSqlIdentifier(args.table)} where ${quoteSqlIdentifier(args.idColumn)} = ? limit 1`, [args.rowId]);
753
+ return result.rows[0] ?? null;
754
+ }
755
+ function quoteSqlIdentifier(identifier) {
756
+ if (!identifier)
757
+ throw new Error('SQLite identifier cannot be empty');
758
+ return `"${identifier.replace(/"/g, '""')}"`;
759
+ }
760
+ async function readCurrentBaseVersion(client, args) {
761
+ const result = await client.executeSql(`select ${quoteSqlIdentifier(args.versionColumn)} as version from ${quoteSqlIdentifier(args.table)} where ${quoteSqlIdentifier(args.idColumn)} = ? limit 1`, [args.rowId]);
762
+ return coerceBaseVersion(result.rows[0]?.version);
763
+ }
764
+ function coerceBaseVersion(value) {
765
+ if (value == null)
766
+ return null;
767
+ const numeric = typeof value === 'number' ? value : Number(value);
768
+ if (!Number.isFinite(numeric) || numeric < 0)
769
+ return null;
770
+ return numeric;
771
+ }
772
+ async function resolveBaseVersion(args) {
773
+ if (args.explicit !== undefined)
774
+ return coerceBaseVersion(args.explicit);
775
+ if (!args.versionColumn)
776
+ return null;
777
+ const readBaseVersion = args.options.readBaseVersion ??
778
+ ((readArgs) => readCurrentBaseVersion(args.options.client, readArgs));
779
+ return readBaseVersion({
780
+ table: args.table,
781
+ rowId: args.rowId,
782
+ idColumn: args.idColumn,
783
+ versionColumn: args.versionColumn,
784
+ });
785
+ }
786
+ function inferTablesFromCompiledQuery(query, appTables) {
787
+ const tables = new Set();
788
+ collectTables(query.query, tables);
789
+ return [...tables].filter((table) => appTables == null || appTables.has(table));
790
+ }
791
+ function inferDependencyHintsFromCompiledQuery(query, tables, tableConfig) {
792
+ if (tables.length !== 1)
793
+ return [];
794
+ const table = tables[0];
795
+ const primaryKey = tableConfig?.[table]?.primaryKeyColumn ?? 'id';
796
+ const rowIds = primaryKeyEqualityValues(query.query, table, primaryKey);
797
+ return rowIds.length > 0 ? [{ table, rowIds }] : [];
798
+ }
799
+ function primaryKeyEqualityValues(query, table, primaryKey) {
800
+ if (!isOperationNode(query) || query.kind !== 'SelectQueryNode')
801
+ return [];
802
+ const where = query.where;
803
+ if (!isOperationNode(where) || where.kind !== 'WhereNode')
804
+ return [];
805
+ return collectConjunctivePrimaryKeyValues(where.where, table, primaryKey);
806
+ }
807
+ function collectConjunctivePrimaryKeyValues(node, table, primaryKey) {
808
+ if (!isOperationNode(node))
809
+ return [];
810
+ if (node.kind === 'AndNode') {
811
+ return uniqueStrings([
812
+ ...collectConjunctivePrimaryKeyValues(node.left, table, primaryKey),
813
+ ...collectConjunctivePrimaryKeyValues(node.right, table, primaryKey),
814
+ ]);
815
+ }
816
+ const equality = primaryKeyEqualityValue(node, table, primaryKey);
817
+ return equality == null ? [] : [equality];
818
+ }
819
+ function primaryKeyEqualityValue(node, table, primaryKey) {
820
+ if (!isOperationNode(node) || node.kind !== 'BinaryOperationNode') {
821
+ return undefined;
822
+ }
823
+ const operator = node.operator;
824
+ if (!isOperationNode(operator) ||
825
+ operator.kind !== 'OperatorNode' ||
826
+ operator.operator !== '=') {
827
+ return undefined;
828
+ }
829
+ return (equalityValueForReference(node.leftOperand, node.rightOperand, table, primaryKey) ??
830
+ equalityValueForReference(node.rightOperand, node.leftOperand, table, primaryKey));
831
+ }
832
+ function equalityValueForReference(reference, value, table, primaryKey) {
833
+ if (!referenceMatchesColumn(reference, table, primaryKey))
834
+ return undefined;
835
+ if (!isOperationNode(value) || value.kind !== 'ValueNode')
836
+ return undefined;
837
+ if (typeof value.value === 'string')
838
+ return value.value;
839
+ if (typeof value.value === 'number' && Number.isFinite(value.value)) {
840
+ return String(value.value);
841
+ }
842
+ return undefined;
843
+ }
844
+ function referenceMatchesColumn(reference, table, column) {
845
+ if (!isOperationNode(reference) || reference.kind !== 'ReferenceNode') {
846
+ return false;
847
+ }
848
+ if (reference.table != null &&
849
+ tableNameFromTableNode(reference.table) !== table) {
850
+ return false;
851
+ }
852
+ const columnNode = reference.column;
853
+ if (!isOperationNode(columnNode) || columnNode.kind !== 'ColumnNode') {
854
+ return false;
855
+ }
856
+ const identifier = columnNode.column;
857
+ return (isOperationNode(identifier) &&
858
+ identifier.kind === 'IdentifierNode' &&
859
+ identifier.name === column);
860
+ }
861
+ function uniqueStrings(values) {
862
+ return [...new Set(values)];
863
+ }
864
+ function collectTables(node, tables) {
865
+ if (Array.isArray(node)) {
866
+ for (const item of node)
867
+ collectTables(item, tables);
868
+ return;
869
+ }
870
+ if (!isOperationNode(node))
871
+ return;
872
+ if (node.kind === 'TableNode')
873
+ collectTableNode(node, tables);
874
+ for (const value of Object.values(node))
875
+ collectTables(value, tables);
876
+ }
877
+ function collectTableNode(node, tables) {
878
+ const table = tableNameFromTableNode(node);
879
+ if (table != null)
880
+ tables.add(table);
881
+ }
882
+ function tableNameFromTableNode(node) {
883
+ if (!isOperationNode(node))
884
+ return undefined;
885
+ if (node.kind === 'AliasNode')
886
+ return tableNameFromTableNode(node.node);
887
+ if (node.kind !== 'TableNode')
888
+ return undefined;
889
+ const table = node.table;
890
+ if (!isOperationNode(table) || table.kind !== 'SchemableIdentifierNode') {
891
+ return undefined;
892
+ }
893
+ const identifier = table.identifier;
894
+ if (!isOperationNode(identifier) || identifier.kind !== 'IdentifierNode') {
895
+ return undefined;
896
+ }
897
+ return typeof identifier.name === 'string' ? identifier.name : undefined;
898
+ }
899
+ function isOperationNode(value) {
900
+ return Boolean(value && typeof value === 'object' && 'kind' in value);
901
+ }
902
+ function normalizeLiveQueryTables(tables, appTables) {
903
+ const normalized = [];
904
+ for (const table of tables) {
905
+ if (table.length === 0) {
906
+ throw new Error('Live query table dependencies must not contain empty names.');
907
+ }
908
+ if (appTables != null && !appTables.has(table)) {
909
+ throw new Error(`Live query table ${table} is not part of the generated app schema.`);
910
+ }
911
+ if (!normalized.includes(table))
912
+ normalized.push(table);
913
+ }
914
+ return normalized;
915
+ }
916
+ //# sourceMappingURL=database.js.map