velocious 1.0.499 → 1.0.501

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 (42) hide show
  1. package/README.md +1 -1
  2. package/build/configuration-types.js +39 -0
  3. package/build/configuration.js +3 -2
  4. package/build/database/drivers/mssql/index.js +79 -2
  5. package/build/database/tenants/data-copier.js +27 -0
  6. package/build/environment-handlers/node/cli/commands/generate/frontend-models.js +4 -20
  7. package/build/src/configuration-types.d.ts +123 -0
  8. package/build/src/configuration-types.d.ts.map +1 -1
  9. package/build/src/configuration-types.js +36 -1
  10. package/build/src/configuration.d.ts.map +1 -1
  11. package/build/src/configuration.js +4 -3
  12. package/build/src/database/drivers/mssql/index.d.ts +22 -0
  13. package/build/src/database/drivers/mssql/index.d.ts.map +1 -1
  14. package/build/src/database/drivers/mssql/index.js +74 -3
  15. package/build/src/database/tenants/data-copier.d.ts +16 -0
  16. package/build/src/database/tenants/data-copier.d.ts.map +1 -1
  17. package/build/src/database/tenants/data-copier.js +25 -1
  18. package/build/src/environment-handlers/node/cli/commands/generate/frontend-models.d.ts +0 -9
  19. package/build/src/environment-handlers/node/cli/commands/generate/frontend-models.d.ts.map +1 -1
  20. package/build/src/environment-handlers/node/cli/commands/generate/frontend-models.js +5 -16
  21. package/build/src/sync/sync-client-types.d.ts +27 -0
  22. package/build/src/sync/sync-client-types.d.ts.map +1 -1
  23. package/build/src/sync/sync-client-types.js +1 -1
  24. package/build/src/sync/sync-client.d.ts +42 -0
  25. package/build/src/sync/sync-client.d.ts.map +1 -1
  26. package/build/src/sync/sync-client.js +70 -20
  27. package/build/src/sync/sync-realtime-bridge.d.ts +125 -0
  28. package/build/src/sync/sync-realtime-bridge.d.ts.map +1 -0
  29. package/build/src/sync/sync-realtime-bridge.js +262 -0
  30. package/build/sync/sync-client-types.js +12 -0
  31. package/build/sync/sync-client.js +80 -22
  32. package/build/sync/sync-realtime-bridge.js +299 -0
  33. package/build/tsconfig.tsbuildinfo +1 -1
  34. package/package.json +2 -2
  35. package/src/configuration-types.js +39 -0
  36. package/src/configuration.js +3 -2
  37. package/src/database/drivers/mssql/index.js +79 -2
  38. package/src/database/tenants/data-copier.js +27 -0
  39. package/src/environment-handlers/node/cli/commands/generate/frontend-models.js +4 -20
  40. package/src/sync/sync-client-types.js +12 -0
  41. package/src/sync/sync-client.js +80 -22
  42. package/src/sync/sync-realtime-bridge.js +299 -0
@@ -94,6 +94,33 @@ export default class DataCopier {
94
94
  return sourceRowsByTableName
95
95
  }
96
96
 
