@g9tm/syncdata 1.2.1

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 (149) hide show
  1. package/LICENSE.md +21 -0
  2. package/PARITY.md +71 -0
  3. package/README.md +71 -0
  4. package/THIRD-PARTY-NOTICES.md +31 -0
  5. package/dist/abstractions/digest.d.ts +27 -0
  6. package/dist/abstractions/digest.js +78 -0
  7. package/dist/abstractions/digest.js.map +1 -0
  8. package/dist/abstractions/enums.d.ts +42 -0
  9. package/dist/abstractions/enums.js +60 -0
  10. package/dist/abstractions/enums.js.map +1 -0
  11. package/dist/abstractions/errors.d.ts +72 -0
  12. package/dist/abstractions/errors.js +90 -0
  13. package/dist/abstractions/errors.js.map +1 -0
  14. package/dist/abstractions/guid.d.ts +24 -0
  15. package/dist/abstractions/guid.js +93 -0
  16. package/dist/abstractions/guid.js.map +1 -0
  17. package/dist/abstractions/key.d.ts +16 -0
  18. package/dist/abstractions/key.js +47 -0
  19. package/dist/abstractions/key.js.map +1 -0
  20. package/dist/abstractions/long.d.ts +103 -0
  21. package/dist/abstractions/long.js +351 -0
  22. package/dist/abstractions/long.js.map +1 -0
  23. package/dist/abstractions/parameters.d.ts +49 -0
  24. package/dist/abstractions/parameters.js +153 -0
  25. package/dist/abstractions/parameters.js.map +1 -0
  26. package/dist/brotli-js/decode.d.ts +8 -0
  27. package/dist/brotli-js/decode.js +2004 -0
  28. package/dist/brotli-js/decode.js.map +1 -0
  29. package/dist/brotli-js/index.d.ts +5 -0
  30. package/dist/brotli-js/index.js +19 -0
  31. package/dist/brotli-js/index.js.map +1 -0
  32. package/dist/client/engine.d.ts +110 -0
  33. package/dist/client/engine.js +1158 -0
  34. package/dist/client/engine.js.map +1 -0
  35. package/dist/client/model.d.ts +61 -0
  36. package/dist/client/model.js +154 -0
  37. package/dist/client/model.js.map +1 -0
  38. package/dist/client/progress.d.ts +101 -0
  39. package/dist/client/progress.js +251 -0
  40. package/dist/client/progress.js.map +1 -0
  41. package/dist/client/runs.d.ts +219 -0
  42. package/dist/client/runs.js +239 -0
  43. package/dist/client/runs.js.map +1 -0
  44. package/dist/client/storeTypes.d.ts +428 -0
  45. package/dist/client/storeTypes.js +256 -0
  46. package/dist/client/storeTypes.js.map +1 -0
  47. package/dist/client/transport.d.ts +19 -0
  48. package/dist/client/transport.js +2 -0
  49. package/dist/client/transport.js.map +1 -0
  50. package/dist/index.d.ts +27 -0
  51. package/dist/index.js +35 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/internal/abort.d.ts +21 -0
  54. package/dist/internal/abort.js +125 -0
  55. package/dist/internal/abort.js.map +1 -0
  56. package/dist/internal/base64.d.ts +8 -0
  57. package/dist/internal/base64.js +85 -0
  58. package/dist/internal/base64.js.map +1 -0
  59. package/dist/internal/dotnetFormat.d.ts +32 -0
  60. package/dist/internal/dotnetFormat.js +207 -0
  61. package/dist/internal/dotnetFormat.js.map +1 -0
  62. package/dist/internal/md5.d.ts +2 -0
  63. package/dist/internal/md5.js +97 -0
  64. package/dist/internal/md5.js.map +1 -0
  65. package/dist/internal/sha256.d.ts +20 -0
  66. package/dist/internal/sha256.js +153 -0
  67. package/dist/internal/sha256.js.map +1 -0
  68. package/dist/internal/utf8.d.ts +8 -0
  69. package/dist/internal/utf8.js +143 -0
  70. package/dist/internal/utf8.js.map +1 -0
  71. package/dist/node/index.d.ts +9 -0
  72. package/dist/node/index.js +35 -0
  73. package/dist/node/index.js.map +1 -0
  74. package/dist/node/sqliteDriver.d.ts +11 -0
  75. package/dist/node/sqliteDriver.js +252 -0
  76. package/dist/node/sqliteDriver.js.map +1 -0
  77. package/dist/protocol/dtos.d.ts +280 -0
  78. package/dist/protocol/dtos.js +33 -0
  79. package/dist/protocol/dtos.js.map +1 -0
  80. package/dist/protocol/protocol.d.ts +36 -0
  81. package/dist/protocol/protocol.js +63 -0
  82. package/dist/protocol/protocol.js.map +1 -0
  83. package/dist/protocol/rowBatch/columnLayout.d.ts +4 -0
  84. package/dist/protocol/rowBatch/columnLayout.js +309 -0
  85. package/dist/protocol/rowBatch/columnLayout.js.map +1 -0
  86. package/dist/protocol/rowBatch/format.d.ts +74 -0
  87. package/dist/protocol/rowBatch/format.js +163 -0
  88. package/dist/protocol/rowBatch/format.js.map +1 -0
  89. package/dist/protocol/rowBatch/reader.d.ts +119 -0
  90. package/dist/protocol/rowBatch/reader.js +459 -0
  91. package/dist/protocol/rowBatch/reader.js.map +1 -0
  92. package/dist/protocol/rowBatch/writer.d.ts +101 -0
  93. package/dist/protocol/rowBatch/writer.js +412 -0
  94. package/dist/protocol/rowBatch/writer.js.map +1 -0
  95. package/dist/protocol/wire.d.ts +32 -0
  96. package/dist/protocol/wire.js +329 -0
  97. package/dist/protocol/wire.js.map +1 -0
  98. package/dist/signalr/index.d.ts +2 -0
  99. package/dist/signalr/index.js +5 -0
  100. package/dist/signalr/index.js.map +1 -0
  101. package/dist/signalr/protocols.d.ts +17 -0
  102. package/dist/signalr/protocols.js +109 -0
  103. package/dist/signalr/protocols.js.map +1 -0
  104. package/dist/signalr/transport.d.ts +67 -0
  105. package/dist/signalr/transport.js +286 -0
  106. package/dist/signalr/transport.js.map +1 -0
  107. package/dist/sqlite/apply.d.ts +91 -0
  108. package/dist/sqlite/apply.js +657 -0
  109. package/dist/sqlite/apply.js.map +1 -0
  110. package/dist/sqlite/commands.d.ts +24 -0
  111. package/dist/sqlite/commands.js +167 -0
  112. package/dist/sqlite/commands.js.map +1 -0
  113. package/dist/sqlite/connection.d.ts +81 -0
  114. package/dist/sqlite/connection.js +322 -0
  115. package/dist/sqlite/connection.js.map +1 -0
  116. package/dist/sqlite/driver.d.ts +63 -0
  117. package/dist/sqlite/driver.js +9 -0
  118. package/dist/sqlite/driver.js.map +1 -0
  119. package/dist/sqlite/index.d.ts +6 -0
  120. package/dist/sqlite/index.js +7 -0
  121. package/dist/sqlite/index.js.map +1 -0
  122. package/dist/sqlite/internals.d.ts +63 -0
  123. package/dist/sqlite/internals.js +194 -0
  124. package/dist/sqlite/internals.js.map +1 -0
  125. package/dist/sqlite/options.d.ts +78 -0
  126. package/dist/sqlite/options.js +78 -0
  127. package/dist/sqlite/options.js.map +1 -0
  128. package/dist/sqlite/push.d.ts +9 -0
  129. package/dist/sqlite/push.js +272 -0
  130. package/dist/sqlite/push.js.map +1 -0
  131. package/dist/sqlite/query.d.ts +38 -0
  132. package/dist/sqlite/query.js +476 -0
  133. package/dist/sqlite/query.js.map +1 -0
  134. package/dist/sqlite/revocation.d.ts +28 -0
  135. package/dist/sqlite/revocation.js +337 -0
  136. package/dist/sqlite/revocation.js.map +1 -0
  137. package/dist/sqlite/sql.d.ts +60 -0
  138. package/dist/sqlite/sql.js +324 -0
  139. package/dist/sqlite/sql.js.map +1 -0
  140. package/dist/sqlite/store.d.ts +116 -0
  141. package/dist/sqlite/store.js +664 -0
  142. package/dist/sqlite/store.js.map +1 -0
  143. package/dist/sqlite/values.d.ts +29 -0
  144. package/dist/sqlite/values.js +288 -0
  145. package/dist/sqlite/values.js.map +1 -0
  146. package/dist/testing/index.d.ts +61 -0
  147. package/dist/testing/index.js +175 -0
  148. package/dist/testing/index.js.map +1 -0
  149. package/package.json +104 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/client/engine.ts"],"names":[],"mappings":"AAAA,qHAAqH;AACrH,oHAAoH;AACpH,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC/F,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAEjF,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,MAAM,EAAE,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AC;AAED,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,KAAkB;IACzC,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,MAAM;QAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAChH,CAAC","sourcesContent":["// Twin of G9SyncData.Client/G9CSyncEngine.cs, .Execution.cs and .Reconcile.cs: one engine per local database, with a\n// prioritised run queue (status queries never wait for a running sync) and background runs that yield to user runs.\nimport { G9EMoveOutPolicy, G9ESyncDirection } from '../abstractions/enums.js';\nimport { G9SyncErrorCodes, G9SyncException, isSyncException } from '../abstractions/errors.js';\nimport { guidToN, newGuid } from '../abstractions/guid.js';\nimport { G9SyncParameters, compareOrdinal } from '../abstractions/parameters.js';\nimport type { G9Long } from '../abstractions/long.js';\nimport { delay, linkSignals, onAbort } from '../internal/abort.js';\nimport { sha256, toHex } from '../internal/sha256.js';\nimport { utf8Encode } from '../internal/utf8.js';\nimport {\n G9ESubscriptionAction,\n type G9DtChangesAvailable,\n type G9DtHelloResult,\n type G9DtNegotiatedTable,\n type G9DtPullPlan,\n type G9DtPushRequest,\n type G9DtPushResult,\n type G9DtReconcileRequest,\n type G9DtReconcileSummary,\n type G9DtSubscriptionDefinition,\n type G9DtSubscriptionState,\n type G9DtSyncChunk,\n syncErrorToException,\n} from '../protocol/dtos.js';\nimport { openRowBatch } from '../protocol/rowBatch/reader.js';\nimport type { G9SyncClientModel } from './model.js';\nimport { G9ESyncPhase, G9SyncProgressTracker, phaseName } from './progress.js';\nimport {\n G9ESyncOutcome,\n G9ESyncPriority,\n G9SyncRun,\n canCoalesce,\n describeModelProblem,\n isTransientError,\n makeRunResult,\n normalizeError,\n outcomeName,\n priorityName,\n requestSignature,\n resolveEngineOptions,\n resolveRequest,\n type G9ResolvedEngineOptions,\n type G9ResolvedSyncRequest,\n type G9RowsAppliedEvent,\n type G9SubscriptionOptions,\n type G9SyncEngineOptions,\n type G9SyncHealth,\n type G9SyncLogLevel,\n type G9SyncModelProblem,\n type G9SyncRequest,\n type G9SyncRunResult,\n} from './runs.js';\nimport {\n G9ApplyReport,\n G9ESubscriptionState,\n toSubscriptionRef,\n type G9ApplySlice,\n type G9ChangeFeedEntry,\n type G9LocalCommand,\n type G9LocalCommandWriter,\n type G9ELocalCommandState,\n type G9LocalRowEntry,\n type G9PendingSummary,\n type G9PushBatch,\n type G9QuarantinedRow,\n type G9RetainedRow,\n type G9SyncClientStore,\n type G9SyncRejection,\n type G9SyncRunReport,\n type G9SyncSubscriptionRecord,\n} from './storeTypes.js';\nimport type { G9SyncTransport } from './transport.js';\n\nconst STAT_CONNECTING = 'Connecting';\nconst STAT_PLANNING = 'Planning';\nconst STAT_PUSH_PER_K_ROW = 'PushPerKRow';\nconst STAT_DOWNLOAD_PER_K_ROW = 'DownloadPerKRow';\nconst STAT_APPLY_PER_K_ROW = 'ApplyPerKRow';\nconst STAT_RECONCILE_PER_SUBSCRIPTION = 'ReconcilePerSubscription';\n\ninterface QueuedRun {\n run: G9SyncRun;\n priority: number;\n order: number;\n}\n\n/**\n * The client sync engine (`G9CSyncEngine`): one per local database. Owns a prioritised run queue, so status queries\n * never wait for a running sync and background runs yield to user runs.\n */\nexport class G9SyncEngine {\n readonly model: G9SyncClientModel;\n private readonly _store: G9SyncClientStore;\n private readonly _transport: G9SyncTransport;\n private readonly _options: G9ResolvedEngineOptions;\n private readonly _lifetime = linkSignals();\n private readonly _queue: QueuedRun[] = [];\n private readonly _pokedTables: { [lower: string]: string } = {};\n private readonly _rowsAppliedListeners: ((event: G9RowsAppliedEvent) => void)[] = [];\n private readonly _runCompletedListeners: ((result: G9SyncRunResult) => void)[] = [];\n private readonly _unsubscribePokes: () => void;\n\n private _initialized = false;\n private _initializing: Promise<void> | null = null;\n private _clientId = '';\n private _order = 0;\n private _current: G9SyncRun | null = null;\n private _suppressions = 0;\n private _autoTimer: ReturnType<typeof setInterval> | null = null;\n private _pokeTimer: ReturnType<typeof setTimeout> | null = null;\n private _wake: (() => void) | null = null;\n private _worker: Promise<void> | null = null;\n private _disposed = false;\n /** The model problems last logged, so the warning is said once per distinct set (ADR-0061). */\n private _reportedModelProblems: string | null = null;\n\n constructor(store: G9SyncClientStore, transport: G9SyncTransport, model: G9SyncClientModel, options?: G9SyncEngineOptions) {\n if (!store) throw new TypeError('A store is required.');\n if (!transport) throw new TypeError('A transport is required.');\n if (!model) throw new TypeError('A model is required.');\n this._store = store;\n this._transport = transport;\n this.model = model;\n this._options = resolveEngineOptions(options);\n this._unsubscribePokes = transport.onChangesAvailable((changes) => this._onChangesAvailable(changes));\n }\n\n get clientId(): string {\n if (!this._initialized) throw new Error('Call initialize first.');\n return this._clientId;\n }\n\n get isRunning(): boolean {\n return this._current !== null;\n }\n\n get queuedRuns(): number {\n return this._queue.length;\n }\n\n get isBackgroundSuppressed(): boolean {\n return this._suppressions > 0;\n }\n\n /** Raised after rows were written locally (download, reconciliation or canonical push results). Returns the unsubscribe function. */\n onRowsApplied(listener: (event: G9RowsAppliedEvent) => void): () => void {\n this._rowsAppliedListeners.push(listener);\n return () => remove(this._rowsAppliedListeners, listener);\n }\n\n onRunCompleted(listener: (result: G9SyncRunResult) => void): () => void {\n this._runCompletedListeners.push(listener);\n return () => remove(this._runCompletedListeners, listener);\n }\n\n /** Provisions local tables and capture, and starts the run worker. Idempotent. */\n initialize(signal?: AbortSignal): Promise<void> {\n if (this._initialized) return Promise.resolve();\n if (!this._initializing) {\n this._initializing = (async () => {\n try {\n await this._store.initialize(this.model, signal);\n this._clientId = await this._store.getClientId(signal);\n this._initialized = true;\n this._worker = this._workerLoop();\n } finally {\n if (!this._initialized) this._initializing = null;\n }\n })();\n }\n return this._initializing;\n }\n\n // ================================================================ subscriptions\n\n /** Adds (or returns) a subscription. Its rows arrive on the next run that includes it. */\n async subscribe(name: string, parameters?: G9SyncParameters | null, options?: G9SubscriptionOptions | null, signal?: AbortSignal): Promise<G9SyncSubscriptionRecord> {\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A subscription name is required.');\n await this.initialize(signal);\n const state = await this._store.getServerState(signal);\n const definition = state.definitions.find((d) => d.name === name) ?? null;\n const ephemeral = options?.ephemeral ?? definition?.ephemeral ?? false;\n const ttlMs = options?.ttlMs ?? (definition && definition.ephemeral && definition.ttlSeconds > 0 ? definition.ttlSeconds * 1000 : null);\n const record = await this._store.ensureSubscription(name, parameters ?? new G9SyncParameters(), ephemeral, ttlMs, options?.adoptExistingRows ?? false, signal);\n await this._store.updateSubscription(record.key, { accessed: true }, signal);\n return record;\n }\n\n /** Removes a subscription; rows no other subscription holds follow the server's move-out policy. */\n async unsubscribe(name: string, parameters?: G9SyncParameters | null, signal?: AbortSignal): Promise<void> {\n await this.initialize(signal);\n const state = await this._store.getServerState(signal);\n const policy = state.definitions.find((d) => d.name === name)?.moveOutPolicy ?? G9EMoveOutPolicy.Delete;\n await this._store.removeSubscription(G9SyncParameters.buildSubscriptionKey(name, parameters ?? null), policy, signal);\n }\n\n async getSubscriptions(signal?: AbortSignal): Promise<G9SyncSubscriptionRecord[]> {\n await this.initialize(signal);\n return this._store.getSubscriptions(signal);\n }\n\n // ================================================================ runs\n\n /** Queues a run. Identical plain requests already waiting are coalesced into one run. */\n run(request?: G9SyncRequest | null): G9SyncRun {\n if (!this._initialized) throw new Error('Call initialize first.');\n const resolved = resolveRequest(request);\n if (canCoalesce(resolved)) {\n const signature = requestSignature(resolved);\n for (const queued of this._queue) {\n const r = queued.run;\n if (!r.isStarted && canCoalesce(r.request) && r.request.priority === resolved.priority && requestSignature(r.request) === signature) return r;\n }\n }\n const run = new G9SyncRun(resolved);\n this._queue.push({ run, priority: resolved.priority, order: this._order++ });\n const current = this._current;\n let preempted: G9SyncRun | null = null;\n if (current !== null && current.request.priority === G9ESyncPriority.Background && resolved.priority > G9ESyncPriority.Background) {\n current.preempted = true;\n preempted = current;\n }\n this._signal();\n if (preempted) {\n preempted.cancel();\n this._log('information', 20001, `Background run ${preempted.runId} pre-empted by run ${run.runId}`);\n }\n return run;\n }\n\n /** Queues a run and awaits its result. */\n sync(request?: G9SyncRequest | null): Promise<G9SyncRunResult> {\n return this.run(request).completion;\n }\n\n /** While the returned scope is alive, background runs are skipped. Call the returned function to end it. */\n suppressBackground(): () => void {\n this._suppressions++;\n let done = false;\n return () => {\n if (done) return;\n done = true;\n this._suppressions--;\n };\n }\n\n /** Queues a background push+pull of every non-heavy subscription on a fixed interval. */\n startAutomaticSync(intervalMs: number): void {\n if (!(intervalMs > 0)) throw new RangeError('The interval must be positive.');\n this.stopAutomaticSync();\n this._autoTimer = setInterval(() => this._tryQueueBackground(null), intervalMs);\n }\n\n stopAutomaticSync(): void {\n if (this._autoTimer !== null) {\n clearInterval(this._autoTimer);\n this._autoTimer = null;\n }\n }\n\n // ================================================================ queries\n\n /**\n * Records a command (ADR-0025): the server executes the handler registered for `name` on the next push, once, in\n * device order. `applyLocally` writes its local effects immediately, in the same transaction.\n */\n async executeCommand(\n name: string,\n payloadJson: string,\n applyLocally?: ((writer: G9LocalCommandWriter, signal?: AbortSignal) => Promise<void>) | null,\n version = 1,\n signal?: AbortSignal,\n ): Promise<G9LocalCommand> {\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A command name is required.');\n if (typeof payloadJson !== 'string') throw new TypeError('The payload JSON is required.');\n await this.initialize(signal);\n return this._store.enqueueCommand({ name, version, payload: payloadJson }, applyLocally ?? null, signal);\n }\n\n /** Frees space taken by an UPLOAD-ONLY table: removes uploaded rows without uploading a delete. */\n async forgetUploadedRows(localTable: string, keys?: readonly string[] | null, signal?: AbortSignal): Promise<number> {\n await this.initialize(signal);\n return this._store.forgetUploadedRows(localTable, keys ?? null, signal);\n }\n\n async getCommands(state?: G9ELocalCommandState | null, limit = 200, signal?: AbortSignal): Promise<G9LocalCommand[]> {\n await this.initialize(signal);\n return this._store.getCommands(state ?? null, limit, signal);\n }\n\n async getPendingSummary(signal?: AbortSignal): Promise<G9PendingSummary> {\n await this.initialize(signal);\n return this._store.getPendingSummary(signal);\n }\n\n async getRejections(signal?: AbortSignal): Promise<G9SyncRejection[]> {\n await this.initialize(signal);\n return this._store.getRejections(signal);\n }\n\n async getQuarantined(signal?: AbortSignal): Promise<G9QuarantinedRow[]> {\n await this.initialize(signal);\n return this._store.getQuarantined(signal);\n }\n\n async restoreQuarantined(localTable: string, key: string, signal?: AbortSignal): Promise<number> {\n await this.initialize(signal);\n return this._store.restoreQuarantined(localTable, key, signal);\n }\n\n /** Throws away every staged pull, so the next run plans afresh. Returns whether there was one. */\n async discardStagedPull(signal?: AbortSignal): Promise<boolean> {\n await this.initialize(signal);\n return (await this._store.discardAllStagedPulls(signal)) > 0;\n }\n\n async discardQuarantined(localTable?: string | null, key?: string | null, signal?: AbortSignal): Promise<number> {\n await this.initialize(signal);\n return this._store.discardQuarantined(localTable ?? null, key ?? null, signal);\n }\n\n async getRetained(signal?: AbortSignal): Promise<G9RetainedRow[]> {\n await this.initialize(signal);\n return this._store.getRetained(signal);\n }\n\n async retryRejected(localTable?: string | null, key?: string | null, signal?: AbortSignal): Promise<number> {\n await this.initialize(signal);\n return this._store.retryRejected(localTable ?? null, key ?? null, signal);\n }\n\n async readChangeFeed(localTable: string, afterSequence: number, limit = 1000, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]> {\n await this.initialize(signal);\n return this._store.readChangeFeed(localTable, afterSequence, limit, signal);\n }\n\n /** The highest sequence readChangeFeed can return today (a watermark above it belongs to a store that no longer exists). */\n async getChangeSequence(signal?: AbortSignal): Promise<number> {\n await this.initialize(signal);\n return this._store.getChangeSequence(signal);\n }\n\n /** The highest sequence ever purged from the change feed; 0 when nothing was (ADR-0059). */\n async getChangeFeedFloor(signal?: AbortSignal): Promise<number> {\n await this.initialize(signal);\n return this._store.getChangeFeedFloor(signal);\n }\n\n async adoptExistingRows(signal?: AbortSignal): Promise<number> {\n await this.initialize(signal);\n return this._store.adoptExistingRows(signal);\n }\n\n async markDirty(localTable: string, keys: readonly string[], signal?: AbortSignal): Promise<number> {\n await this.initialize(signal);\n return this._store.markDirty(localTable, keys, signal);\n }\n\n async getHealth(signal?: AbortSignal): Promise<G9SyncHealth> {\n await this.initialize(signal);\n const state = await this._store.getServerState(signal);\n return {\n clientId: this._clientId,\n isConnected: this._transport.isConnected,\n isRunning: this.isRunning,\n queuedRuns: this.queuedRuns,\n serverEpoch: state.epoch,\n lastHelloUtcMs: state.lastHelloUtcMs,\n pending: await this._store.getPendingSummary(signal),\n subscriptions: await this._store.getSubscriptions(signal),\n recentRuns: await this._store.getRecentRunReports(10, signal),\n };\n }\n\n async dispose(): Promise<void> {\n if (this._disposed) return;\n this._disposed = true;\n this.stopAutomaticSync();\n this._unsubscribePokes();\n this._lifetime.abort();\n const abandoned = this._queue.splice(0, this._queue.length);\n for (const { run } of abandoned) {\n run.complete(makeRunResult({ runId: run.runId, outcome: G9ESyncOutcome.Canceled, error: new G9SyncException(G9SyncErrorCodes.Canceled, 'The sync engine was disposed.') }));\n }\n this._current?.cancel();\n this._signal();\n if (this._worker) {\n try {\n await this._worker;\n } catch {\n // shutting down\n }\n }\n if (this._pokeTimer !== null) {\n clearTimeout(this._pokeTimer);\n this._pokeTimer = null;\n }\n }\n\n // ================================================================ worker\n\n private _signal(): void {\n const wake = this._wake;\n this._wake = null;\n if (wake) wake();\n }\n\n private _dequeue(): G9SyncRun | null {\n if (this._queue.length === 0) return null;\n let best = 0;\n for (let i = 1; i < this._queue.length; i++) {\n const a = this._queue[i] as QueuedRun;\n const b = this._queue[best] as QueuedRun;\n if (a.priority > b.priority || (a.priority === b.priority && a.order < b.order)) best = i;\n }\n return (this._queue.splice(best, 1)[0] as QueuedRun).run;\n }\n\n private async _workerLoop(): Promise<void> {\n while (!this._lifetime.signal.aborted) {\n const run = this._dequeue();\n if (!run) {\n await new Promise<void>((resolve) => {\n this._wake = resolve;\n });\n continue;\n }\n run.isStarted = true;\n this._current = run;\n try {\n await this._executeRun(run);\n } catch (exception) {\n this._log('error', 20002, `Unexpected failure executing run ${run.runId}`, exception);\n run.complete(makeRunResult({ runId: run.runId, outcome: G9ESyncOutcome.Failed, error: normalizeError(exception) }));\n } finally {\n this._current = null;\n }\n // A pre-empted background run still owes its work: queue it again behind the run that pre-empted it.\n if (run.preempted && run.request.priority === G9ESyncPriority.Background) this._tryQueueBackground(run.request.subscriptions);\n }\n }\n\n private _tryQueueBackground(subscriptions: readonly string[] | null): void {\n if (!this._initialized || this.isBackgroundSuppressed || (this._options.hooks && !this._options.hooks.isNetworkAvailable) || this._lifetime.signal.aborted) {\n return;\n }\n this.run({ priority: G9ESyncPriority.Background, subscriptions });\n }\n\n private _onChangesAvailable(payload: G9DtChangesAvailable): void {\n if (!this._options.pullOnChangesAvailable || payload.tables.length === 0) return;\n for (const table of payload.tables) this._pokedTables[table.toLowerCase()] = table;\n if (this._pokeTimer === null) this._pokeTimer = setTimeout(() => this._flushPokes(), this._options.changesDebounceMs);\n }\n\n private _flushPokes(): void {\n const tables = Object.keys(this._pokedTables);\n for (const key of tables) delete this._pokedTables[key];\n this._pokeTimer = null;\n if (tables.length === 0 || !this._initialized) return;\n const signal = this._lifetime.signal;\n void (async () => {\n try {\n const state = await this._store.getServerState(signal);\n const names: { [name: string]: true } = {};\n let any = false;\n for (const d of state.definitions) {\n if (!d.heavy && d.tables.some((t) => tables.indexOf(t.toLowerCase()) >= 0)) {\n names[d.name] = true;\n any = true;\n }\n }\n if (!any) return;\n const keys = (await this._store.getSubscriptions(signal)).filter((s) => names[s.name] === true).map((s) => s.key);\n if (keys.length > 0) this._tryQueueBackground(keys);\n } catch (exception) {\n if (!signal.aborted) this._log('warning', 20003, 'Handling a server change notification failed', exception);\n }\n })();\n }\n\n private _raiseRowsApplied(report: G9ApplyReport, source: G9ESyncPhase, slice: G9ApplySlice | null = null): void {\n for (const listener of this._rowsAppliedListeners.slice()) {\n try {\n listener({ report, source, slice });\n } catch (exception) {\n this._log('warning', 20004, 'A RowsApplied handler threw', exception);\n }\n }\n }\n\n private _log(level: G9SyncLogLevel, eventId: number, message: string, error?: unknown): void {\n const logger = this._options.logger;\n if (!logger) return;\n try {\n logger.log(level, eventId, message, error);\n } catch {\n // A logger must never break the sync.\n }\n }\n\n // ================================================================ execution\n\n private async _executeRun(run: G9SyncRun): Promise<void> {\n const request = run.request;\n const startedUtcMs = Date.now();\n const changes = new G9ApplyReport();\n const problems: G9DtSubscriptionState[] = [];\n let modelProblems: G9SyncModelProblem[] = [];\n const synced: string[] = [];\n let pushed = 0;\n let rejected = 0;\n let conflicts = 0;\n let downloaded = 0;\n let downloadedBytes = 0;\n let reconciled = 0;\n let error: G9SyncException | null = null;\n let outcome: G9ESyncOutcome = G9ESyncOutcome.Succeeded;\n\n const tracker = new G9SyncProgressTracker(run.runId, (p) => run.publish(p), () => this.queuedRuns, this._options.progressMaxHz);\n try {\n if (request.priority === G9ESyncPriority.Background && this.isBackgroundSuppressed) {\n tracker.complete(G9ESyncPhase.Canceled);\n run.complete(makeRunResult({ runId: run.runId, outcome: G9ESyncOutcome.Canceled, error: new G9SyncException(G9SyncErrorCodes.Canceled, 'Background sync is suppressed.') }));\n return;\n }\n\n const linked = linkSignals(run.cancellation.signal, this._lifetime.signal);\n const ct = linked.signal;\n const cancelRegistration = onAbort(ct, () => tracker.setCancelPending());\n let hostScope: { dispose(): void | Promise<void> } | null = null;\n\n try {\n const history = await this._store.getPhaseStatistics(ct);\n const pending = request.push ? await this._store.getPendingSummary(ct) : null;\n this._planPhases(tracker, history, request, pending ? pending.totalRows : 0);\n if (this._options.hooks) hostScope = await this._options.hooks.beginRun(run, ct);\n\n // ---------------------------------------------------------------- 1. connect + hello\n tracker.enter(G9ESyncPhase.Connecting);\n await this._ensureConnected(ct);\n await this._store.collectExpiredEphemeral(Date.now(), ct);\n const subscriptions = await this._store.getSubscriptions(ct);\n const hello = await this._withRetry(\n (token) =>\n this._transport.hello(\n {\n clientId: this._clientId,\n appVersion: this._options.appVersion,\n protocolVersion: 1,\n tables: this.model.tables.map((t) => t.toWire()),\n subscriptions: subscriptions.map(toSubscriptionRef),\n },\n token,\n ),\n ct,\n );\n if (hello.error) throw syncErrorToException(hello.error);\n await this._store.saveHello(hello, ct);\n if (hello.unknownTables.length > 0) {\n this._log('warning', 20016, 'The server does not know these client tables (they will not sync): ' + hello.unknownTables.join(', '));\n }\n\n // A column declared with the wrong type syncs in NEITHER direction (ADR-0061): say it on every run's result, and once\n // per distinct set in the log.\n modelProblems = [];\n for (const table of hello.tables) {\n for (const column of table.typeMismatchColumns) {\n modelProblems.push({ code: G9SyncErrorCodes.ModelTypeMismatch, table: table.name, column: column.name, clientType: column.clientType, serverType: column.serverType });\n }\n }\n if (modelProblems.length > 0) {\n const described = modelProblems.map(describeModelProblem).join('; ');\n if (this._reportedModelProblems !== described) {\n this._reportedModelProblems = described;\n this._log(\n 'warning',\n 20022,\n `The client model declares ${modelProblems.length} column(s) with a type the server does not have; they sync in NEITHER direction until the model is fixed: ${described}`,\n );\n }\n if (this._options.failOnTypeMismatch) {\n throw new G9SyncException(G9SyncErrorCodes.ModelTypeMismatch, 'The client model declares column types the server does not have; those columns would not sync: ' + described);\n }\n }\n\n const negotiated = hello.tables;\n const definitions: { [name: string]: G9DtSubscriptionDefinition } = {};\n for (const d of hello.definitions) definitions[d.name] = d;\n const states: { [key: string]: G9DtSubscriptionState } = {};\n for (const state of hello.subscriptions) states[state.key] = state;\n\n // ---------------------------------------------------------------- 2. push\n // A FAILED PUSH MUST NOT COST THE PULL: the failure is rethrown after the pull, never swallowed.\n let pushFailure: { error: unknown } | null = null;\n if (request.push && pending && (pending.totalRows > 0 || pending.pendingCommands > 0)) {\n tracker.enter(G9ESyncPhase.Pushing, pending.totalRows + pending.pendingCommands);\n try {\n const totals = await this._pushAll(negotiated, subscriptions, hello.maxPushRows, hello.maxPushBytes, tracker, changes, ct);\n pushed = totals.pushed;\n rejected = totals.rejected;\n conflicts = totals.conflicts;\n } catch (exception) {\n if (ct.aborted) throw exception;\n this._log('warning', 20019, `Run ${run.runId}: the push failed; continuing to the pull so the device keeps receiving, then reporting the failure`, exception);\n pushFailure = { error: exception };\n }\n }\n\n if (request.pull) {\n // ------------------------------------------------------------ 3. select subscriptions (+ dependencies)\n const selected = await this._selectSubscriptions(request, subscriptions, definitions, problems, ct);\n const usable: G9SyncSubscriptionRecord[] = [];\n for (const subscription of selected) {\n const state = states[subscription.key];\n if (\n state &&\n (state.action === G9ESubscriptionAction.Unknown || state.action === G9ESubscriptionAction.InvalidParameters || state.action === G9ESubscriptionAction.Forbidden)\n ) {\n problems.push(state);\n await this._store.updateSubscription(subscription.key, { state: G9ESubscriptionState.Failed, errorCode: actionCode(state.action) }, ct);\n // Forbidden: these rows are no longer this caller's to hold (ADR-0048).\n if (state.action === G9ESubscriptionAction.Forbidden) {\n const released = await this._store.releaseSubscriptionRows(subscription.key, ct);\n changes.merge(released);\n if (released.total > 0) {\n this._log(\n 'warning',\n 20018,\n `Subscription ${subscription.key} is forbidden; released its rows (${released.revokedDeleted} deleted, ${released.revokedQuarantined} quarantined, ${released.revokedRetained} retained)`,\n );\n this._raiseRowsApplied(released, G9ESyncPhase.Reconciling);\n }\n }\n continue;\n }\n usable.push(subscription);\n }\n\n // ------------------------------------------------------------ 4. reconcile\n const now = Date.now();\n const toReconcile = usable.filter((s) => needsReconcile(s, request, states, definitions, now));\n tracker.expect(G9ESyncPhase.Reconciling, toReconcile.length * historyOf(history, STAT_RECONCILE_PER_SUBSCRIPTION, 2500));\n if (toReconcile.length > 0) {\n tracker.enter(G9ESyncPhase.Reconciling, toReconcile.length);\n let done = 0;\n for (const subscription of toReconcile) {\n try {\n const report = await this._reconcileSubscription(subscription, definitions[subscription.name] as G9DtSubscriptionDefinition, negotiated, ct);\n changes.merge(report);\n reconciled += report.total;\n if (report.total > 0) this._raiseRowsApplied(report, G9ESyncPhase.Reconciling);\n } catch (exception) {\n if (isSyncException(exception) && !exception.retryable && exception.code !== G9SyncErrorCodes.Canceled) {\n problems.push({ key: subscription.key, action: G9ESubscriptionAction.Reconcile, message: exception.message });\n await this._store.updateSubscription(subscription.key, { state: G9ESubscriptionState.Failed, errorCode: exception.code }, ct);\n } else {\n throw exception;\n }\n }\n tracker.report(++done, -1, null, subscription.key);\n }\n }\n\n // ------------------------------------------------------------ 5. plan (or resume a staged pull)\n tracker.enter(G9ESyncPhase.Planning);\n const failedKeys: { [key: string]: true } = {};\n for (const p of problems) failedKeys[p.key] = true;\n const current: { [key: string]: G9SyncSubscriptionRecord } = {};\n for (const s of await this._store.getSubscriptions(ct)) current[s.key] = s;\n const plannable = usable.filter((s) => !failedKeys[s.key] && current[s.key] !== undefined).map((s) => current[s.key] as G9SyncSubscriptionRecord);\n\n // A stage is kept PER GENERATION (ADR-0060); what makes one resumable is that the epoch, permissions, columns and\n // the cursors it was planned from are all still exactly what they were.\n const generation = stageGeneration(hello, plannable, states, negotiated);\n const pruned = await this._store.pruneStagedPulls(Date.now() - this._options.stagedPullMaxAgeMs, this._options.stagedPullsMaxBytes, generation, ct);\n if (pruned > 0) this._log('information', 20021, `Removed ${pruned} staged pull(s) past their age or the byte cap`);\n\n const staged = await this._store.getStagedPullForGeneration(generation, ct);\n let plan: G9DtPullPlan;\n let runId: string;\n if (staged && staged.createdUtcMs > Date.now() - this._options.stagedPullMaxAgeMs) {\n plan = staged.plan;\n runId = staged.runId;\n this._log('information', 20012, `Resuming staged pull ${runId} (${plan.totalRows} rows planned)`);\n } else {\n const backfills = await this._store.getPendingBackfills(ct);\n plan = await this._withRetry(\n (token) =>\n this._transport.planPull(\n {\n clientId: this._clientId,\n subscriptions: plannable.map(toSubscriptionRef),\n tables: negotiated.map((t) => ({ tableId: t.tableId, columns: t.columns.map((c) => c.name) })),\n backfills: backfills.slice(),\n frameVersion: this._options.maxFrameVersion,\n },\n token,\n ),\n ct,\n );\n if (plan.error) throw syncErrorToException(plan.error);\n runId = guidToN(newGuid());\n const plannedFromCursors: { [key: string]: string | null } = {};\n for (const s of plannable) plannedFromCursors[s.key] = s.cursor;\n await this._store.beginStagedPull(\n { runId, plan, createdUtcMs: Date.now(), backfills, generation, plannedFromCursors, stageSequence: 0 },\n ct,\n );\n }\n\n for (const skipped of plan.skipped) {\n problems.push(skipped);\n if (skipped.action === G9ESubscriptionAction.Reconcile || skipped.action === G9ESubscriptionAction.ResyncRequired) {\n await this._store.updateSubscription(skipped.key, { state: G9ESubscriptionState.NeedsReconcile }, ct);\n }\n }\n\n for (const c of plan.cursors) synced.push(c.key);\n tracker.expect(G9ESyncPhase.Downloading, Math.max(200, (plan.totalRows / 1000) * historyOf(history, STAT_DOWNLOAD_PER_K_ROW, 350)));\n tracker.expect(G9ESyncPhase.Applying, Math.max(100, (plan.totalRows / 1000) * historyOf(history, STAT_APPLY_PER_K_ROW, 250)));\n\n // ------------------------------------------------------------ 6. download (resumable)\n tracker.enter(G9ESyncPhase.Downloading, plan.totalRows, plan.estimatedBytes);\n const totals = await this._download(runId, plan, tracker, ct);\n downloaded = totals.rows;\n downloadedBytes = totals.bytes;\n\n // ------------------------------------------------------------ 7. apply (atomic, or in committed slices)\n tracker.enter(G9ESyncPhase.Applying, downloaded);\n const applied = await this._store.applyStagedPull(\n runId,\n (rows) => tracker.report(rows),\n (slice) => {\n if (slice.report.total > 0) this._raiseRowsApplied(slice.report, G9ESyncPhase.Applying, slice);\n },\n ct,\n );\n changes.merge(applied);\n }\n\n // ---------------------------------------------------------------- 8. post steps\n for (const step of request.postSteps) {\n tracker.enter(G9ESyncPhase.PostStep, 0, 0, step.name);\n await step.action({ run, changes, progress: (fraction) => tracker.reportFraction(fraction) }, ct);\n }\n\n // Rows retained after revocation by a RetainWhile rule are re-checked once per run (ADR-0026).\n changes.revokedDeleted += await this._store.reevaluateRetained(ct);\n\n // The pull has been applied and its cursors committed; now the push failure decides the run's fate.\n if (pushFailure) throw pushFailure.error;\n\n outcome = rejected > 0 || problems.length > 0 ? G9ESyncOutcome.CompletedWithRejections : G9ESyncOutcome.Succeeded;\n tracker.complete(G9ESyncPhase.Completed);\n } catch (exception) {\n if (ct.aborted) {\n outcome = G9ESyncOutcome.Canceled;\n error = new G9SyncException(G9SyncErrorCodes.Canceled, run.preempted ? 'Pre-empted by a higher-priority sync.' : 'The sync was canceled.', { cause: exception });\n tracker.complete(G9ESyncPhase.Canceled);\n } else {\n error = normalizeError(exception);\n outcome = G9ESyncOutcome.Failed;\n tracker.complete(G9ESyncPhase.Failed);\n this._log('warning', 20011, `Run ${run.runId} failed with ${error.code}`, error);\n }\n } finally {\n cancelRegistration();\n linked.dispose();\n if (hostScope) {\n try {\n await hostScope.dispose();\n } catch (exception) {\n this._log('warning', 20004, 'A host scope handler threw', exception);\n }\n }\n }\n\n const durations = tracker.durations;\n const phaseMs: { [phase: string]: number } = {};\n for (const key of Object.keys(durations)) phaseMs[key] = Math.floor(durations[key] as number);\n const result = makeRunResult({\n runId: run.runId,\n outcome,\n error,\n pushed,\n rejected,\n conflicts,\n downloaded,\n applied: changes.total,\n durationMs: Date.now() - startedUtcMs,\n subscriptions: synced,\n problems,\n modelProblems,\n changes,\n phaseMs,\n });\n\n try {\n await this._persistRun(run, result, durations, startedUtcMs, downloadedBytes, reconciled);\n } catch (exception) {\n this._log('warning', 20004, 'A run report handler threw', exception);\n }\n\n this._log(\n 'information',\n 20010,\n `Run ${run.runId} finished ${outcomeName(outcome)}: pushed ${pushed}, downloaded ${downloaded}, applied ${changes.total} in ${result.durationMs} ms`,\n );\n run.complete(result);\n for (const listener of this._runCompletedListeners.slice()) {\n try {\n listener(result);\n } catch (exception) {\n this._log('warning', 20004, 'A RunCompleted handler threw', exception);\n }\n }\n } finally {\n tracker.dispose();\n }\n }\n\n private _planPhases(tracker: G9SyncProgressTracker, history: { [key: string]: number }, request: G9ResolvedSyncRequest, pendingRows: number): void {\n const connecting = historyOf(history, STAT_CONNECTING, 800);\n const pushing = request.push && pendingRows > 0 ? Math.max(300, (pendingRows / 1000) * historyOf(history, STAT_PUSH_PER_K_ROW, 1200)) : 0;\n const planning = request.pull ? historyOf(history, STAT_PLANNING, 700) : 0;\n const downloading = request.pull ? 2000 : 0;\n const applying = request.pull ? 1500 : 0;\n tracker.plan(G9ESyncPhase.Connecting, connecting);\n if (pushing > 0) tracker.plan(G9ESyncPhase.Pushing, pushing);\n if (request.pull) {\n tracker.plan(G9ESyncPhase.Reconciling, 0);\n tracker.plan(G9ESyncPhase.Planning, planning);\n tracker.plan(G9ESyncPhase.Downloading, downloading);\n tracker.plan(G9ESyncPhase.Applying, applying);\n }\n const core = connecting + pushing + planning + downloading + applying;\n for (const step of request.postSteps) {\n const hint = step.weightHint;\n tracker.plan(G9ESyncPhase.PostStep, historyOf(history, 'PostStep:' + step.name, hint >= 0.9 ? core * 9 : (core * hint) / (1 - hint)), step.name);\n }\n }\n\n private async _selectSubscriptions(\n request: G9ResolvedSyncRequest,\n all: G9SyncSubscriptionRecord[],\n definitions: { [name: string]: G9DtSubscriptionDefinition },\n problems: G9DtSubscriptionState[],\n ct: AbortSignal,\n ): Promise<G9SyncSubscriptionRecord[]> {\n const byKey: { [key: string]: G9SyncSubscriptionRecord } = {};\n for (const s of all) byKey[s.key] = s;\n const wanted = request.subscriptions;\n let roots = wanted === null ? all.slice() : all.filter((s) => wanted.indexOf(s.key) >= 0 || wanted.indexOf(s.name) >= 0);\n if (request.priority === G9ESyncPriority.Background && wanted === null) {\n roots = roots.filter((s) => !(definitions[s.name] && (definitions[s.name] as G9DtSubscriptionDefinition).heavy));\n }\n const ordered: G9SyncSubscriptionRecord[] = [];\n const visiting: { [key: string]: true } = {};\n const done: { [key: string]: true } = {};\n\n const visit = async (record: G9SyncSubscriptionRecord): Promise<void> => {\n if (done[record.key] || visiting[record.key]) return;\n visiting[record.key] = true;\n const definition = definitions[record.name];\n if (definition) {\n for (const dependency of definition.dependsOn) {\n const parentDefinition = definitions[dependency.name];\n if (!parentDefinition) {\n if (dependency.required) {\n problems.push({ key: record.key, action: G9ESubscriptionAction.Unknown, message: `Required dependency '${dependency.name}' is not available.` });\n }\n continue;\n }\n let parent = byKey[dependency.name];\n if (!parent) {\n parent = await this._store.ensureSubscription(\n dependency.name,\n new G9SyncParameters(),\n parentDefinition.ephemeral,\n parentDefinition.ephemeral ? parentDefinition.ttlSeconds * 1000 : null,\n false,\n ct,\n );\n byKey[parent.key] = parent;\n }\n await visit(parent);\n }\n }\n done[record.key] = true;\n ordered.push(record);\n };\n\n // Creation order. Two subscriptions created in the same millisecond keep it through their slots (handed out lowest\n // free first), then the key, ordinal (JS `<` compares UTF-16 units, like StringComparer.Ordinal) — never the order\n // the store happened to list them in (by key: a random GUID decided which site's rows came first, LES-0052).\n const sorted = roots\n .map((r, i) => ({ r, i }))\n .sort((a, b) => a.r.createdUtcMs - b.r.createdUtcMs || a.r.slot - b.r.slot || (a.r.key < b.r.key ? -1 : a.r.key > b.r.key ? 1 : 0) || a.i - b.i);\n for (const { r } of sorted) await visit(r);\n return ordered;\n }\n\n private async _pushAll(\n negotiated: G9DtNegotiatedTable[],\n subscriptions: G9SyncSubscriptionRecord[],\n serverMaxRows: number,\n serverMaxBytes: number,\n tracker: G9SyncProgressTracker,\n changes: G9ApplyReport,\n ct: AbortSignal,\n ): Promise<{ pushed: number; rejected: number; conflicts: number }> {\n let pushed = 0;\n let rejected = 0;\n let conflicts = 0;\n const references = subscriptions.map(toSubscriptionRef);\n // The server's limits win over the device's preference; bytes keep a margin for the header and compression variance.\n const targetRows = Math.max(1, serverMaxRows > 0 ? Math.min(this._options.pushBatchRows, serverMaxRows) : this._options.pushBatchRows);\n let batchRows = targetRows;\n const batchBytes = serverMaxBytes > 0 ? Math.floor(serverMaxBytes * 0.9) : Number.MAX_SAFE_INTEGER;\n for (;;) {\n const batch = await this._store.buildPushBatch(negotiated, batchRows, batchBytes, ct);\n if (!batch) break;\n rejected += batch.rejectedLocally;\n if (batch.rowCount === 0 && batch.commands.length === 0) break; // only rows that can never be uploaded were left\n\n const request: G9DtPushRequest = {\n clientId: this._clientId,\n batchId: batch.batchId,\n subscriptions: references,\n tables: batch.tables.slice(),\n commands: batch.commands.slice(),\n // Canonical rows come back in the columns the DEVICE holds (LES-0035).\n heldTables: negotiated\n .filter((t) => batch.commands.length > 0 || batch.tables.some((p) => p.tableId === t.tableId))\n .map((t) => ({ tableId: t.tableId, columns: t.columns.map((c) => c.name) })),\n frameVersion: this._options.maxFrameVersion,\n };\n let result: G9DtPushResult;\n try {\n result = await this._withRetry((token) => this._transport.push(request, toChunks(batch), token), ct);\n if (result.error) throw syncErrorToException(result.error);\n } catch (exception) {\n if (isSyncException(exception) && exception.code === G9SyncErrorCodes.RejectTooMany && batchRows > 1 && batch.rowCount > 1) {\n // The server rolled the WHOLE push back for too many rejections (ADR-0063): halve and resend the smaller prefix\n // under the same batch id, so the valid rows get through and the bad ones are parked one by one.\n batchRows = Math.max(1, Math.floor(Math.min(batchRows, batch.rowCount) / 2));\n this._log(\n 'warning',\n 20023,\n `Push batch ${batch.batchId} of ${batch.rowCount} rows was rolled back for too many rejections; sending it again as ${batchRows} rows so the valid rows get through`,\n );\n continue;\n }\n throw exception;\n }\n\n const report = await this._store.applyPushResult(batch, result, ct);\n changes.merge(report);\n if (report.upserts + report.deletes > 0) this._raiseRowsApplied(report, G9ESyncPhase.Pushing);\n pushed += batch.rowCount + batch.commands.length;\n rejected += result.rejections.length;\n conflicts += result.conflicts.length;\n tracker.report(pushed);\n this._log(\n 'debug',\n 20014,\n `Pushed batch ${batch.batchId}: ${batch.rowCount} rows, ${result.rejections.length} rejected, ${result.conflicts.length} conflicts, replayed ${result.alreadyApplied}`,\n );\n\n if (report.accepted + report.rejected + report.conflicts + report.commandsCompleted === 0 && !result.alreadyApplied) {\n this._log('warning', 20015, `Push batch ${batch.batchId} changed no row state; stopping the push loop for this run`);\n break;\n }\n if (batch.rowCount < batchRows && batch.commands.length < batchRows && !batch.truncated && !result.alreadyApplied) break;\n // After a split: grow back towards the normal size.\n if (batchRows < targetRows) batchRows = Math.min(targetRows, batchRows * 2);\n }\n return { pushed, rejected, conflicts };\n }\n\n private async _download(runId: string, plan: G9DtPullPlan, tracker: G9SyncProgressTracker, ct: AbortSignal): Promise<{ rows: number; bytes: number }> {\n for (let attempt = 0; ; attempt++) {\n const resume = await this._store.getResumePoint(runId, ct);\n let rows = resume.stagedRows;\n let bytes = resume.stagedBytes;\n if (resume.complete) return { rows, bytes };\n tracker.report(rows, bytes);\n try {\n for await (const chunk of this._transport.pull(plan.token, resume.continuation, ct)) {\n await this._store.stageChunk(runId, chunk, ct);\n if (chunk.isFinal) return { rows, bytes };\n rows += chunk.rowCount;\n bytes += chunk.payload ? chunk.payload.length : 0;\n tracker.report(rows, bytes, null, chunk.subscriptionKey ?? null);\n }\n throw new G9SyncException(G9SyncErrorCodes.NetworkFailure, 'The pull stream ended before its final chunk.');\n } catch (exception) {\n if (\n isSyncException(exception) &&\n (exception.code === G9SyncErrorCodes.TokenExpired ||\n exception.code === G9SyncErrorCodes.TokenInvalid ||\n exception.code === G9SyncErrorCodes.ResyncEpoch ||\n exception.code === G9SyncErrorCodes.ResyncAuthChanged)\n ) {\n await this._store.discardStagedPull(runId);\n throw exception;\n }\n if (!ct.aborted && isTransientError(exception) && attempt < this._options.maxRetries) {\n this._log('warning', 20013, `Transient pull failure, retry ${attempt + 1}: ${messageOf(exception)}`);\n await delay(this._backoff(attempt), ct);\n await this._ensureConnected(ct);\n continue;\n }\n throw exception;\n }\n }\n }\n\n private async _withRetry<T>(operation: (signal: AbortSignal) => Promise<T>, ct: AbortSignal): Promise<T> {\n for (let attempt = 0; ; attempt++) {\n try {\n await this._ensureConnected(ct);\n return await operation(ct);\n } catch (exception) {\n if (!ct.aborted && isTransientError(exception) && attempt < this._options.maxRetries) {\n this._log('warning', 20013, `Transient call failure, retry ${attempt + 1}: ${messageOf(exception)}`);\n await delay(this._backoff(attempt), ct);\n continue;\n }\n throw exception;\n }\n }\n }\n\n private _backoff(attempt: number): number {\n return Math.min(30000, this._options.retryBaseDelayMs * Math.pow(2, attempt)) * (0.85 + Math.random() * 0.3);\n }\n\n private async _ensureConnected(ct: AbortSignal): Promise<void> {\n if (!this._transport.isConnected) await this._transport.connect(ct);\n }\n\n private async _persistRun(\n run: G9SyncRun,\n result: G9SyncRunResult,\n durations: { [key: string]: number },\n startedUtcMs: number,\n downloadedBytes: number,\n reconciledRows: number,\n ): Promise<void> {\n const diagnostics = result.changes.diagnostics;\n const phaseMs: { [phase: string]: number } = {};\n for (const key of Object.keys(durations)) phaseMs[key] = Math.floor(durations[key] as number);\n const report: G9SyncRunReport = {\n runId: run.runId,\n startedUtcMs,\n durationMs: result.durationMs,\n outcome: outcomeName(result.outcome),\n priority: priorityName(run.request.priority),\n errorCode: result.error ? result.error.code : null,\n errorMessage: result.error ? result.error.message : null,\n pushed: result.pushed,\n rejected: result.rejected,\n conflicts: result.conflicts,\n downloaded: result.downloaded,\n applied: result.applied,\n downloadedBytes,\n subscriptions: result.subscriptions.slice(),\n phaseMs,\n triggersSkipped: diagnostics.triggersSkipped,\n foreignTriggers: diagnostics.foreignTriggers.slice(),\n applyTransactions: diagnostics.transactions,\n indexesDeferred: diagnostics.deferredIndexCount,\n indexRebuildMs: diagnostics.indexRebuildMs,\n liveIndexReasons: { ...diagnostics.liveIndexReasons },\n unchangedRows: result.changes.unchangedRows,\n };\n await this._store.saveRunReport(report, this._options.keepRunReports);\n\n if (!result.isSuccess) return;\n const samples: { [key: string]: number } = {};\n const connecting = durations[phaseName(G9ESyncPhase.Connecting)];\n if (connecting !== undefined) samples[STAT_CONNECTING] = connecting;\n const planning = durations[phaseName(G9ESyncPhase.Planning)];\n if (planning !== undefined) samples[STAT_PLANNING] = planning;\n const pushingMs = durations[phaseName(G9ESyncPhase.Pushing)];\n if (result.pushed >= 100 && pushingMs !== undefined) samples[STAT_PUSH_PER_K_ROW] = pushingMs / (result.pushed / 1000);\n const downloadingMs = durations[phaseName(G9ESyncPhase.Downloading)];\n if (result.downloaded >= 500 && downloadingMs !== undefined) samples[STAT_DOWNLOAD_PER_K_ROW] = downloadingMs / (result.downloaded / 1000);\n const applyingMs = durations[phaseName(G9ESyncPhase.Applying)];\n if (result.downloaded >= 500 && applyingMs !== undefined) samples[STAT_APPLY_PER_K_ROW] = applyingMs / (result.downloaded / 1000);\n const reconcilingMs = durations[phaseName(G9ESyncPhase.Reconciling)];\n if (reconcilingMs !== undefined && reconciledRows >= 0 && run.request.pull) {\n samples[STAT_RECONCILE_PER_SUBSCRIPTION] = reconcilingMs / Math.max(1, result.subscriptions.length);\n }\n for (const step of run.request.postSteps) {\n const stepMs = durations['PostStep:' + step.name];\n if (stepMs !== undefined) samples['PostStep:' + step.name] = stepMs;\n }\n if (Object.keys(samples).length > 0) await this._store.recordPhaseStatistics(samples);\n if (result.applied > 0) await this._store.purgeDeletedFeed(this._options.keepDeletedFeedEntries);\n }\n\n // ================================================================ reconciliation (D-07)\n\n private async _reconcileSubscription(\n subscription: G9SyncSubscriptionRecord,\n definition: G9DtSubscriptionDefinition,\n negotiated: G9DtNegotiatedTable[],\n ct: AbortSignal,\n ): Promise<G9ApplyReport> {\n const tables: G9DtNegotiatedTable[] = [];\n for (const name of definition.tables) {\n const table = negotiated.find((t) => t.name.toLowerCase() === name.toLowerCase());\n // UploadOnly: the device's own rows, nothing on the server to compare them with.\n if (table && table.direction !== G9ESyncDirection.UploadOnly) tables.push(table);\n }\n\n const request: G9DtReconcileRequest = { clientId: this._clientId, subscription: toSubscriptionRef(subscription), tables: [], frameVersion: this._options.maxFrameVersion };\n for (const table of tables) request.tables.push(await this._store.computeDigest(subscription.key, table, ct));\n\n const serverRows: { [tableId: number]: Map<string, { version: number; hash: G9Long }> } = {};\n let summary: G9DtReconcileSummary | null = null;\n for await (const chunk of this._transport.reconcile(request, ct)) {\n if (chunk.isFinal) {\n summary = chunk.reconcileSummary ?? null;\n break;\n }\n if (!chunk.payload) continue;\n const reader = await openRowBatch(chunk.payload, { maxBodyBytes: this._options.maxDecodedFrameBytes });\n while (reader.nextSection()) {\n let rows = serverRows[reader.tableId];\n if (!rows) serverRows[reader.tableId] = rows = new Map();\n while (reader.readRow()) rows.set(reader.key, { version: reader.version, hash: reader.rowHash });\n }\n }\n if (!summary) throw new G9SyncException(G9SyncErrorCodes.NetworkFailure, 'The reconcile stream ended before its summary.');\n\n const report = new G9ApplyReport();\n let handedToSnapshot = false;\n for (const mismatch of summary.mismatched) {\n const table = tables.find((t) => t.tableId === mismatch.tableId);\n if (!table) continue;\n const server = serverRows[table.tableId] ?? new Map<string, { version: number; hash: G9Long }>();\n const buckets = new Set<number>(mismatch.buckets);\n const serverKeys = new Set<string>();\n server.forEach((_value, key) => serverKeys.add(key));\n const local = await this._store.readLocalEntries(subscription.key, table, buckets, serverKeys, ct);\n const localByKey = new Map<string, G9LocalRowEntry>();\n for (const entry of local) localByKey.set(entry.key, entry);\n\n const fetch: string[] = [];\n const addMembership: string[] = [];\n const moveOut: string[] = [];\n server.forEach(({ hash }, key) => {\n const entry = localByKey.get(key);\n if (!entry) fetch.push(key);\n else if (entry.dirty) {\n // A pending local change is never overwritten here; a row visible again still gets its membership back.\n if (!entry.member) addMembership.push(key);\n } else if (!entry.hash.equals(hash)) fetch.push(key);\n else if (!entry.member) addMembership.push(key);\n });\n for (const entry of local) {\n // Rows with pending changes are released too; the store's revocation policy decides (ADR-0026).\n if (entry.member && buckets.has(entry.bucket) && !server.has(entry.key)) moveOut.push(entry.key);\n }\n\n // A difference this large is a download, not a repair (ADR-0066).\n if (this._options.reconcileSnapshotThreshold > 0 && fetch.length >= this._options.reconcileSnapshotThreshold) {\n const released = await this._store.applyReconcile(subscription.key, table, [], addMembership, moveOut, definition.moveOutPolicy, ct);\n report.merge(released);\n handedToSnapshot = true;\n this._log(\n 'information',\n 20024,\n `Reconciling ${subscription.key} / ${table.name} would fetch ${fetch.length} rows (threshold ${this._options.reconcileSnapshotThreshold}): released what left, and leaving the rows to a staged snapshot pull`,\n );\n continue;\n }\n\n // Fetched and applied in groups (ADR-0066).\n const groupKeys = Math.max(Math.max(1, this._options.fetchKeysPerRequest), this._options.reconcileApplyRows);\n let pendingMembership = addMembership;\n let pendingMoveOut = moveOut;\n let fetched = 0;\n for (const group of chunked(fetch, groupKeys)) {\n const frames: Uint8Array[] = [];\n const returned = new Set<string>();\n for (const keys of chunked(group, Math.max(1, this._options.fetchKeysPerRequest))) {\n const fetchRequest = {\n clientId: this._clientId,\n subscription: toSubscriptionRef(subscription),\n tableId: table.tableId,\n keys,\n columns: table.columns.map((c) => c.name),\n frameVersion: this._options.maxFrameVersion,\n };\n for await (const chunk of this._transport.fetchRows(fetchRequest, ct)) {\n if (chunk.isFinal || !chunk.payload) continue;\n frames.push(chunk.payload);\n const reader = await openRowBatch(chunk.payload, { maxBodyBytes: this._options.maxDecodedFrameBytes });\n while (reader.nextSection()) {\n while (reader.readRow()) returned.add(reader.key);\n }\n }\n }\n // A key listed but not returned left the subscription between listing and fetch.\n const groupMoveOut = group.filter((k) => !returned.has(k) && (localByKey.get(k)?.member ?? false));\n for (const key of pendingMoveOut) groupMoveOut.push(key);\n const applied = await this._store.applyReconcile(subscription.key, table, frames, pendingMembership, groupMoveOut, definition.moveOutPolicy, ct);\n report.merge(applied);\n pendingMembership = [];\n pendingMoveOut = [];\n fetched += group.length;\n }\n if (fetched === 0 && (pendingMembership.length > 0 || pendingMoveOut.length > 0)) {\n report.merge(await this._store.applyReconcile(subscription.key, table, [], pendingMembership, pendingMoveOut, definition.moveOutPolicy, ct));\n }\n this._log(\n 'information',\n 20020,\n `Reconciled ${subscription.key} / ${table.name}: ${mismatch.buckets.length} buckets differed, fetched ${fetch.length}, adopted ${addMembership.length}, moved out ${moveOut.length}`,\n );\n }\n\n await this._store.updateSubscription(\n subscription.key,\n handedToSnapshot\n ? // No cursor: the plan step of this run sees an initial pull and stages a snapshot.\n { clearCursor: true, state: G9ESubscriptionState.Active, clearError: true, reconciled: true }\n : {\n cursor: summary.cursor,\n definitionHash: summary.definitionHash,\n authHash: summary.authHash,\n state: G9ESubscriptionState.Active,\n clearError: true,\n reconciled: true,\n },\n ct,\n );\n return report;\n }\n}\n\n// ---------------------------------------------------------------- helpers\n\nfunction remove<T>(list: T[], item: T): void {\n const index = list.indexOf(item);\n if (index >= 0) list.splice(index, 1);\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction historyOf(history: { [key: string]: number }, key: string, fallback: number): number {\n const value = history[key];\n return value !== undefined && value > 0 ? value : fallback;\n}\n\nfunction needsReconcile(\n subscription: G9SyncSubscriptionRecord,\n request: G9ResolvedSyncRequest,\n states: { [key: string]: G9DtSubscriptionState },\n definitions: { [name: string]: G9DtSubscriptionDefinition },\n nowMs: number,\n): boolean {\n if (subscription.state === G9ESubscriptionState.NeedsReconcile) return true;\n const state = states[subscription.key];\n if (state && (state.action === G9ESubscriptionAction.Reconcile || state.action === G9ESubscriptionAction.ResyncRequired)) return true;\n if (subscription.cursor === null) return false;\n if (request.forceReconcile) return true;\n const definition = definitions[subscription.name];\n return (\n definition !== undefined &&\n definition.reconcileIntervalMinutes > 0 &&\n (subscription.lastReconcileUtcMs ?? subscription.lastSuccessUtcMs ?? subscription.createdUtcMs) < nowMs - definition.reconcileIntervalMinutes * 60000\n );\n}\n\n/**\n * Everything a staged pull's rows depend on (ADR-0046): the server's epoch, the exact set of subscriptions with their\n * definition and authorisation hashes, and the negotiated columns. The cursor is deliberately NOT part of it (ADR-0060).\n */\nexport function stageGeneration(\n hello: G9DtHelloResult,\n plannable: readonly G9SyncSubscriptionRecord[],\n states: { [key: string]: G9DtSubscriptionState },\n negotiated: readonly G9DtNegotiatedTable[],\n): string {\n let text = guidToN(hello.epoch) + '\\n';\n for (const subscription of plannable.slice().sort((a, b) => compareOrdinal(a.key, b.key))) {\n const state = states[subscription.key];\n text += subscription.key + '\\u001F' + ((state ? state.definitionHash : null) ?? subscription.definitionHash ?? '') + '\\u001F' + ((state ? state.authHash : null) ?? subscription.authHash ?? '') + '\\n';\n }\n text += '\\n';\n const tables = negotiated.map((t, i) => ({ t, i })).sort((a, b) => a.t.tableId - b.t.tableId || a.i - b.i);\n for (const { t } of tables) text += String(t.tableId) + '\\u001F' + t.columns.map((c) => c.name).join(',') + '\\n';\n return toHex(sha256(utf8Encode(text)));\n}\n\nfunction actionCode(action: number): string {\n switch (action) {\n case G9ESubscriptionAction.Unknown:\n return G9SyncErrorCodes.UnknownSubscription;\n case G9ESubscriptionAction.Forbidden:\n return G9SyncErrorCodes.SubscriptionForbidden;\n default:\n return G9SyncErrorCodes.InvalidParameters;\n }\n}\n\nfunction chunked<T>(items: readonly T[], size: number): T[][] {\n const out: T[][] = [];\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));\n return out;\n}\n\nasync function* toChunks(batch: G9PushBatch): AsyncGenerator<G9DtSyncChunk> {\n let sequence = 0;\n for (const frame of batch.frames) yield { sequence: sequence++, payload: frame, rowCount: 0, isFinal: false };\n}\n"]}
