@syncular/client 0.57.0 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +7 -7
  2. package/dist/apply.d.ts +20 -11
  3. package/dist/apply.js +67 -45
  4. package/dist/blob.d.ts +17 -9
  5. package/dist/blob.js +5 -6
  6. package/dist/bun-database.d.ts +1 -0
  7. package/dist/bun-database.js +28 -0
  8. package/dist/client.d.ts +27 -10
  9. package/dist/client.js +357 -190
  10. package/dist/database.d.ts +5 -0
  11. package/dist/encryption.d.ts +2 -2
  12. package/dist/encryption.js +8 -2
  13. package/dist/errors.d.ts +2 -0
  14. package/dist/errors.js +4 -0
  15. package/dist/failed-overlay.d.ts +0 -1
  16. package/dist/failed-overlay.js +3 -6
  17. package/dist/http.d.ts +4 -1
  18. package/dist/http.js +61 -39
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/invalidation.d.ts +11 -10
  22. package/dist/invalidation.js +15 -26
  23. package/dist/local-purge.js +9 -12
  24. package/dist/local-rebootstrap.js +2 -2
  25. package/dist/multi-tab.d.ts +89 -1
  26. package/dist/multi-tab.js +70 -31
  27. package/dist/native-bridge.d.ts +235 -0
  28. package/dist/native-bridge.js +789 -0
  29. package/dist/node-database.d.ts +1 -0
  30. package/dist/node-database.js +29 -0
  31. package/dist/outbox.d.ts +9 -12
  32. package/dist/outbox.js +19 -36
  33. package/dist/outcomes.js +3 -3
  34. package/dist/previous-version.js +96 -114
  35. package/dist/query-guard.d.ts +25 -24
  36. package/dist/query-guard.js +34 -191
  37. package/dist/reactive-store.js +53 -11
  38. package/dist/realtime-supervisor.d.ts +9 -2
  39. package/dist/realtime-supervisor.js +31 -7
  40. package/dist/remote.js +11 -15
  41. package/dist/schema.js +15 -10
  42. package/dist/sync-scheduler.js +28 -2
  43. package/dist/transport.d.ts +19 -4
  44. package/dist/wasm-database.js +58 -21
  45. package/dist/worker-core.d.ts +5 -0
  46. package/dist/worker-core.js +80 -72
  47. package/dist/worker-host.d.ts +10 -5
  48. package/dist/worker-host.js +64 -7
  49. package/dist/worker-local-authority.js +2 -2
  50. package/dist/worker-protocol.d.ts +6 -2
  51. package/package.json +11 -3
  52. package/src/apply.ts +91 -55
  53. package/src/blob.ts +27 -15
  54. package/src/bun-database.ts +29 -0
  55. package/src/client.ts +477 -261
  56. package/src/database.ts +5 -0
  57. package/src/encryption.ts +10 -5
  58. package/src/errors.ts +8 -0
  59. package/src/failed-overlay.ts +3 -7
  60. package/src/http.ts +90 -79
  61. package/src/index.ts +1 -1
  62. package/src/invalidation.ts +17 -32
  63. package/src/local-purge.ts +11 -13
  64. package/src/local-rebootstrap.ts +2 -3
  65. package/src/multi-tab.ts +88 -30
  66. package/src/native-bridge.ts +1189 -0
  67. package/src/node-database.ts +32 -0
  68. package/src/outbox.ts +19 -41
  69. package/src/outcomes.ts +3 -5
  70. package/src/previous-version.ts +103 -114
  71. package/src/query-guard.ts +43 -180
  72. package/src/reactive-store.ts +50 -10
  73. package/src/realtime-supervisor.ts +37 -12
  74. package/src/remote.ts +12 -16
  75. package/src/schema.ts +19 -12
  76. package/src/sync-scheduler.ts +31 -1
  77. package/src/transport.ts +21 -2
  78. package/src/wasm-database.ts +76 -27
  79. package/src/worker-core.ts +94 -74
  80. package/src/worker-host.ts +63 -16
  81. package/src/worker-local-authority.ts +2 -5
  82. package/src/worker-protocol.ts +6 -2