97
+ /**
98
+ * Deletes one tenant's rows from the target database, children before parents, with
99
+ * foreign keys disabled inside a single transaction. This is `copy` without the reinsert:
100
+ * the same plan traversal selects the tenant's current target rows and `deleteTargetRows`
101
+ * removes them children-first so the ordering never trips a foreign key. Multi-tenant apps
102
+ * use it to purge a tenant — for example clearing the tenant's master copy in the
103
+ * global/default database on teardown, so foreign keys stop referencing the tenant's
104
+ * about-to-be-removed root row.
105
+ *
106
+ * Returns the deleted rows keyed by table name so the caller can perform any app-specific
107
+ * post-delete work (record-location cleanup, auditing) without that policy leaking into the
108
+ * framework.
109
+ * @param {string} keyValue - Tenant key whose rows should be removed from the target.
110
+ * @returns {Promise<Map<string, Record<string, unknown>[]>>} - The deleted rows by table name.
111
+ */
112
+ async deleteTenantRows(keyValue) {
113
+ const rowsByTableName = await this.loadRows(this.targetDb, keyValue)
114
+
115
+ await this.targetDb.withDisabledForeignKeys(async () => {
116
+ await this.targetDb.transaction(async () => {
117
+ await this.deleteTargetRows(rowsByTableName)
118
+ })
119
+ })
120
+
121
+ return rowsByTableName
122
+ }
123
+
97
124
  /**
98
125
  * Loads the rows for `keyValue` for every table in the plan from `db`, resolving
99
126
  * parent-scoped tables from the ids already selected for their parent table. Used for
@@ -167,11 +167,10 @@ export default class DbGenerateFrontendModels extends BaseCommand {
167
167
  }
168
168
 
169
169
  for (const [frontendModelsDir, generatedFiles] of generatedFilesByDirectory) {
170
- const indexContent = this.buildIndexFileContent(generatedFiles)
171
-
172
- await fs.writeFile(`${frontendModelsDir}/index.js`, indexContent)
173
-
174
- console.log("create src/frontend-models/index.js")
170
+ // The index.js barrel is no longer generated — nothing imports it (models are
171
+ // imported by file path, and setup.js performs the registration side-effects).
172
+ // Remove any stale one left from an older generator.
173
+ await fs.rm(`${frontendModelsDir}/index.js`, {force: true})
175
174
 
176
175
  const setupContent = this.buildSetupFileContent(generatedFiles)
177
176
 
@@ -632,21 +631,6 @@ export default class DbGenerateFrontendModels extends BaseCommand {
632
631
  return fileContent
633
632
  }
634
633
 
635
- /**
636
- * Runs build index file content.
637
- * @param {Array<{className: string, fileName: string}>} generatedFiles - Generated model files.
638
- * @returns {string} - Index file content that imports and re-exports all models.
639
- */
640
- buildIndexFileContent(generatedFiles) {
641
- let content = generatedFileBanner(FRONTEND_MODELS_REGENERATE_COMMAND)
642
-
643
- for (const {className, fileName} of generatedFiles) {
644
- content += `export {default as ${className}} from "./${fileName}"\n`
645
- }
646
-
647
- return content
648
- }
649
-
650
634
  /**
651
635
  * Runs build setup file content.
652
636
  * @param {Array<{className: string, fileName: string}>} generatedFiles - Generated model files.
@@ -7,6 +7,15 @@
7
7
  * @property {string} resourceType - Resource/model name the scope was declared for.
8
8
  */
9
9
 
10
+ /**
11
+ * Static realtime channel declaration on a model's `static sync`, for channels
12
+ * whose name and params are static. Channels needing runtime params (like
13
+ * eventId) belong in the `sync.client.realtime.channels` callback instead.
14
+ * @typedef {object} ModelSyncRealtimeDeclaration
15
+ * @property {string} channel - Server channel name to subscribe.
16
+ * @property {Record<string, ?>} [params] - Static subscribe params. The framework injects `authenticationToken` automatically.
17
+ */
18
+
10
19
  /**
11
20
  * Declarative per-resource sync policy.
12
21
  * @typedef {object} SyncClientResourceConfig
@@ -20,6 +29,7 @@
20
29
  * @property {"upsert" | ((args: {operation: "create" | "update" | "destroy", record: ?}) => string)} [syncType] - Maps a mutation operation to a sync type. The "upsert" flag queues creates and updates as "update" rows (the server upserts by resource id) and destroys as "delete". Defaults to the operation name with destroy mapped to "delete".
21
30
  * @property {(args: {operation: "create" | "update" | "destroy", record: ?}) => Record<string, ?>} [trackedData] - Custom queued-payload builder for tracked mutations.
22
31
  * @property {boolean | {operations: Array<"create" | "update" | "destroy">}} [track] - Enables automatic mutation tracking through model lifecycle callbacks.
32
+ * @property {ModelSyncRealtimeDeclaration} [realtime] - Static realtime channel this resource subscribes through `subscribeRealtime(...)`.
23
33
  */
24
34
 
25
35
  /**
@@ -36,6 +46,7 @@
36
46
  * @property {"upsert" | ((args: {operation: "create" | "update" | "destroy", record: ?}) => string)} [syncType] - Sync type flag or mapper (see SyncClientResourceConfig).
37
47
  * @property {boolean | Array<"create" | "update" | "destroy"> | {operations: Array<"create" | "update" | "destroy">}} [track] - Enables automatic mutation tracking; an array is shorthand for {operations}.
38
48
  * @property {(args: {operation: "create" | "update" | "destroy", record: ?}) => Record<string, ?>} [trackedData] - Custom queued-payload builder for tracked mutations.
49
+ * @property {ModelSyncRealtimeDeclaration} [realtime] - Static realtime channel this resource subscribes through `subscribeRealtime(...)`; use the `sync.client.realtime.channels` callback for channels needing runtime params.
39
50
  */