@@ -0,0 +1,61 @@
1
+ import { G9ESyncColumnType } from '../abstractions/enums.js';
2
+ import type { G9DtClientTableModel } from '../protocol/dtos.js';
3
+ /** A synced column as the client build understands it. */
4
+ export interface G9SyncClientColumn {
5
+ readonly name: string;
6
+ readonly type: G9ESyncColumnType;
7
+ readonly nullable: boolean;
8
+ }
9
+ /** A secondary index the client store creates. */
10
+ export interface G9SyncClientIndex {
11
+ readonly name: string;
12
+ readonly columns: readonly string[];
13
+ readonly unique: boolean;
14
+ }
15
+ /**
16
+ * A synced table of the client model. Column order is the bit order of the local dirty mask; it is local and never sent
17
+ * over the wire (the push maps bits to the negotiated column order).
18
+ */
19
+ export declare class G9SyncClientTable {
20
+ /** Server logical name, e.g. `Operation.Pot`. */
21
+ readonly serverName: string;
22
+ /** Local table name, e.g. `Pot`. */
23
+ readonly localName: string;
24
+ readonly keyColumn: string;
25
+ readonly keyType: G9ESyncColumnType;
26
+ /** Synced columns except the key. */
27
+ readonly columns: readonly G9SyncClientColumn[];
28
+ readonly indexes: readonly G9SyncClientIndex[];
29
+ private readonly _index;
30
+ constructor(serverName: string, localName: string, keyColumn: string, keyType: G9ESyncColumnType, columns: readonly G9SyncClientColumn[], indexes: readonly G9SyncClientIndex[]);
31
+ /** Index of a column (its dirty-mask bit), or -1. Case-insensitive, like .NET's OrdinalIgnoreCase lookup. */
32
+ indexOf(column: string): number;
33
+ toWire(): G9DtClientTableModel;
34
+ }
35
+ /** The immutable client model (`G9CSyncClientModel`). Build it with {@link G9SyncClientModelBuilder}. */
36
+ export declare class G9SyncClientModel {
37
+ readonly tables: readonly G9SyncClientTable[];
38
+ private readonly _byServer;
39
+ private readonly _byLocal;
40
+ constructor(tables: readonly G9SyncClientTable[]);
41
+ findByServerName(serverName: string): G9SyncClientTable | null;
42
+ findByLocalName(localName: string): G9SyncClientTable | null;
43
+ }
44
+ /** Builds the client model (`G9CSyncClientModelBuilder`). */
45
+ export declare class G9SyncClientModelBuilder {
46
+ static readonly MaxColumns = 62;
47
+ private readonly _tables;
48
+ table(serverName: string, localName: string, configure: (table: G9SyncClientTableBuilder) => void): this;
49
+ build(): G9SyncClientModel;
50
+ }
51
+ export declare class G9SyncClientTableBuilder {
52
+ private readonly _columns;
53
+ private readonly _indexes;
54
+ private _key;
55
+ private _keyType;
56
+ key(column: string, type?: G9ESyncColumnType): this;
57
+ column(name: string, type: G9ESyncColumnType, nullable?: boolean): this;
58
+ index(name: string | null, unique: boolean, ...columns: string[]): this;
59
+ /** @internal */
60
+ build(server: string, local: string, errors: string[]): G9SyncClientTable | null;
61
+ }
@@ -0,0 +1,154 @@
1
+ // Twin of G9SyncData.Client/Model/G9CSyncClientModel.cs: the client model and its builder (the .NET source generator
2
+ // has no TypeScript twin; build the model in code, or from the same table list the .NET app generates).
3
+ import { G9ESyncColumnType, columnTypeName, isColumnType } from '../abstractions/enums.js';
4
+ import { G9SyncErrorCodes, G9SyncException } from '../abstractions/errors.js';
5
+ import { G9SyncKey } from '../abstractions/key.js';
6
+ /**
7
+ * A synced table of the client model. Column order is the bit order of the local dirty mask; it is local and never sent
8
+ * over the wire (the push maps bits to the negotiated column order).
9
+ */
10
+ export class G9SyncClientTable {
11
+ constructor(serverName, localName, keyColumn, keyType, columns, indexes) {
12
+ this._index = {};
13
+ this.serverName = serverName;
14
+ this.localName = localName;
15
+ this.keyColumn = keyColumn;
16
+ this.keyType = keyType;
17
+ this.columns = columns;
18
+ this.indexes = indexes;
19
+ for (let i = 0; i < columns.length; i++)
20
+ this._index[columns[i].name.toLowerCase()] = i;
21
+ }
22
+ /** Index of a column (its dirty-mask bit), or -1. Case-insensitive, like .NET's OrdinalIgnoreCase lookup. */
23
+ indexOf(column) {
24
+ const index = this._index[column.toLowerCase()];
25
+ return index === undefined ? -1 : index;
26
+ }
27
+ toWire() {
28
+ return {
29
+ name: this.serverName,
30
+ keyColumn: this.keyColumn,
31
+ keyType: this.keyType,
32
+ columns: this.columns.map((c) => ({ name: c.name, type: c.type, nullable: c.nullable })),
33
+ };
34
+ }
35
+ }
36
+ /** The immutable client model (`G9CSyncClientModel`). Build it with {@link G9SyncClientModelBuilder}. */
37
+ export class G9SyncClientModel {
38
+ constructor(tables) {
39
+ this._byServer = {};
40
+ this._byLocal = {};
41
+ this.tables = tables;
42
+ for (const table of tables) {
43
+ this._byServer[table.serverName.toLowerCase()] = table;
44
+ this._byLocal[table.localName.toLowerCase()] = table;
45
+ }
46
+ }
47
+ findByServerName(serverName) {
48
+ var _a;
49
+ return (_a = this._byServer[serverName.toLowerCase()]) !== null && _a !== void 0 ? _a : null;
50
+ }
51
+ findByLocalName(localName) {
52
+ var _a;
53
+ return (_a = this._byLocal[localName.toLowerCase()]) !== null && _a !== void 0 ? _a : null;
54
+ }
55
+ }
56
+ /** Builds the client model (`G9CSyncClientModelBuilder`). */
57
+ export class G9SyncClientModelBuilder {
58
+ constructor() {
59
+ this._tables = [];
60
+ }
61
+ table(serverName, localName, configure) {
62
+ if (typeof serverName !== 'string' || serverName.trim() === '')
63
+ throw new TypeError('A server table name is required.');
64
+ if (typeof localName !== 'string' || localName.trim() === '')
65
+ throw new TypeError('A local table name is required.');
66
+ const builder = new G9SyncClientTableBuilder();
67
+ configure(builder);
68
+ this._tables.push({ server: serverName, local: localName, builder });
69
+ return this;
70
+ }
71
+ build() {
72
+ const errors = [];
73
+ const tables = [];
74
+ const servers = {};
75
+ const locals = {};
76
+ for (const { server, local, builder } of this._tables) {
77
+ if (servers[server.toLowerCase()])
78
+ errors.push(`Server table '${server}' is mapped twice.`);
79
+ servers[server.toLowerCase()] = true;
80
+ if (locals[local.toLowerCase()])
81
+ errors.push(`Local table '${local}' is mapped twice.`);
82
+ locals[local.toLowerCase()] = true;
83
+ if (local.toLowerCase().indexOf('g9_') === 0)
84
+ errors.push(`Local table '${local}' uses the reserved prefix g9_.`);
85
+ const table = builder.build(server, local, errors);
86
+ if (table)
87
+ tables.push(table);
88
+ }
89
+ if (errors.length > 0) {
90
+ throw new G9SyncException(G9SyncErrorCodes.ModelInvalid, 'The G9SyncData client model is invalid:\n' + errors.map((e) => ' - ' + e).join('\n'));
91
+ }
92
+ return new G9SyncClientModel(tables);
93
+ }
94
+ }
95
+ G9SyncClientModelBuilder.MaxColumns = 62;
96
+ export class G9SyncClientTableBuilder {
97
+ constructor() {
98
+ this._columns = [];
99
+ this._indexes = [];
100
+ this._key = null;
101
+ this._keyType = G9ESyncColumnType.Guid;
102
+ }
103
+ key(column, type = G9ESyncColumnType.Guid) {
104
+ if (typeof column !== 'string' || column.trim() === '')
105
+ throw new TypeError('A key column is required.');
106
+ this._key = column;
107
+ this._keyType = type;
108
+ return this;
109
+ }
110
+ column(name, type, nullable = true) {
111
+ if (typeof name !== 'string' || name.trim() === '')
112
+ throw new TypeError('A column name is required.');
113
+ this._columns.push({ name, type, nullable });
114
+ return this;
115
+ }
116
+ index(name, unique, ...columns) {
117
+ this._indexes.push({ name: name !== null && name !== void 0 ? name : '', columns, unique });
118
+ return this;
119
+ }
120
+ /** @internal */
121
+ build(server, local, errors) {
122
+ const before = errors.length;
123
+ if (this._key === null)
124
+ errors.push(`${local}: no key.`);
125
+ else if (!G9SyncKey.isSupportedKeyType(this._keyType))
126
+ errors.push(`${local}: key type ${columnTypeName(this._keyType)} is not supported.`);
127
+ if (this._columns.length > G9SyncClientModelBuilder.MaxColumns) {
128
+ errors.push(`${local}: ${this._columns.length} columns; the maximum is ${G9SyncClientModelBuilder.MaxColumns}.`);
129
+ }
130
+ const names = {};
131
+ if (this._key !== null)
132
+ names[this._key.toLowerCase()] = true;
133
+ for (const column of this._columns) {
134
+ if (names[column.name.toLowerCase()])
135
+ errors.push(`${local}: column '${column.name}' is declared twice (or as the key).`);
136
+ names[column.name.toLowerCase()] = true;
137
+ if (!isColumnType(column.type))
138
+ errors.push(`${local}.${column.name}: invalid type.`);
139
+ }
140
+ const indexes = [];
141
+ for (const index of this._indexes) {
142
+ if (index.columns.length === 0)
143
+ errors.push(`${local}: an index has no columns.`);
144
+ for (const column of index.columns) {
145
+ if (!names[column.toLowerCase()])
146
+ errors.push(`${local}: index column '${column}' is not a synced column.`);
147
+ }
148
+ const name = index.name.trim() === '' ? 'IX_' + local + '_' + index.columns.join('_') : index.name;
149
+ indexes.push({ name, columns: index.columns.slice(), unique: index.unique });
150
+ }
151
+ return errors.length > before ? null : new G9SyncClientTable(server, local, this._key, this._keyType, this._columns.slice(), indexes);
152
+ }
153
+ }
154
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/client/model.ts"],"names":[],"mappings":"AAAA,qHAAqH;AACrH,wGAAwG;AACxG,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAC3F,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC9E,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAiBnD;;;GAGG;AACH,MAAM,OAAO,iBAAiB;IAY5B,YACE,UAAkB,EAClB,SAAiB,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IAAI,CAAC,QAAQ,EAAE,CAAC;YAClC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC;gBAAE,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,4BAA4B,CAAC,CAAC;YAClF,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;gBACnC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;oBAAE,MAAM,CAAC,IAAI,CAAC,GAAG,KAAK,mBAAmB,MAAM,2BAA2B,CAAC,CAAC;YAC9G,CAAC;YACD,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;YACnG,OAAO,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;QAC/E,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,iBAAiB,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC,IAAc,EAAE,IAAI,CAAC,QAA6B,EAAE,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC;IACvK,CAAC;CACF","sourcesContent":["// Twin of G9SyncData.Client/Model/G9CSyncClientModel.cs: the client model and its builder (the .NET source generator\n// has no TypeScript twin; build the model in code, or from the same table list the .NET app generates).\nimport { G9ESyncColumnType, columnTypeName, isColumnType } from '../abstractions/enums.js';\nimport { G9SyncErrorCodes, G9SyncException } from '../abstractions/errors.js';\nimport { G9SyncKey } from '../abstractions/key.js';\nimport type { G9DtClientTableModel } from '../protocol/dtos.js';\n\n/** A synced column as the client build understands it. */\nexport interface G9SyncClientColumn {\n readonly name: string;\n readonly type: G9ESyncColumnType;\n readonly nullable: boolean;\n}\n\n/** A secondary index the client store creates. */\nexport interface G9SyncClientIndex {\n readonly name: string;\n readonly columns: readonly string[];\n readonly unique: boolean;\n}\n\n/**\n * A synced table of the client model. Column order is the bit order of the local dirty mask; it is local and never sent\n * over the wire (the push maps bits to the negotiated column order).\n */\nexport class G9SyncClientTable {\n /** Server logical name, e.g. `Operation.Pot`. */\n readonly serverName: string;\n /** Local table name, e.g. `Pot`. */\n readonly localName: string;\n readonly keyColumn: string;\n readonly keyType: G9ESyncColumnType;\n /** Synced columns except the key. */\n readonly columns: readonly G9SyncClientColumn[];\n readonly indexes: readonly G9SyncClientIndex[];\n private readonly _index: { [lowerName: string]: number } = {};\n\n constructor(\n serverName: string,\n localName: string,\n keyColumn: string,\n keyType: G9ESyncColumnType,\n columns: readonly G9SyncClientColumn[],\n indexes: readonly G9SyncClientIndex[],\n ) {\n this.serverName = serverName;\n this.localName = localName;\n this.keyColumn = keyColumn;\n this.keyType = keyType;\n this.columns = columns;\n this.indexes = indexes;\n for (let i = 0; i < columns.length; i++) this._index[(columns[i] as G9SyncClientColumn).name.toLowerCase()] = i;\n }\n\n /** Index of a column (its dirty-mask bit), or -1. Case-insensitive, like .NET's OrdinalIgnoreCase lookup. */\n indexOf(column: string): number {\n const index = this._index[column.toLowerCase()];\n return index === undefined ? -1 : index;\n }\n\n toWire(): G9DtClientTableModel {\n return {\n name: this.serverName,\n keyColumn: this.keyColumn,\n keyType: this.keyType,\n columns: this.columns.map((c) => ({ name: c.name, type: c.type, nullable: c.nullable })),\n };\n }\n}\n\n/** The immutable client model (`G9CSyncClientModel`). Build it with {@link G9SyncClientModelBuilder}. */\nexport class G9SyncClientModel {\n readonly tables: readonly G9SyncClientTable[];\n private readonly _byServer: { [lower: string]: G9SyncClientTable } = {};\n private readonly _byLocal: { [lower: string]: G9SyncClientTable } = {};\n\n constructor(tables: readonly G9SyncClientTable[]) {\n this.tables = tables;\n for (const table of tables) {\n this._byServer[table.serverName.toLowerCase()] = table;\n this._byLocal[table.localName.toLowerCase()] = table;\n }\n }\n\n findByServerName(serverName: string): G9SyncClientTable | null {\n return this._byServer[serverName.toLowerCase()] ?? null;\n }\n\n findByLocalName(localName: string): G9SyncClientTable | null {\n return this._byLocal[localName.toLowerCase()] ?? null;\n }\n}\n\n/** Builds the client model (`G9CSyncClientModelBuilder`). */\nexport class G9SyncClientModelBuilder {\n static readonly MaxColumns = 62;\n private readonly _tables: { server: string; local: string; builder: G9SyncClientTableBuilder }[] = [];\n\n table(serverName: string, localName: string, configure: (table: G9SyncClientTableBuilder) => void): this {\n if (typeof serverName !== 'string' || serverName.trim() === '') throw new TypeError('A server table name is required.');\n if (typeof localName !== 'string' || localName.trim() === '') throw new TypeError('A local table name is required.');\n const builder = new G9SyncClientTableBuilder();\n configure(builder);\n this._tables.push({ server: serverName, local: localName, builder });\n return this;\n }\n\n build(): G9SyncClientModel {\n const errors: string[] = [];\n const tables: G9SyncClientTable[] = [];\n const servers: { [lower: string]: true } = {};\n const locals: { [lower: string]: true } = {};\n for (const { server, local, builder } of this._tables) {\n if (servers[server.toLowerCase()]) errors.push(`Server table '${server}' is mapped twice.`);\n servers[server.toLowerCase()] = true;\n if (locals[local.toLowerCase()]) errors.push(`Local table '${local}' is mapped twice.`);\n locals[local.toLowerCase()] = true;\n if (local.toLowerCase().indexOf('g9_') === 0) errors.push(`Local table '${local}' uses the reserved prefix g9_.`);\n const table = builder.build(server, local, errors);\n if (table) tables.push(table);\n }\n if (errors.length > 0) {\n throw new G9SyncException(G9SyncErrorCodes.ModelInvalid, 'The G9SyncData client model is invalid:\\n' + errors.map((e) => ' - ' + e).join('\\n'));\n }\n return new G9SyncClientModel(tables);\n }\n}\n\nexport class G9SyncClientTableBuilder {\n private readonly _columns: G9SyncClientColumn[] = [];\n private readonly _indexes: G9SyncClientIndex[] = [];\n private _key: string | null = null;\n private _keyType: number = G9ESyncColumnType.Guid;\n\n key(column: string, type: G9ESyncColumnType = G9ESyncColumnType.Guid): this {\n if (typeof column !== 'string' || column.trim() === '') throw new TypeError('A key column is required.');\n this._key = column;\n this._keyType = type;\n return this;\n }\n\n column(name: string, type: G9ESyncColumnType, nullable = true): this {\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A column name is required.');\n this._columns.push({ name, type, nullable });\n return this;\n }\n\n index(name: string | null, unique: boolean, ...columns: string[]): this {\n this._indexes.push({ name: name ?? '', columns, unique });\n return this;\n }\n\n /** @internal */\n build(server: string, local: string, errors: string[]): G9SyncClientTable | null {\n const before = errors.length;\n if (this._key === null) errors.push(`${local}: no key.`);\n else if (!G9SyncKey.isSupportedKeyType(this._keyType)) errors.push(`${local}: key type ${columnTypeName(this._keyType)} is not supported.`);\n if (this._columns.length > G9SyncClientModelBuilder.MaxColumns) {\n errors.push(`${local}: ${this._columns.length} columns; the maximum is ${G9SyncClientModelBuilder.MaxColumns}.`);\n }\n const names: { [lower: string]: true } = {};\n if (this._key !== null) names[this._key.toLowerCase()] = true;\n for (const column of this._columns) {\n if (names[column.name.toLowerCase()]) errors.push(`${local}: column '${column.name}' is declared twice (or as the key).`);\n names[column.name.toLowerCase()] = true;\n if (!isColumnType(column.type)) errors.push(`${local}.${column.name}: invalid type.`);\n }\n const indexes: G9SyncClientIndex[] = [];\n for (const index of this._indexes) {\n if (index.columns.length === 0) errors.push(`${local}: an index has no columns.`);\n for (const column of index.columns) {\n if (!names[column.toLowerCase()]) errors.push(`${local}: index column '${column}' is not a synced column.`);\n }\n const name = index.name.trim() === '' ? 'IX_' + local + '_' + index.columns.join('_') : index.name;\n indexes.push({ name, columns: index.columns.slice(), unique: index.unique });\n }\n return errors.length > before ? null : new G9SyncClientTable(server, local, this._key as string, this._keyType as G9ESyncColumnType, this._columns.slice(), indexes);\n }\n}\n"]}
@@ -0,0 +1,101 @@
1
+ /** Phases of a sync run, in execution order (`G9ESyncPhase`). */
2
+ export declare const G9ESyncPhase: {
3
+ readonly Queued: 0;
4
+ readonly Connecting: 1;
5
+ readonly Pushing: 2;
6
+ readonly Reconciling: 3;
7
+ readonly Planning: 4;
8
+ readonly Downloading: 5;
9
+ readonly Applying: 6;
10
+ readonly PostStep: 7;
11
+ readonly Completed: 8;
12
+ readonly Canceled: 9;
13
+ readonly Failed: 10;
14
+ };
15
+ export type G9ESyncPhase = (typeof G9ESyncPhase)[keyof typeof G9ESyncPhase];
16
+ /** The .NET enum member name of a phase (the statistics and PhaseMs keys), e.g. `Downloading`. */
17
+ export declare function phaseName(phase: number): string;
18
+ /**
19
+ * One progress sample. `overall` is monotonic within a run and reaches 1 only when the run completed. The library emits
20
+ * numbers and phases; localising them is the app's job.
21
+ */
22
+ export interface G9DtSyncProgress {
23
+ runId: string;
24
+ phase: G9ESyncPhase;
25
+ /** 0..1, monotonic. */
26
+ overall: number;
27
+ /** 0..1 inside the phase. */
28
+ phaseFraction: number;
29
+ rowsDone: number;
30
+ rowsTotal: number;
31
+ bytesDone: number;
32
+ bytesTotal: number;
33
+ subscriptionKey: string | null;
34
+ table: string | null;
35
+ rowsPerSecond: number;
36
+ /** Estimated milliseconds to completion of the run, or null while unknown. */
37
+ etaMs: number | null;
38
+ queuedBehind: number;
39
+ postStepName: string | null;
40
+ cancelPending: boolean;
41
+ }
42
+ /**
43
+ * Turns phase transitions and counts into monotonic progress. Each phase entered gets a span of the REMAINING bar in
44
+ * proportion to its expected share of the remaining work, so monotonicity holds by construction; a phase without a
45
+ * real signal creeps toward 90% of its span along an exponential curve scaled by its expected duration.
46
+ */
47
+ export declare class G9SyncProgressTracker {
48
+ private readonly _runId;
49
+ private readonly _publish;
50
+ private readonly _queuedBehind;
51
+ private readonly _minIntervalMs;
52
+ private readonly _plan;
53
+ private readonly _durations;
54
+ private readonly _runStart;
55
+ private _phaseStart;
56
+ private _timer;
57
+ private _phase;
58
+ private _postStep;
59
+ private _table;
60
+ private _subscription;
61
+ private _base;
62
+ private _span;
63
+ private _overall;
64
+ private _fraction;
65
+ private _phaseExpectedMs;
66
+ private _rowsDone;
67
+ private _rowsTotal;
68
+ private _bytesDone;
69
+ private _bytesTotal;
70
+ private _lastPublish;
71
+ private _realSignal;
72
+ private _terminal;
73
+ private _cancelPending;
74
+ private _disposed;
75
+ private _lastPublished;
76
+ constructor(runId: string, publish: (progress: G9DtSyncProgress) => void, queuedBehind: () => number, maxHz: number);
77
+ get overall(): number;
78
+ /** Measured milliseconds per phase (post steps keyed `PostStep:name`). */
79
+ get durations(): {
80
+ [key: string]: number;
81
+ };
82
+ /** Appends a phase to the plan with its expected duration. */
83
+ plan(phase: G9ESyncPhase, expectedMs: number, name?: string | null): void;
84
+ /** Updates the expected duration of a planned phase that has not started yet. */
85
+ expect(phase: G9ESyncPhase, expectedMs: number, name?: string | null): void;
86
+ enter(phase: G9ESyncPhase, rowsTotal?: number, bytesTotal?: number, name?: string | null): void;
87
+ /** Reports absolute counts for the current phase. */
88
+ report(rowsDone: number, bytesDone?: number, table?: string | null, subscriptionKey?: string | null): void;
89
+ /** Reports a 0..1 fraction of the current phase (post steps). */
90
+ reportFraction(fraction: number): void;
91
+ setCancelPending(): void;
92
+ complete(terminal: G9ESyncPhase): void;
93
+ dispose(): void;
94
+ private _stopTimer;
95
+ private _creep;
96
+ private _advance;
97
+ private _close;
98
+ private _sample;
99
+ /** Publishes a sample unless it would go backwards (lower overall or an earlier phase). */
100
+ private _emit;
101
+ }