@@ -10,6 +10,7 @@ export declare class NodeClientDatabase implements ClientDatabase {
10
10
  constructor(path?: string);
11
11
  exec(sql: string, params?: readonly SqlValue[]): void;
12
12
  query(sql: string, params?: readonly SqlValue[]): SqlRow[];
13
+ queryReadOnly(sql: string, params?: readonly SqlValue[]): SqlRow[];
13
14
  /** RFC 0005: a sibling file beside the replica, e.g. `<path>.prev-context`. */
14
15
  openSibling(name: string): SiblingDatabase;
15
16
  siblingExists(name: string): boolean;
@@ -7,6 +7,7 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
7
7
  import { tmpdir } from 'node:os';
8
8
  import { join } from 'node:path';
9
9
  import { assertImageAlias, runTransaction, } from './database.js';
10
+ import { prepareReadOnly, SQL_BLANK } from './query-guard.js';
10
11
  function coerceParams(params) {
11
12
  return params.map((value) => {
12
13
  if (typeof value === 'boolean')
@@ -50,6 +51,34 @@ export class NodeClientDatabase {
50
51
  const rows = this.db.prepare(sql).all(...coerceParams(params));
51
52
  return rows.map(normalizeRow);
52
53
  }
54
+ queryReadOnly(sql, params = []) {
55
+ const statement = prepareReadOnly(sql, () => {
56
+ const prepared = this.db.prepare(sql);
57
+ // node:sqlite exposes no `sqlite3_stmt_readonly` (and no column count
58
+ // before Node 22.16), so the verb decides: SELECT, VALUES, EXPLAIN, or
59
+ // a WITH clause whose first keyword outside parentheses is SELECT or
60
+ // VALUES.
61
+ const body = prepared.sourceSQL.replace(SQL_BLANK, '');
62
+ const verb = /^[a-z]+/i.exec(body)?.[0].toLowerCase();
63
+ let reads = verb === 'select' || verb === 'values' || verb === 'explain';
64
+ if (verb === 'with') {
65
+ let depth = 0;
66
+ for (const [token] of body.matchAll(/'[^']*'|"[^"]*"|`[^`]*`|\[[^\]]*\]|--[^\n]*|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$)|[\w$\u0080-\uffff]+|[\s\S]/g)) {
67
+ if (token === '(')
68
+ depth += 1;
69
+ else if (token === ')')
70
+ depth -= 1;
71
+ else if (depth === 0 &&
72
+ /^(?:select|values|insert|update|delete|replace)$/i.test(token)) {
73
+ reads = /^(?:select|values)$/i.test(token);
74
+ break;
75
+ }
76
+ }
77
+ }
78
+ return [prepared, prepared.sourceSQL, reads];
79
+ });
80
+ return statement.all(...coerceParams(params)).map(normalizeRow);
81
+ }
53
82
  /** RFC 0005: a sibling file beside the replica, e.g. `<path>.prev-context`. */
54
83
  openSibling(name) {
55
84
  const siblingPath = this.#path === ':memory:' ? ':memory:' : `${this.#path}.${name}`;
package/dist/outbox.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export declare const OUTBOX_TABLE = "_syncular_outbox";
2
2
  export declare const OUTBOX_IMAGES = "_syncular_outbox_before_images";
3
- import { type OverlayScope } from './failed-overlay.js';
3
+ import type { OverlayScope } from './failed-overlay.js';
4
4
  /**
5
5
  * The durable outbox (SPEC.md §7.1) with encode-at-send (the §0 binary-push
6
6
  * outbox rule): local mutations are persisted in a schema-agnostic JSON
@@ -8,7 +8,7 @@ import { type OverlayScope } from './failed-overlay.js';
8
8
  * request is built — a commit recorded under schema N replays after an
9
9
  * upgrade to N+1 by re-encoding.
10
10
  */
11
- import { type PushCommitFrame, type ScopeMap } from '@syncular/core';
11
+ import { type PushCommitFrame } from '@syncular/core';
12
12
  import type { ClientDatabase } from './database.js';
13
13
  import type { EncryptionConfig } from './encryption.js';
14
14
  import { ClientSyncError } from './errors.js';
@@ -47,7 +47,11 @@ export interface OutboxBeforeImage {
47
47
  readonly values?: Readonly<Record<string, JsonRowValue>>;
48
48
  }
49
49
  export declare function appendOutboxCommit(db: ClientDatabase, clientCommitId: string, operations: readonly OutboxOperation[], nowMs: number, beforeImages?: readonly OutboxBeforeImage[]): void;
50
- /** Pending commits in FIFO creation order (§7.1). Full reads serve replay and the public listing. */
50
+ /**
51
+ * Pending commits in FIFO creation order (§7.1). Full reads serve replay and
52
+ * the public listing; a scoped read finds commits through the before-image
53
+ * row index and never parses operation bodies it does not return.
54
+ */
51
55
  export declare function listOutbox(db: ClientDatabase, scope?: OverlayScope): OutboxCommit[];
52
56
  /** Keyset pages bound staging; laziness decodes only commits consumed by the encoder. */
53
57
  export declare function iterateOutbox(db: ClientDatabase, throughSeq: number): Generator<OutboxCommit>;
@@ -55,7 +59,8 @@ export declare function iterateOutbox(db: ClientDatabase, throughSeq: number): G
55
59
  export declare function countOutbox(db: ClientDatabase): number;
56
60
  export declare function deleteOutboxCommit(db: ClientDatabase, clientCommitId: string): void;
57
61
  export declare function listOutboxBeforeImages(db: ClientDatabase, clientCommitId: string): OutboxBeforeImage[];
58
- export declare function replaceOutboxBeforeImages(db: ClientDatabase, clientCommitId: string, replacements: readonly OutboxBeforeImage[]): void;
62
+ /** Each image carries its operation's row key, the index of every per-row outbox lookup. */
63
+ export declare function replaceOutboxBeforeImages(db: ClientDatabase, commit: Pick<OutboxCommit, 'clientCommitId' | 'operations'>, replacements: readonly OutboxBeforeImage[]): void;
59
64
  /**
60
65
  * §7.4.4: after a schema bump, a persisted upsert may name a column the new
61
66
  * schema no longer has. The value has nowhere to go and there is no
@@ -74,11 +79,3 @@ export declare class OutboxEncodeError extends ClientSyncError {
74
79
  * key-id selector for a sparse upsert that omits that column (§5.11).
75
80
  */
76
81
  export declare function encodeOutboxCommit(schema: CompiledClientSchema, commit: OutboxCommit, encryption?: EncryptionConfig, storedKeyIdFor?: (table: CompiledClientTable, rowId: string) => string | undefined): Promise<PushCommitFrame>;
77
- /**
78
- * §3.3: drop pending commits that write into a revoked scope instead of
79
- * replaying them into guaranteed rejections. A whole commit is dropped when
80
- * any of its upserts provably lands in the revoked effective scopes —
81
- * commits are atomic and their content is pinned by the idempotency key,
82
- * so ops are never removed individually. Returns dropped commit ids.
83
- */
84
- export declare function dropOutboxCommitsInScope(db: ClientDatabase, table: CompiledClientTable, effective: ScopeMap): string[];
package/dist/outbox.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { BLOB_COMMIT_REFS } from './blob.js';
2
2
  export const OUTBOX_TABLE = '_syncular_outbox';
3
3
  export const OUTBOX_IMAGES = '_syncular_outbox_before_images';
4
- import { overlayScopePredicate } from './failed-overlay.js';
5
4
  /**
6
5
  * The durable outbox (SPEC.md §7.1) with encode-at-send (the §0 binary-push
7
6
  * outbox rule): local mutations are persisted in a schema-agnostic JSON
@@ -10,21 +9,25 @@ import { overlayScopePredicate } from './failed-overlay.js';
10
9
  * upgrade to N+1 by re-encoding.
11
10
  */
12
11
  import { encodeSparseRow, } from '@syncular/core';
13
- import { ClientSyncError } from './errors.js';
14
- import { jsonToRowValue, matchesLocalScopes, } from './schema.js';
12
+ import { ClientSyncError, invalidRequest } from './errors.js';
13
+ import { jsonToRowValue, } from './schema.js';
15
14
  export function appendOutboxCommit(db, clientCommitId, operations, nowMs, beforeImages = []) {
16
15
  if (operations.length === 0) {
17
16
  throw new ClientSyncError('sync.empty_commit', 'a local commit must carry at least one operation (§6.1)');
18
17
  }
19
18
  db.exec(`INSERT INTO ${OUTBOX_TABLE}(client_commit_id,created_at_ms,operations)VALUES(?,?,?)`, [clientCommitId, nowMs, JSON.stringify(operations)]);
20
- replaceOutboxBeforeImages(db, clientCommitId, beforeImages);
19
+ replaceOutboxBeforeImages(db, { clientCommitId, operations }, beforeImages);
21
20
  }
22
- /** Pending commits in FIFO creation order (§7.1). Full reads serve replay and the public listing. */
21
+ /**
22
+ * Pending commits in FIFO creation order (§7.1). Full reads serve replay and
23
+ * the public listing; a scoped read finds commits through the before-image
24
+ * row index and never parses operation bodies it does not return.
25
+ */
23
26
  export function listOutbox(db, scope) {
24
27
  return db
25
28
  .query(scope === undefined
26
29
  ? `SELECT * FROM ${OUTBOX_TABLE} ORDER BY seq ASC`
27
- : `SELECT * FROM ${OUTBOX_TABLE} WHERE EXISTS(SELECT 1 FROM json_each(operations) WHERE ${overlayScopePredicate("json_extract(value,'$.table')", "json_extract(value,'$.rowId')")}) ORDER BY seq`, scope && [JSON.stringify(scope)])
30
+ : `SELECT * FROM ${OUTBOX_TABLE} WHERE client_commit_id IN(SELECT client_commit_id FROM ${OUTBOX_IMAGES} WHERE (tbl,row_id) IN(SELECT json_extract(value,'$[0]'),json_extract(value,'$[1]') FROM json_each(?1)) UNION SELECT client_commit_id FROM ${OUTBOX_IMAGES} WHERE tbl IN(SELECT json_extract(value,'$[0]') FROM json_each(?1) WHERE json_array_length(value)=1)) ORDER BY seq`, scope && [JSON.stringify(scope)])
28
31
  .map(decodeOutboxRow);
29
32
  }
30
33
  function decodeOutboxRow(row) {
@@ -84,11 +87,16 @@ export function listOutboxBeforeImages(db, clientCommitId) {
84
87
  : {}),
85
88
  }));
86
89
  }
87
- export function replaceOutboxBeforeImages(db, clientCommitId, replacements) {
90
+ /** Each image carries its operation's row key, the index of every per-row outbox lookup. */
91
+ export function replaceOutboxBeforeImages(db, commit, replacements) {
88
92
  for (const image of replacements) {
89
- db.exec(`INSERT INTO ${OUTBOX_IMAGES}(client_commit_id,op_index,existed,sync_version,values_json)VALUES(?,?,?,?,?) ON CONFLICT(client_commit_id,op_index)DO UPDATE SET existed=excluded.existed,sync_version=excluded.sync_version,values_json=excluded.values_json`, [
90
- clientCommitId,
93
+ // Images are captured per operation index of this same commit.
94
+ const operation = commit.operations[image.opIndex];
95
+ db.exec(`INSERT INTO ${OUTBOX_IMAGES}(client_commit_id,op_index,tbl,row_id,existed,sync_version,values_json)VALUES(?,?,?,?,?,?,?) ON CONFLICT(client_commit_id,op_index)DO UPDATE SET existed=excluded.existed,sync_version=excluded.sync_version,values_json=excluded.values_json`, [
96
+ commit.clientCommitId,
91
97
  image.opIndex,
98
+ operation.table,
99
+ operation.rowId,
92
100
  image.existed ? 1 : 0,
93
101
  image.syncVersion ?? null,
94
102
  image.values === undefined ? null : JSON.stringify(image.values),
@@ -155,10 +163,10 @@ export async function encodeOutboxCommit(schema, commit, encryption, storedKeyId
155
163
  throw new OutboxEncodeError(`outbox table ${JSON.stringify(op.table)} is absent from the current schema (§7.4.4)`);
156
164
  }
157
165
  if (op.values === undefined) {
158
- throw new ClientSyncError('sync.invalid_request', `outbox upsert on ${op.table}/${op.rowId} has no values`);
166
+ throw invalidRequest(`outbox upsert on ${op.table}/${op.rowId} has no values`);
159
167
  }
160
168
  let values = sparseValues(table, op.values, op.insert === true);
161
- if (encryption !== undefined && table.hasEncryptedColumns) {
169
+ if (table.hasEncryptedColumns) {
162
170
  // Lazy: opt-in E2EE never enters an encryption-free app's bundle.
163
171
  const { encryptRowValues } = await import('./encryption.js');
164
172
  values = await encryptRowValues(encryption, table, op.rowId, values, storedKeyIdFor?.(table, op.rowId));
@@ -177,28 +185,3 @@ export async function encodeOutboxCommit(schema, commit, encryption, storedKeyId
177
185
  operations,
178
186
  };
179
187
  }
180
- /**
181
- * §3.3: drop pending commits that write into a revoked scope instead of
182
- * replaying them into guaranteed rejections. A whole commit is dropped when
183
- * any of its upserts provably lands in the revoked effective scopes —
184
- * commits are atomic and their content is pinned by the idempotency key,
185
- * so ops are never removed individually. Returns dropped commit ids.
186
- */
187
- export function dropOutboxCommitsInScope(db, table, effective) {
188
- const entries = Object.entries(effective);
189
- if (entries.length === 0)
190
- return [];
191
- const dropped = [];
192
- for (const commit of listOutbox(db)) {
193
- const inScope = commit.operations.some((op) => {
194
- if (op.table !== table.name || op.values === undefined)
195
- return false;
196
- return matchesLocalScopes(table, effective, op.values);
197
- });
198
- if (inScope) {
199
- deleteOutboxCommit(db, commit.clientCommitId);
200
- dropped.push(commit.clientCommitId);
201
- }
202
- }
203
- return dropped;
204
- }
package/dist/outcomes.js CHANGED
@@ -10,7 +10,7 @@ import { RETAINED_ROWS } from './failed-overlay.js';
10
10
  * deliberately stay local; retention never deletes an unresolved failure.
11
11
  */
12
12
  import { normalizeRejectionDetails, } from '@syncular/core';
13
- import { ClientSyncError } from './errors.js';
13
+ import { ClientSyncError, invalidRequest } from './errors.js';
14
14
  import { isBytesEnvelope, mapRowValues, jsonToRowValue, rowValueToJson, } from './schema.js';
15
15
  function encodeResults(results) {
16
16
  const stored = results.map((result) => {
@@ -252,7 +252,7 @@ export function persistedCommitOutcome(db, clientCommitId) {
252
252
  export function listCommitOutcomes(db, query = {}) {
253
253
  const limit = query.limit;
254
254
  if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) {
255
- throw new ClientSyncError('sync.invalid_request', 'commit outcome limit must be a positive safe integer');
255
+ throw invalidRequest('commit outcome limit must be a positive safe integer');
256
256
  }
257
257
  const where = query.activeOnly
258
258
  ? "WHERE resolution = 'active' AND status IN ('conflict', 'rejected')"
@@ -275,7 +275,7 @@ export function persistCommitOutcomeResolution(db, input, nowMs) {
275
275
  */
276
276
  export function pruneCommitOutcomes(db, maxEntries) {
277
277
  if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
278
- throw new ClientSyncError('sync.invalid_request', 'outcome retention maxEntries must be a positive safe integer');
278
+ throw invalidRequest('outcome retention maxEntries must be a positive safe integer');
279
279
  }
280
280
  const count = db.query(`SELECT COUNT(*) AS count FROM ${OUTCOMES_TABLE}`)[0]
281
281
  ?.count;
@@ -30,6 +30,9 @@ const COPY_BATCH_ROWS = 500;
30
30
  const MAX_AUDIT_INCOMPATIBLE = 200;
31
31
  /** Read spec `limit` ceiling (D7). */
32
32
  export const PREVIOUS_VERSION_MAX_LIMIT = 200;
33
+ function isRecord(value) {
34
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
35
+ }
33
36
  function isCount(value) {
34
37
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
35
38
  }
@@ -45,10 +48,7 @@ function isSqlValue(value) {
45
48
  value instanceof Uint8Array);
46
49
  }
47
50
  function isSqlRow(value) {
48
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
49
- return false;
50
- }
51
- return Object.values(value).every(isSqlValue);
51
+ return isRecord(value) && Object.values(value).every(isSqlValue);
52
52
  }
53
53
  const PREVIOUS_VERSION_REASONS = [
54
54
  'not-configured',
@@ -83,16 +83,16 @@ const AUDIT_ENTRY_KEYS = ['column', 'commitId', 'reason', 'table'];
83
83
  function parseJsonObject(raw) {
84
84
  try {
85
85
  const parsed = JSON.parse(raw);
86
- return parsed !== null &&
87
- typeof parsed === 'object' &&
88
- !Array.isArray(parsed)
89
- ? parsed
90
- : undefined;
86
+ return isRecord(parsed) ? parsed : undefined;
91
87
  }
92
88
  catch {
93
89
  return undefined;
94
90
  }
95
91
  }
92
+ function hasExactKeys(record, expected) {
93
+ return (Object.keys(record).length === expected.length &&
94
+ expected.every((key) => Object.hasOwn(record, key)));
95
+ }
96
96
  function localCorrupt(what) {
97
97
  throw new ClientSyncError('sync.local_corrupt', `persisted ${what} is invalid`);
98
98
  }
@@ -113,40 +113,31 @@ function decodeColumns(value) {
113
113
  if (!Array.isArray(value))
114
114
  return localCorrupt('schema descriptor');
115
115
  return value.map((entry) => {
116
- if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
116
+ if (!isRecord(entry)) {
117
117
  return localCorrupt('schema descriptor');
118
118
  }
119
- const column = entry;
120
- const keys = Object.keys(column).sort();
121
- if (keys.length !== 2 ||
122
- keys[0] !== 'name' ||
123
- keys[1] !== 'type' ||
124
- typeof column.name !== 'string' ||
125
- typeof column.type !== 'string' ||
126
- !COLUMN_TYPES.has(column.type)) {
119
+ if (!hasExactKeys(entry, ['name', 'type']) ||
120
+ typeof entry.name !== 'string' ||
121
+ typeof entry.type !== 'string' ||
122
+ !COLUMN_TYPES.has(entry.type)) {
127
123
  return localCorrupt('schema descriptor');
128
124
  }
129
- return { name: column.name, type: column.type };
125
+ return { name: entry.name, type: entry.type };
130
126
  });
131
127
  }
132
128
  function decodeTable(value) {
133
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
129
+ if (!isRecord(value)) {
134
130
  return localCorrupt('schema descriptor');
135
131
  }
136
- const table = value;
137
- const keys = Object.keys(table).sort();
138
- if (keys.length !== 3 ||
139
- keys[0] !== 'columns' ||
140
- keys[1] !== 'name' ||
141
- keys[2] !== 'primaryKey' ||
142
- typeof table.name !== 'string' ||
143
- typeof table.primaryKey !== 'string') {
132
+ if (!hasExactKeys(value, ['columns', 'name', 'primaryKey']) ||
133
+ typeof value.name !== 'string' ||
134
+ typeof value.primaryKey !== 'string') {
144
135
  return localCorrupt('schema descriptor');
145
136
  }
146
137
  return {
147
- name: table.name,
148
- primaryKey: table.primaryKey,
149
- columns: decodeColumns(table.columns),
138
+ name: value.name,
139
+ primaryKey: value.primaryKey,
140
+ columns: decodeColumns(value.columns),
150
141
  };
151
142
  }
152
143
  /**
@@ -172,11 +163,7 @@ function decodeLocalSchemaDescriptor(value) {
172
163
  const record = parseJsonObject(value);
173
164
  if (record === undefined)
174
165
  return localCorrupt('schema descriptor');
175
- const keys = Object.keys(record).sort();
176
- if (keys.length !== 3 ||
177
- keys[0] !== 'tables' ||
178
- keys[1] !== 'v' ||
179
- keys[2] !== 'version' ||
166
+ if (!hasExactKeys(record, ['tables', 'v', 'version']) ||
180
167
  record.v !== DESCRIPTOR_VERSION ||
181
168
  !isCount(record.version) ||
182
169
  !Array.isArray(record.tables)) {
@@ -258,15 +245,15 @@ function decodeRecord(value) {
258
245
  const record = parseJsonObject(value);
259
246
  if (record === undefined)
260
247
  return localCorrupt('previous-version context');
261
- const keys = Object.keys(record).sort();
262
- if (keys.length !== 7 ||
263
- keys[0] !== 'bytes' ||
264
- keys[1] !== 'createdAtMs' ||
265
- keys[2] !== 'currentVersion' ||
266
- keys[3] !== 'previousVersion' ||
267
- keys[4] !== 'rows' ||
268
- keys[5] !== 'tables' ||
269
- keys[6] !== 'v' ||
248
+ if (!hasExactKeys(record, [
249
+ 'bytes',
250
+ 'createdAtMs',
251
+ 'currentVersion',
252
+ 'previousVersion',
253
+ 'rows',
254
+ 'tables',
255
+ 'v',
256
+ ]) ||
270
257
  record.v !== 1 ||
271
258
  !isCount(record.bytes) ||
272
259
  !isCount(record.createdAtMs) ||
@@ -352,7 +339,7 @@ export function capturePreviousVersion(replica, container, oldDescriptor, newSch
352
339
  const selectColumns = table.columns
353
340
  .map((column) => quoteIdent(column.name))
354
341
  .join(', ');
355
- let lastRowId = -1;
342
+ let lastRowId = -(2 ** 63);
356
343
  for (;;) {
357
344
  const rows = replica.query(`SELECT rowid AS _rid,${selectColumns} FROM ${quoteIdent(table.name)} WHERE rowid>? ORDER BY rowid ASC LIMIT ?`, [lastRowId, COPY_BATCH_ROWS]);
358
345
  if (rows.length === 0)
@@ -557,23 +544,22 @@ export function storedPreviousVersionAudit(db) {
557
544
  }
558
545
  const incompatible = [];
559
546
  for (const entry of record.incompatible) {
560
- if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
547
+ if (!isRecord(entry)) {
561
548
  return undefined;
562
549
  }
563
- const item = entry;
564
- if (typeof item.commitId !== 'string' ||
565
- typeof item.table !== 'string' ||
566
- (item.reason !== 'unknown-table' &&
567
- item.reason !== 'unknown-column' &&
568
- item.reason !== 'missing-required-column') ||
569
- (item.column !== undefined && typeof item.column !== 'string')) {
550
+ if (typeof entry.commitId !== 'string' ||
551
+ typeof entry.table !== 'string' ||
552
+ (entry.reason !== 'unknown-table' &&
553
+ entry.reason !== 'unknown-column' &&
554
+ entry.reason !== 'missing-required-column') ||
555
+ (entry.column !== undefined && typeof entry.column !== 'string')) {
570
556
  return undefined;
571
557
  }
572
558
  incompatible.push({
573
- commitId: item.commitId,
574
- table: item.table,
575
- reason: item.reason,
576
- ...(typeof item.column === 'string' ? { column: item.column } : {}),
559
+ commitId: entry.commitId,
560
+ table: entry.table,
561
+ reason: entry.reason,
562
+ ...(typeof entry.column === 'string' ? { column: entry.column } : {}),
577
563
  });
578
564
  }
579
565
  return {
@@ -607,29 +593,28 @@ export function clearPreviousVersionAudit(db) {
607
593
  /** Strictly decode a Worker/native `previousVersionSnapshot` reply. */
608
594
  export function decodePreviousVersionSnapshot(value) {
609
595
  const method = 'previousVersionSnapshot';
610
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
596
+ if (!isRecord(value)) {
611
597
  return invalidHostResponse(method);
612
598
  }
613
- const source = value;
614
599
  const allowed = new Set([
615
600
  ...SNAPSHOT_REQUIRED_KEYS,
616
601
  ...SNAPSHOT_OPTIONAL_KEYS,
617
602
  ]);
618
- const keys = Object.keys(source);
603
+ const keys = Object.keys(value);
619
604
  if (!keys.every((key) => allowed.has(key)) ||
620
- SNAPSHOT_REQUIRED_KEYS.some((key) => !(key in source)) ||
621
- source.state !== 'previousVersion' ||
622
- typeof source.available !== 'boolean' ||
623
- !isCount(source.currentVersion) ||
624
- typeof source.truncated !== 'boolean' ||
625
- !Array.isArray(source.rows) ||
626
- !source.rows.every(isSqlRow)) {
605
+ SNAPSHOT_REQUIRED_KEYS.some((key) => !(key in value)) ||
606
+ value.state !== 'previousVersion' ||
607
+ typeof value.available !== 'boolean' ||
608
+ !isCount(value.currentVersion) ||
609
+ typeof value.truncated !== 'boolean' ||
610
+ !Array.isArray(value.rows) ||
611
+ !value.rows.every(isSqlRow)) {
627
612
  return invalidHostResponse(method);
628
613
  }
629
- const reason = source.reason;
630
- const previousVersion = source.previousVersion;
631
- const rows = source.rows;
632
- if (source.available) {
614
+ const reason = value.reason;
615
+ const previousVersion = value.previousVersion;
616
+ const rows = value.rows;
617
+ if (value.available) {
633
618
  // An available read names the previous version and never a refusal.
634
619
  if (!isCount(previousVersion) || reason !== undefined) {
635
620
  return invalidHostResponse(method);
@@ -638,9 +623,9 @@ export function decodePreviousVersionSnapshot(value) {
638
623
  state: 'previousVersion',
639
624
  available: true,
640
625
  previousVersion,
641
- currentVersion: source.currentVersion,
626
+ currentVersion: value.currentVersion,
642
627
  rows,
643
- truncated: source.truncated,
628
+ truncated: value.truncated,
644
629
  };
645
630
  }
646
631
  if (previousVersion !== undefined ||
@@ -651,10 +636,10 @@ export function decodePreviousVersionSnapshot(value) {
651
636
  return {
652
637
  state: 'previousVersion',
653
638
  available: false,
654
- currentVersion: source.currentVersion,
639
+ currentVersion: value.currentVersion,
655
640
  reason: reason,
656
641
  rows,
657
- truncated: source.truncated,
642
+ truncated: value.truncated,
658
643
  };
659
644
  }
660
645
  /**
@@ -665,73 +650,70 @@ export function decodePreviousVersionAuditResult(value) {
665
650
  const method = 'previousVersionAudit';
666
651
  if (value === undefined)
667
652
  return undefined;
668
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
653
+ if (!isRecord(value)) {
669
654
  return invalidHostResponse(method);
670
655
  }
671
- const source = value;
672
- const keys = Object.keys(source).sort();
656
+ const keys = Object.keys(value).sort();
673
657
  if (keys.length !== AUDIT_KEYS.length)
674
658
  return invalidHostResponse(method);
675
659
  if (keys.some((key, index) => key !== AUDIT_KEYS[index])) {
676
660
  return invalidHostResponse(method);
677
661
  }
678
- if (source.v !== AUDIT_VERSION ||
679
- !isCount(source.atMs) ||
680
- !isCount(source.fromVersion) ||
681
- !isCount(source.toVersion) ||
682
- !isCount(source.pending) ||
683
- !isCount(source.encodable) ||
684
- typeof source.truncated !== 'boolean' ||
685
- !Array.isArray(source.incompatible) ||
686
- source.incompatible.length > MAX_AUDIT_INCOMPATIBLE) {
662
+ if (value.v !== AUDIT_VERSION ||
663
+ !isCount(value.atMs) ||
664
+ !isCount(value.fromVersion) ||
665
+ !isCount(value.toVersion) ||
666
+ !isCount(value.pending) ||
667
+ !isCount(value.encodable) ||
668
+ typeof value.truncated !== 'boolean' ||
669
+ !Array.isArray(value.incompatible) ||
670
+ value.incompatible.length > MAX_AUDIT_INCOMPATIBLE) {
687
671
  return invalidHostResponse(method);
688
672
  }
689
673
  const incompatible = [];
690
- for (const entry of source.incompatible) {
691
- if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
674
+ for (const entry of value.incompatible) {
675
+ if (!isRecord(entry)) {
692
676
  return invalidHostResponse(method);
693
677
  }
694
- const item = entry;
695
- if (!Object.keys(item).every((key) => AUDIT_ENTRY_KEYS.includes(key)) ||
696
- typeof item.commitId !== 'string' ||
697
- typeof item.table !== 'string' ||
698
- (item.reason !== 'unknown-table' &&
699
- item.reason !== 'unknown-column' &&
700
- item.reason !== 'missing-required-column') ||
701
- (item.column !== undefined && typeof item.column !== 'string')) {
678
+ if (!Object.keys(entry).every((key) => AUDIT_ENTRY_KEYS.includes(key)) ||
679
+ typeof entry.commitId !== 'string' ||
680
+ typeof entry.table !== 'string' ||
681
+ (entry.reason !== 'unknown-table' &&
682
+ entry.reason !== 'unknown-column' &&
683
+ entry.reason !== 'missing-required-column') ||
684
+ (entry.column !== undefined && typeof entry.column !== 'string')) {
702
685
  return invalidHostResponse(method);
703
686
  }
704
687
  incompatible.push({
705
- commitId: item.commitId,
706
- table: item.table,
707
- reason: item.reason,
708
- ...(typeof item.column === 'string' ? { column: item.column } : {}),
688
+ commitId: entry.commitId,
689
+ table: entry.table,
690
+ reason: entry.reason,
691
+ ...(typeof entry.column === 'string' ? { column: entry.column } : {}),
709
692
  });
710
693
  }
711
694
  return {
712
695
  v: 1,
713
- atMs: source.atMs,
714
- fromVersion: source.fromVersion,
715
- toVersion: source.toVersion,
716
- pending: source.pending,
717
- encodable: source.encodable,
718
- truncated: source.truncated,
696
+ atMs: value.atMs,
697
+ fromVersion: value.fromVersion,
698
+ toVersion: value.toVersion,
699
+ pending: value.pending,
700
+ encodable: value.encodable,
701
+ truncated: value.truncated,
719
702
  incompatible,
720
703
  };
721
704
  }
722
705
  /** Strictly decode a Worker/native `previousVersionDiscard` reply. */
723
706
  export function decodePreviousVersionDiscardResult(value) {
724
707
  const method = 'previousVersionDiscard';
725
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
708
+ if (!isRecord(value)) {
726
709
  return invalidHostResponse(method);
727
710
  }
728
- const source = value;
729
- const keys = Object.keys(source).sort();
711
+ const keys = Object.keys(value).sort();
730
712
  if (keys.length !== DISCARD_KEYS.length ||
731
713
  keys.some((key, index) => key !== DISCARD_KEYS[index]) ||
732
- typeof source.present !== 'boolean' ||
733
- typeof source.discarded !== 'boolean') {
714
+ typeof value.present !== 'boolean' ||
715
+ typeof value.discarded !== 'boolean') {
734
716
  return invalidHostResponse(method);
735
717
  }
736
- return { present: source.present, discarded: source.discarded };
718
+ return { present: value.present, discarded: value.discarded };
737
719
  }