40
51
 
41
52
  /** @typedef {boolean | ModelSyncDeclarationConfig} ModelSyncDeclaration */
@@ -63,6 +74,7 @@
63
74
  * @property {(error: Error) => void} [onError] - Reports background replay/pull failures. Defaults to rethrowing.
64
75
  * @property {(payload: import("./sync-api-client-types.js").SyncChangesRequest & {scope: SerializedSyncScope}) => Promise<import("./sync-api-client-types.js").SyncChangesResponse>} postChanges - Posts one changes request.
65
76
  * @property {(payload: {authenticationToken: string, syncs: Array<Record<string, ?>>}) => Promise<import("./sync-api-client-types.js").SyncReplayResponse>} postReplay - Posts one replay request.
77
+ * @property {import("../configuration-types.js").VelociousSyncClientRealtimeConfiguration} [realtime] - Realtime push configuration consumed by `subscribeRealtime(...)`.
66
78
  * @property {Record<string, SyncClientResourceConfig>} resources - Derived resource policies keyed by resource/model name.
67
79
  * @property {?} syncModel - Local pending-sync model class.
68
80
  */
@@ -6,6 +6,7 @@ import restArgsError from "../utils/rest-args-error.js"
6
6
 
7
7
  import {serializedScopeFromQuery} from "./query-scope.js"
8
8
  import SyncApiClient from "./sync-api-client.js"
9
+ import SyncRealtimeBridge from "./sync-realtime-bridge.js"
9
10
  import SyncScopeStore from "./sync-scope-store.js"
10
11
  import {currentSyncClient, setCurrentSyncClient} from "./sync-client-registry.js"
11
12
 
@@ -87,10 +88,13 @@ export default class SyncClient {
87
88
  onError: clientConfiguration.onError,
88
89
  postChanges: transportPoster({path: `${clientConfiguration.mountPath}/changes`, transport: clientConfiguration.transport}),
89
90
  postReplay: transportPoster({path: `${clientConfiguration.mountPath}/replay`, transport: clientConfiguration.transport}),
91
+ realtime: clientConfiguration.realtime,
90
92
  resources,
91
93
  syncModel: resolvedSyncModel
92
94
  }
93
95
  this._clientNumber = ++clientCounter
96
+ /** @type {SyncRealtimeBridge | null} */
97
+ this._realtimeBridge = null
94
98
  /** @type {import("./sync-scope-store.js").default | null} */
95
99
  this._scopeStore = scopeStore || null
96
100
  /** @type {Promise<void> | null} */
@@ -265,26 +269,7 @@ export default class SyncClient {
265
269
  await SyncApiClient.singleFlight(`velocious-sync-client-pull-${this._clientNumber}`, async () => {
266
270
  const authenticationToken = await this.config.authenticationToken()
267
271
  const scopeStore = this.scopeStore()
268
- const pullResourceConfigs = this.pullResourceConfigs()
269
- const applier = SyncApiClient.resourceApplier(pullResourceConfigs, (record) => {
270
- this._remoteApplyRecords.add(record)
271
-
272
- return () => this._remoteApplyRecords.delete(record)
273
- })
274
- /**
275
- * Applies one pulled change, failing loudly instead of silently skipping unconfigured resources.
276
- * @param {import("./sync-api-client-types.js").SyncChangeEnvelope} sync - Pulled change.
277
- * @returns {Promise<import("./sync-api-client-types.js").SyncChangeApplyResult>} Apply result.
278
- */
279
- const applySync = async (sync) => {
280
- const resourceType = sync.resourceType()
281
-
282
- if (!resourceType || !pullResourceConfigs[resourceType]) {
283
- throw new Error(`No sync resource with pull attributes configured for pulled change: ${String(resourceType)}`)
284
- }
285
-
286
- return await applier(sync)
287
- }
272
+ const applySync = this.remoteApplySync()
288
273
  const result = {
289
274
  changed: false,
290
275
  pages: 0,
@@ -324,6 +309,78 @@ export default class SyncClient {
324
309
  return combinedResult
325
310
  }
326
311
 
312
+ /**
313
+ * Builds the derived remote-change applier shared by pulls and realtime pushes:
314
+ * applies through the declared resource configs, registers each written record
315
+ * for echo suppression (tracked resources do not re-queue applied changes), and
316
+ * fails loudly instead of silently skipping unconfigured resources.
317
+ * @param {{source?: string}} [args] - Error context describing where the change came from.
318
+ * @returns {(sync: import("./sync-api-client-types.js").SyncChangeEnvelope) => Promise<import("./sync-api-client-types.js").SyncChangeApplyResult>} Loud remote-change applier.
319
+ */
320
+ remoteApplySync({source = "pulled change"} = {}) {
321
+ const pullResourceConfigs = this.pullResourceConfigs()
322
+ const applier = SyncApiClient.resourceApplier(pullResourceConfigs, (record) => {
323
+ this._remoteApplyRecords.add(record)
324
+
325
+ return () => this._remoteApplyRecords.delete(record)
326
+ })
327
+
328
+ return async (sync) => {
329
+ const resourceType = sync.resourceType()
330
+
331
+ if (!resourceType || !pullResourceConfigs[resourceType]) {
332
+ throw new Error(`No sync resource with pull attributes configured for ${source}: ${String(resourceType)}`)
333
+ }
334
+
335
+ return await applier(sync)
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Subscribes the derived realtime channels so pushed websocket changes apply
341
+ * through the same derived applier as pulls (idempotent, single-flighted).
342
+ * @param {?} [context] - App context passed to the `sync.client.realtime.channels` callback (runtime values like eventId).
343
+ * @returns {Promise<void>}
344
+ */
345
+ async subscribeRealtime(context) {
346
+ await this.realtimeBridge().subscribe(context)
347
+ }
348
+
349
+ /**
350
+ * Unsubscribes the realtime channels and disconnects the websocket client (idempotent).
351
+ * @returns {Promise<void>}
352
+ */
353
+ async unsubscribeRealtime() {
354
+ await this.realtimeBridge().unsubscribe()
355
+ }
356
+
357
+ /**
358
+ * Reports the realtime subscription state and per-channel readiness.
359
+ * @returns {ReturnType<SyncRealtimeBridge["status"]>} Realtime status.
360
+ */
361
+ realtimeStatus() {
362
+ return this.realtimeBridge().status()
363
+ }
364
+
365
+ /**
366
+ * Awaits all pending realtime message applies and any scheduled
367
+ * pull-on-reconnect (useful in tests and shutdown flows).
368
+ * @returns {Promise<void>}
369
+ */
370
+ async waitForRealtimeApplied() {
371
+ await this.realtimeBridge().waitForApplied()
372
+ }
373
+
374
+ /**
375
+ * Returns the lazily built realtime bridge.
376
+ * @returns {SyncRealtimeBridge} Realtime bridge.
377
+ */
378
+ realtimeBridge() {
379
+ this._realtimeBridge ||= new SyncRealtimeBridge({syncClient: this})
380
+
381
+ return this._realtimeBridge
382
+ }
383
+
327
384
  /**
328
385
  * Queues a local model change as a pending sync row and schedules an immediate
329
386
  * replay attempt (kept pending while offline or when the backend rejects it).
@@ -491,11 +548,11 @@ function resourceConfigFromSyncDeclaration({declaration, modelClass, resourceTyp
491
548
  throw new Error(`${resourceType} static sync must be true or a sync declaration object, got: ${String(declaration)}`)
492
549
  }
493
550
 
494
- const {afterApply, attributes, booleanAttributes, findRecord, findRecordForDelete, localOnlyAttributes, syncType, track, trackedData, ...restDeclaration} = normalizedDeclaration
551
+ const {afterApply, attributes, booleanAttributes, findRecord, findRecordForDelete, localOnlyAttributes, realtime, syncType, track, trackedData, ...restDeclaration} = normalizedDeclaration
495
552
  const unknownKeys = Object.keys(restDeclaration)
496
553
 
497
554
  if (unknownKeys.length > 0) {
498
- throw new Error(`${resourceType} static sync received unknown keys: ${unknownKeys.join(", ")} (supported: afterApply, attributes, booleanAttributes, findRecord, findRecordForDelete, localOnlyAttributes, syncType, track, trackedData)`)
555
+ throw new Error(`${resourceType} static sync received unknown keys: ${unknownKeys.join(", ")} (supported: afterApply, attributes, booleanAttributes, findRecord, findRecordForDelete, localOnlyAttributes, realtime, syncType, track, trackedData)`)
499
556
  }
500
557
  if (syncType !== undefined && typeof syncType !== "function" && syncType !== "upsert") {
501
558
  throw new Error(`${resourceType} static sync syncType must be a function or the string "upsert", got: ${String(syncType)}`)
@@ -511,6 +568,7 @@ function resourceConfigFromSyncDeclaration({declaration, modelClass, resourceTyp
511
568
  findRecordForDelete,
512
569
  localOnlyAttributes: mergedAttributeNames(derived.localOnlyAttributes, localOnlyAttributes),
513
570
  modelClass,
571
+ realtime,
514
572
  syncType,
515
573
  track: normalizedTrack(track),
516
574
  trackedData
@@ -0,0 +1,299 @@
1
+ // @ts-check
2
+
3
+ import SyncApiClient from "./sync-api-client.js"
4
+
5
+ /** @typedef {import("../configuration-types.js").VelociousSyncRealtimeChannelDescriptor} VelociousSyncRealtimeChannelDescriptor */
6
+ /** @typedef {import("../configuration-types.js").VelociousSyncRealtimeWebsocketClient} VelociousSyncRealtimeWebsocketClient */
7
+
8
+ /**
9
+ * Derived realtime push bridge for the sync client. Subscribes the declared
10
+ * websocket channels (config `sync.client.realtime.channels` callback plus
11
+ * model-level `static sync = {realtime: {channel}}` declarations), applies
12
+ * pushed changes through the same derived resource applier as pulls (with echo
13
+ * suppression against tracked re-queueing), drops own-device messages by echo
14
+ * origin, and fires a coalesced `pull()` when subscriptions become ready or
15
+ * resume so offline gaps close.
16
+ */
17
+ export default class SyncRealtimeBridge {
18
+ /**
19
+ * Builds the bridge for a sync client.
20
+ * @param {{syncClient: import("./sync-client.js").default}} args - Bridge args.
21
+ */
22
+ constructor({syncClient}) {
23
+ this.syncClient = syncClient
24
+ /** @type {Array<{channel: string, resourceType: string | null, subscription: import("../configuration-types.js").VelociousSyncRealtimeSubscription}>} */
25
+ this._channels = []
26
+ /** @type {VelociousSyncRealtimeWebsocketClient | null} */
27
+ this._client = null
28
+ /** @type {Promise<void>} */
29
+ this._applyPromise = Promise.resolve()
30
+ /** @type {number} Subscription generation - bumped by unsubscribe so in-flight subscribes detect they became stale. */
31
+ this._generation = 0
32
+ /** @type {Promise<void> | null} */
33
+ this._scheduledPull = null
34
+ /** @type {Promise<void> | null} */
35
+ this._subscribePromise = null
36
+ /** @type {"subscribed" | "subscribing" | "unsubscribed"} */
37
+ this._state = "unsubscribed"
38
+ }
39
+
40
+ /**
41
+ * Subscribes the derived realtime channels (idempotent and single-flighted):
42
+ * an active subscription is kept as-is and a concurrent subscribe awaits the
43
+ * in-flight attempt. Call `unsubscribe()` first to change the context.
44
+ * @param {?} [context] - App context passed to the `sync.client.realtime.channels` callback (runtime values like eventId).
45
+ * @returns {Promise<void>}
46
+ */
47
+ async subscribe(context) {
48
+ if (this._state === "subscribed") return
49
+
50
+ if (!this._subscribePromise) {
51
+ this._subscribePromise = this._subscribe(context).finally(() => {
52
+ this._subscribePromise = null
53
+ })
54
+ }
55
+
56
+ await this._subscribePromise
57
+ }
58
+
59
+ /**
60
+ * Connects the websocket client, subscribes every derived channel, and waits
61
+ * for each subscription's server acknowledgement before the gap-closing pull,
62
+ * so no change can land between the pull and the subscriptions going live.
63
+ * Locally created resources are only promoted to the bridge once everything
64
+ * is live; an unsubscribe arriving during any await marks this attempt stale
65
+ * and it tears its own resources down instead of resubscribing.
66
+ * @param {?} context - App context passed to the channels callback.
67
+ * @returns {Promise<void>}
68
+ */
69
+ async _subscribe(context) {
70
+ const generation = this._generation
71
+
72
+ this._state = "subscribing"
73
+
74
+ /** @type {Array<{channel: string, resourceType: string | null, subscription: import("../configuration-types.js").VelociousSyncRealtimeSubscription}>} */
75
+ const channels = []
76
+ /** @type {VelociousSyncRealtimeWebsocketClient | null} */
77
+ let client = null
78
+ /**
79
+ * Tears down everything this stale/failed subscribe attempt created itself.
80
+ * @returns {Promise<void>}
81
+ */
82
+ const teardown = async () => {
83
+ for (const {subscription} of channels) {
84
+ subscription.close()
85
+ }
86
+
87
+ if (client) await client.disconnectAndStopReconnect()
88
+ }
89
+
90
+ try {
91
+ const realtime = this.realtimeConfiguration()
92
+ const channelDescriptors = await this.channelDescriptors(context)
93
+
94
+ if (generation !== this._generation) return
95
+
96
+ client = await realtime.createClient()
97
+
98
+ if (generation !== this._generation) return
99
+
100
+ await client.connect()
101
+
102
+ if (generation !== this._generation) {
103
+ await teardown()
104
+ return
105
+ }
106
+
107
+ const authenticationToken = await this.syncClient.config.authenticationToken()
108
+
109
+ if (generation !== this._generation) {
110
+ await teardown()
111
+ return
112
+ }
113
+
114
+ for (const channelDescriptor of channelDescriptors) {
115
+ if (channelDescriptor.params && "authenticationToken" in channelDescriptor.params) {
116
+ throw new Error(`Realtime channel "${channelDescriptor.channel}" params must not include authenticationToken - the framework injects the sync.client authenticationToken automatically`)
117
+ }
118
+
119
+ const resourceType = channelDescriptor.resourceType ?? null
120
+ const subscription = client.subscribeChannel(channelDescriptor.channel, {
121
+ onMessage: (body) => this.enqueueApply({body, resourceType}),
122
+ onResume: () => this.schedulePull(),
123
+ params: {...channelDescriptor.params, authenticationToken}
124
+ })
125
+
126
+ channels.push({channel: channelDescriptor.channel, resourceType, subscription})
127
+ }
128
+
129
+ await Promise.all(channels.map(({subscription}) => subscription.waitForReady()))
130
+
131
+ if (generation !== this._generation) {
132
+ await teardown()
133
+ return
134
+ }
135
+
136
+ this._channels = channels
137
+ this._client = client
138
+ this._state = "subscribed"
139
+ this.schedulePull()
140
+ } catch (error) {
141
+ await teardown()
142
+
143
+ if (generation === this._generation) this._state = "unsubscribed"
144
+
145
+ throw error
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Closes every channel subscription and disconnects the websocket client
151
+ * (idempotent). Also marks any in-flight subscribe attempt stale so it tears
152
+ * itself down instead of finishing the subscription afterwards.
153
+ * @returns {Promise<void>}
154
+ */
155
+ async unsubscribe() {
156
+ this._generation += 1
157
+
158
+ const channels = this._channels
159
+ const client = this._client
160
+
161
+ this._channels = []
162
+ this._client = null
163
+ this._state = "unsubscribed"
164
+
165
+ for (const {subscription} of channels) {
166
+ subscription.close()
167
+ }
168
+
169
+ if (client) await client.disconnectAndStopReconnect()
170
+ }
171
+
172
+ /**
173
+ * Reports the bridge subscription state and per-channel readiness.
174
+ * @returns {{channels: Array<{channel: string, ready: boolean, resourceType: string | null}>, state: "subscribed" | "subscribing" | "unsubscribed"}} Realtime status.
175
+ */
176
+ status() {
177
+ return {
178
+ channels: this._channels.map(({channel, resourceType, subscription}) => ({channel, ready: subscription.isReady(), resourceType})),
179
+ state: this._state
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Awaits all enqueued message applies and any scheduled pull (tests, shutdown flows).
185
+ * @returns {Promise<void>}
186
+ */
187
+ async waitForApplied() {
188
+ await this._applyPromise
189
+ if (this._scheduledPull) await this._scheduledPull
190
+ }
191
+
192
+ /**
193
+ * Resolves the realtime configuration, failing loudly when it is missing.
194
+ * @returns {import("../configuration-types.js").VelociousSyncClientRealtimeConfiguration} Realtime configuration.
195
+ */
196
+ realtimeConfiguration() {
197
+ const realtime = this.syncClient.config.realtime
198
+
199
+ if (!realtime) {
200
+ throw new Error("subscribeRealtime requires a sync.client.realtime configuration block with a createClient callback")
201
+ }
202
+
203
+ return realtime
204
+ }
205
+
206
+ /**
207
+ * Derives the channel descriptors to subscribe: model-level static realtime
208
+ * declarations plus the config channels callback, failing loudly when none exist.
209
+ * @param {?} context - App context passed to the channels callback.
210
+ * @returns {Promise<Array<VelociousSyncRealtimeChannelDescriptor>>} Channel descriptors.
211
+ */
212
+ async channelDescriptors(context) {
213
+ const realtime = this.realtimeConfiguration()
214
+ /** @type {Array<VelociousSyncRealtimeChannelDescriptor>} */
215
+ const channelDescriptors = []
216
+
217
+ for (const [resourceType, resourceConfig] of Object.entries(this.syncClient.config.resources)) {
218
+ if (!resourceConfig.realtime) continue
219
+
220
+ channelDescriptors.push({channel: resourceConfig.realtime.channel, params: resourceConfig.realtime.params, resourceType})
221
+ }
222
+
223
+ if (realtime.channels) {
224
+ channelDescriptors.push(...await realtime.channels(context))
225
+ }
226
+
227
+ if (channelDescriptors.length === 0) {
228
+ throw new Error("subscribeRealtime found no realtime channels - declare sync.client.realtime.channels or static sync = {realtime: {channel}} on a model")
229
+ }
230
+
231
+ return channelDescriptors
232
+ }
233
+
234
+ /**
235
+ * Chains one pushed message onto the serialized apply queue so changes apply
236
+ * in arrival order; failures go to the sync client's error reporting.
237
+ * @param {{body: ?, resourceType: string | null}} args - Message args.
238
+ * @returns {void}
239
+ */
240
+ enqueueApply({body, resourceType}) {
241
+ this._applyPromise = this._applyPromise.then(async () => {
242
+ try {
243
+ await this.applyMessage({body, resourceType})
244
+ } catch (error) {
245
+ this.syncClient.reportError(/** @type {Error} */ (error))
246
+ }
247
+ })
248
+ }
249
+
250
+ /**
251
+ * Applies one pushed message through the derived resource applier: drops
252
+ * own-device messages by echo origin, defaults the channel's resourceType onto
253
+ * envelopes without one, and fails loudly on unknown resource types.
254
+ * @param {{body: ?, resourceType: string | null}} args - Message args.
255
+ * @returns {Promise<void>}
256
+ */
257
+ async applyMessage({body, resourceType}) {
258
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
259
+ throw new Error(`Realtime sync messages must be envelope objects, got: ${JSON.stringify(body)}`)
260
+ }
261
+
262
+ const realtime = this.realtimeConfiguration()
263
+
264
+ if (realtime.localOrigin && body.echoOrigin !== undefined && body.echoOrigin !== null) {
265
+ const localOrigin = String(await realtime.localOrigin())
266
+
267
+ if (String(body.echoOrigin) === localOrigin) return
268
+ }
269
+
270
+ const syncPayloads = Array.isArray(body.syncs) ? body.syncs : [body]
271
+ const applySync = this.syncClient.remoteApplySync({source: "remote change"})
272
+
273
+ for (const syncPayload of syncPayloads) {
274
+ const sync = SyncApiClient.syncEnvelopeFromPayload({resourceType, ...syncPayload})
275
+
276
+ await applySync(sync)
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Schedules a coalesced background pull closing offline gaps after
282
+ * (re)subscription readiness. Resumes arriving while a pull is already
283
+ * scheduled or in flight coalesce into that pull instead of stacking.
284
+ * @returns {void}
285
+ */
286
+ schedulePull() {
287
+ if (this.realtimeConfiguration().pullOnReconnect === false) return
288
+
289
+ this._scheduledPull ||= (async () => {
290
+ try {
291
+ await this.syncClient.pull()
292
+ } catch (error) {
293
+ this.syncClient.reportError(/** @type {Error} */ (error))
294
+ } finally {
295
+ this._scheduledPull = null
296
+ }
297
+ })()
298
+ }
299
+ }