js-bao 0.12.0-alpha.13 → 0.12.0-alpha.14

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.
package/dist/browser.cjs CHANGED
@@ -2000,14 +2000,14 @@ function servableOperator(condition) {
2000
2000
  }
2001
2001
  return null;
2002
2002
  }
2003
- function analyze(model, node, indexes, isSetField) {
2003
+ function analyze(model, node, indexes, isSetField2) {
2004
2004
  const out = { served: false, servable: false, first: null };
2005
2005
  if (!isPlainObject(node)) return out;
2006
2006
  if ("id" in node && servableOperator(node.id) !== null) return { served: true, servable: false, first: null };
2007
2007
  for (const [key, value] of Object.entries(node)) {
2008
2008
  if (key === "$and" || key === "$or") {
2009
2009
  if (!Array.isArray(value) || value.length === 0) continue;
2010
- const branches = value.map((branch) => analyze(model, branch, indexes, isSetField));
2010
+ const branches = value.map((branch) => analyze(model, branch, indexes, isSetField2));
2011
2011
  out.served ||= key === "$and" ? branches.some((b) => b.served) : branches.every((b) => b.served);
2012
2012
  out.servable ||= branches.some((b) => b.servable);
2013
2013
  out.first ??= branches.find((b) => b.first)?.first ?? null;
@@ -2015,7 +2015,7 @@ function analyze(model, node, indexes, isSetField) {
2015
2015
  }
2016
2016
  if (key.startsWith("$") || key === "id" || key === "type") continue;
2017
2017
  const operator = servableOperator(value);
2018
- if (operator === null || isSetField(model, key)) continue;
2018
+ if (operator === null || isSetField2(model, key)) continue;
2019
2019
  out.servable = true;
2020
2020
  if (out.served) continue;
2021
2021
  if (indexes.leads(model, key)) out.served = true;
@@ -2024,14 +2024,14 @@ function analyze(model, node, indexes, isSetField) {
2024
2024
  if (out.served) out.first = null;
2025
2025
  return out;
2026
2026
  }
2027
- function sortSignal(model, sort, indexes, isSetField) {
2027
+ function sortSignal(model, sort, indexes, isSetField2) {
2028
2028
  if (!isPlainObject(sort)) return null;
2029
2029
  const entries = Object.entries(sort);
2030
2030
  while (entries.length > 0 && entries[entries.length - 1][0] === "id") entries.pop();
2031
2031
  if (entries.length === 0) return null;
2032
2032
  const fields = entries.map(([field2]) => field2);
2033
2033
  const directions = entries.map(([, direction]) => Number(direction) < 0 || direction === "desc" ? -1 : 1);
2034
- const named = (field2) => field2 !== "id" && field2 !== "type" && !isSetField(model, field2);
2034
+ const named = (field2) => field2 !== "id" && field2 !== "type" && !isSetField2(model, field2);
2035
2035
  if (!named(fields[0])) return null;
2036
2036
  const tuples = indexes.of(model);
2037
2037
  let covered = 0;
@@ -2046,13 +2046,13 @@ function sortSignal(model, sort, indexes, isSetField) {
2046
2046
  if (!named(field)) return null;
2047
2047
  return { model, field, reason: "sort", fields: fields.slice(0, covered + 1) };
2048
2048
  }
2049
- function signalFor(model, filter, sort, indexes, isSetField) {
2050
- const analysis = analyze(model, filter, indexes, isSetField);
2049
+ function signalFor(model, filter, sort, indexes, isSetField2) {
2050
+ const analysis = analyze(model, filter, indexes, isSetField2);
2051
2051
  if (analysis.served) return null;
2052
2052
  if (analysis.servable) {
2053
2053
  return analysis.first ? { model, field: analysis.first.field, reason: "filter", operator: analysis.first.operator } : null;
2054
2054
  }
2055
- return sortSignal(model, sort, indexes, isSetField);
2055
+ return sortSignal(model, sort, indexes, isSetField2);
2056
2056
  }
2057
2057
  function scanSignalsFor(model, filter, options, context) {
2058
2058
  const indexes = new Indexes(context);
@@ -3466,6 +3466,10 @@ var init_JsonQueryTranslator = __esm({
3466
3466
  get membershipFromData() {
3467
3467
  return this.options.stringSets === "json_each";
3468
3468
  }
3469
+ /** The whole row's `_data` as a select column: JSON text, whichever encoding the row is stored in. */
3470
+ get wholeData() {
3471
+ return this.options.jsonbData === true ? "json(_data) AS _data" : "_data";
3472
+ }
3469
3473
  /** Whether `$all`, `$size` and the substring operators read a set's array in `_data`. */
3470
3474
  get setArraysFromData() {
3471
3475
  return this.membershipFromData || this.options.setArraysInData === true;
@@ -3632,7 +3636,7 @@ var init_JsonQueryTranslator = __esm({
3632
3636
  `${foreignKeySql} IN (${parentValues.map(() => "?").join(", ")})`
3633
3637
  ];
3634
3638
  const sql = `
3635
- SELECT "_id", "_type", _data FROM (
3639
+ SELECT "_id", "_type", ${this.wholeData} FROM (
3636
3640
  SELECT "_id", "_type", _data,
3637
3641
  ROW_NUMBER() OVER (
3638
3642
  PARTITION BY ${foreignKeySql}
@@ -3668,7 +3672,7 @@ var init_JsonQueryTranslator = __esm({
3668
3672
  */
3669
3673
  aggregateSource(options = {}) {
3670
3674
  const table = this.table;
3671
- const isSetField = options.isSetField ?? (() => false);
3675
+ const isSetField2 = options.isSetField ?? (() => false);
3672
3676
  const baseConditions = this.options.baseConditions ?? [];
3673
3677
  const setAlias = (field, index) => {
3674
3678
  assertValidIdentifier(field, "aggregation groupBy field");
@@ -3680,7 +3684,8 @@ var init_JsonQueryTranslator = __esm({
3680
3684
  table,
3681
3685
  facetOperations: "all",
3682
3686
  facetSortsByMember: true,
3683
- isSetField,
3687
+ facetTiesByMember: this.options.facetTiesByMember === true,
3688
+ isSetField: isSetField2,
3684
3689
  fieldSql: (field) => qualified.getFieldSql(field),
3685
3690
  operationSql: (operation) => operation.type === "count" ? `COUNT(*) AS ${quoteIdentifier("count")}` : `${operation.type.toUpperCase()}(${qualified.getFieldSql(operation.field)}) AS ${quoteIdentifier(
3686
3691
  aggregationOperationKey(operation)
@@ -3696,11 +3701,29 @@ var init_JsonQueryTranslator = __esm({
3696
3701
  filterSql: (filter, reservedParams) => qualified.translateFilterWithinBound(filter ?? {}, reservedParams),
3697
3702
  membership: (level, index) => {
3698
3703
  const alias = setAlias(level.field, index);
3699
- if (this.membershipFromData) {
3704
+ const memberIndex = this.memberIndexOf(level.field);
3705
+ if (memberIndex !== null) {
3700
3706
  return {
3701
3707
  alias,
3702
- select: `CASE WHEN ${this.setMemberSql(level.field, "_set.value = ?")} THEN 'true' ELSE 'false' END`,
3708
+ select: `CASE WHEN ${this.memberIndexSql(memberIndex)} THEN 'true' ELSE 'false' END`,
3703
3709
  selectParams: [level.contains],
3710
+ // The level is judged against the bound as its `_data` statement
3711
+ // binds it, its field and its member, though the probe binds the
3712
+ // member alone (#5150, #5146).
3713
+ reservedParams: 1,
3714
+ group: quoteIdentifier(alias),
3715
+ join: "",
3716
+ joinParams: []
3717
+ };
3718
+ }
3719
+ if (this.membershipFromData) {
3720
+ return {
3721
+ alias,
3722
+ select: `CASE WHEN ${this.setMemberSql(level.field, "_set.value = ?", true)} THEN 'true' ELSE 'false' END`,
3723
+ // The level binds its field and its member, as the member table's
3724
+ // join does, so a filter is refused past the bound where it is on
3725
+ // every source (#5146).
3726
+ selectParams: [this.dataPath(level.field), level.contains],
3704
3727
  // The presence binds its member, so the level groups by its alias
3705
3728
  // rather than repeating the expression and its bind.
3706
3729
  group: quoteIdentifier(alias),
@@ -3718,14 +3741,26 @@ var init_JsonQueryTranslator = __esm({
3718
3741
  joinParams: [level.field, level.contains]
3719
3742
  };
3720
3743
  },
3721
- facet: (field) => {
3744
+ facet: (field, facetOptions) => {
3745
+ const memberIndex = this.memberIndexOf(field);
3746
+ if (memberIndex !== null && !facetOptions?.filtered) {
3747
+ return {
3748
+ from: facetOptions?.readsRecords ? `${quoteIdentifier(memberIndex)} AS _facet JOIN ${table} ON ${table}.rowid = _facet.rid` : `${quoteIdentifier(memberIndex)} AS _facet`,
3749
+ value: "_facet.value",
3750
+ conditions: [],
3751
+ params: []
3752
+ };
3753
+ }
3722
3754
  if (this.membershipFromData) {
3723
- const path = this.dataPathSql(field);
3724
3755
  return {
3725
- from: `${table}, json_each(${path}) AS _facet`,
3756
+ from: `${table}, json_each(${table}._data, ?) AS _facet`,
3726
3757
  value: "_facet.value",
3727
- conditions: [`${table}.${quoteIdentifier("_type")} = ?`, `json_type(${path}) = 'array'`, ...baseConditions],
3728
- params: [this.modelName]
3758
+ conditions: [
3759
+ `${table}.${quoteIdentifier("_type")} = ?`,
3760
+ `json_type(${this.dataPathSql(field)}) = 'array'`,
3761
+ ...baseConditions
3762
+ ],
3763
+ params: [this.dataPath(field), this.modelName]
3729
3764
  };
3730
3765
  }
3731
3766
  return {
@@ -4008,16 +4043,35 @@ var init_JsonQueryTranslator = __esm({
4008
4043
  * A membership condition over the array a record holds in `fieldName`
4009
4044
  * (`stringSets: "json_each"`): true only where the stored value is an
4010
4045
  * array, and then when `members` (a condition over the `json_each` rows of
4011
- * its members, aliased `_set`) holds for one of them.
4046
+ * its members, aliased `_set`) holds for one of them. With `bindPath`, the
4047
+ * `json_each` takes the field's path as its first parameter, before any
4048
+ * `members` binds.
4012
4049
  */
4013
- setMemberSql(fieldName, members) {
4050
+ setMemberSql(fieldName, members, bindPath = false) {
4014
4051
  const path = this.dataPathSql(fieldName);
4015
- return `(json_type(${path}) = 'array' AND EXISTS (SELECT 1 FROM json_each(${path}) AS _set WHERE ${members}))`;
4052
+ const each = bindPath ? `${this.table}._data, ?` : path;
4053
+ return `(json_type(${path}) = 'array' AND EXISTS (SELECT 1 FROM json_each(${each}) AS _set WHERE ${members}))`;
4054
+ }
4055
+ /** The member index `fieldName`'s members are read from, or `null` (#5150). */
4056
+ memberIndexOf(fieldName) {
4057
+ if (SYSTEM_FIELDS2.has(fieldName)) return null;
4058
+ return this.options.memberIndexTable?.(fieldName) ?? null;
4059
+ }
4060
+ /**
4061
+ * A record holds `?` in the set `table` indexes: a rowid probe of the
4062
+ * member index (#5150), driven by the member, never a correlated `EXISTS`.
4063
+ */
4064
+ memberIndexSql(table) {
4065
+ return `${this.table}.rowid IN (SELECT rid FROM ${quoteIdentifier(table)} WHERE value = ?)`;
4016
4066
  }
4017
4067
  /** `<table>._data, '$.<field>'`: the arguments that address a field's stored JSON. */
4018
4068
  dataPathSql(fieldName) {
4069
+ return `${this.table}._data, '${this.dataPath(fieldName)}'`;
4070
+ }
4071
+ /** `$.<field>`: the JSON path of a field in `_data`. */
4072
+ dataPath(fieldName) {
4019
4073
  assertValidIdentifier(fieldName, "query field");
4020
- return `${this.table}._data, '$.${fieldName}'`;
4074
+ return `$.${fieldName}`;
4021
4075
  }
4022
4076
  /**
4023
4077
  * Translate field condition to SQL
@@ -4113,7 +4167,7 @@ var init_JsonQueryTranslator = __esm({
4113
4167
  } catch {
4114
4168
  }
4115
4169
  }
4116
- if (this.setArraysFromData) {
4170
+ if (this.setArraysFromData && !SYSTEM_FIELDS2.has(fieldName)) {
4117
4171
  const like = `LIKE ? ESCAPE '\\' COLLATE NOCASE`;
4118
4172
  conditions.push(
4119
4173
  `((json_type(${this.dataPathSql(fieldName)}) <> 'array' AND ${fieldSql} ${like}) OR ${this.setMemberSql(fieldName, `_set.value ${like}`)})`
@@ -4298,6 +4352,10 @@ var init_JsonQueryTranslator = __esm({
4298
4352
  fieldType
4299
4353
  );
4300
4354
  }
4355
+ {
4356
+ const table = this.memberIndexOf(fieldName);
4357
+ if (table !== null) return { sql: this.memberIndexSql(table), params: [value] };
4358
+ }
4301
4359
  if (this.membershipFromData) {
4302
4360
  return { sql: this.setMemberSql(fieldName, "_set.value = ?"), params: [value] };
4303
4361
  }
@@ -4380,7 +4438,7 @@ var init_JsonQueryTranslator = __esm({
4380
4438
  */
4381
4439
  buildSelectClause(projection, aliasedSortFields) {
4382
4440
  if (!projection || Object.keys(projection).length === 0) {
4383
- return "_id, _type, _data";
4441
+ return `_id, _type, ${this.wholeData}`;
4384
4442
  }
4385
4443
  const includeFields = [];
4386
4444
  const excludeFields = [];
@@ -4421,9 +4479,9 @@ var init_JsonQueryTranslator = __esm({
4421
4479
  }
4422
4480
  return selectParts.join(", ");
4423
4481
  } else if (hasExcludes) {
4424
- return "_id, _type, _data";
4482
+ return `_id, _type, ${this.wholeData}`;
4425
4483
  }
4426
- return "_id, _type, _data";
4484
+ return `_id, _type, ${this.wholeData}`;
4427
4485
  }
4428
4486
  /**
4429
4487
  * Build LIMIT clause
@@ -5348,6 +5406,24 @@ var init_resolve = __esm({
5348
5406
  });
5349
5407
 
5350
5408
  // src/record-log/results.ts
5409
+ function sameValue(a, b) {
5410
+ if (a === b) return true;
5411
+ if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
5412
+ return JSON.stringify(a) === JSON.stringify(b);
5413
+ }
5414
+ function changeBetween(key, before, after) {
5415
+ const { model, id } = key;
5416
+ if (!after) return before ? { model, id, gone: true } : null;
5417
+ if (!before) return { model, id, row: after };
5418
+ const set = {};
5419
+ for (const [field, v] of Object.entries(after)) {
5420
+ if (field !== "id" && (!(field in before) || !sameValue(before[field], v))) set[field] = v;
5421
+ }
5422
+ const unset = Object.keys(before).filter((field) => !(field in after));
5423
+ const hasSet = Object.keys(set).length > 0;
5424
+ if (!hasSet && !unset.length) return null;
5425
+ return { model, id, ...hasSet ? { set } : {}, ...unset.length ? { unset } : {} };
5426
+ }
5351
5427
  function plainRowAfter(row, m) {
5352
5428
  if (m.kind === "delete") return null;
5353
5429
  const prior = m.kind === "create" ? { id: m.id } : row;
@@ -5581,11 +5657,12 @@ function checkOptions(options) {
5581
5657
  throw new AggregateOptionsError("options.limit must be a positive integer");
5582
5658
  }
5583
5659
  }
5584
- function orderAndLimit(options, sortSql) {
5660
+ function orderAndLimit(options, sortSql, tieBreak = null) {
5585
5661
  let sql = "";
5586
5662
  if (options.sort) {
5587
5663
  const direction = options.sort.direction === 1 ? "ASC" : "DESC";
5588
5664
  sql += ` ORDER BY ${sortSql(options.sort.field)} ${direction}`;
5665
+ if (tieBreak !== null) sql += `, ${tieBreak} ASC`;
5589
5666
  }
5590
5667
  if (options.limit) {
5591
5668
  sql += ` LIMIT ${Number(options.limit)}`;
@@ -5634,9 +5711,10 @@ function buildAggregate(source, options) {
5634
5711
  const joinParams = joined.flatMap((entry) => entry.joinParams);
5635
5712
  const base = source.baseConditions();
5636
5713
  const scope = source.documentConditions(options.documents);
5714
+ const reserved = joined.reduce((n, entry) => n + (entry.reservedParams ?? 0), 0);
5637
5715
  const translated = source.filterSql(
5638
5716
  filter,
5639
- selectParams.length + joinParams.length + base.params.length + scope.params.length
5717
+ selectParams.length + joinParams.length + reserved + base.params.length + scope.params.length
5640
5718
  );
5641
5719
  const conditions = [...base.sql, ...translated.sql ? [translated.sql] : [], ...scope.sql];
5642
5720
  const group = [...plainSql, ...periodSql, ...joined.map((entry) => entry.group)];
@@ -5669,7 +5747,10 @@ function buildAggregate(source, options) {
5669
5747
  }
5670
5748
  function facetPlan(source, options, field, filter) {
5671
5749
  const { groupBy, operations } = options;
5672
- const facet = source.facet(field);
5750
+ const facet = source.facet(field, {
5751
+ filtered: Object.keys(filter).length > 0,
5752
+ readsRecords: source.facetOperations === "all" && operations.some((operation) => operation.type !== "count")
5753
+ });
5673
5754
  const selected = source.facetOperations === "all" ? operations.map((operation) => source.operationSql(operation, true)) : [source.operationSql({ type: "count" }, true)];
5674
5755
  const scope = source.documentConditions(options.documents);
5675
5756
  const translated = source.filterSql(filter, facet.params.length + scope.params.length);
@@ -5677,6 +5758,8 @@ function facetPlan(source, options, field, filter) {
5677
5758
  let sql = `SELECT ${facet.value} AS ${quoteIdentifier("group_key")}, ${selected.join(", ")} FROM ${facet.from}`;
5678
5759
  sql += where(conditions);
5679
5760
  sql += ` GROUP BY ${facet.value}`;
5761
+ const sortsByMember = options.sort?.field === field && source.facetSortsByMember;
5762
+ const tieBreak = source.facetTiesByMember && !sortsByMember ? facet.value : null;
5680
5763
  sql += orderAndLimit(options, (sortField) => {
5681
5764
  if (sortField === "count") return "COUNT(*)";
5682
5765
  if (operations.some((operation) => aggregationOperationKey(operation) === sortField)) {
@@ -5684,7 +5767,7 @@ function facetPlan(source, options, field, filter) {
5684
5767
  }
5685
5768
  if (sortField === field && source.facetSortsByMember) return facet.value;
5686
5769
  return quoteIdentifier(sortField);
5687
- });
5770
+ }, tieBreak);
5688
5771
  const layout = { facetField: field, plainFields: [], periodLevels: [], memberships: [] };
5689
5772
  return {
5690
5773
  sql,
@@ -7019,6 +7102,13 @@ function stagedForRead(ormContext, store, model, id) {
7019
7102
  const group = activeRecordLogTransactions.get(ormContext) ?? (unbound && unbound.owner === ormContext ? unbound : null);
7020
7103
  return group?.staged(store, model, id);
7021
7104
  }
7105
+ function refusalRecords(error) {
7106
+ const { conflicting, current } = error.details ?? {};
7107
+ return {
7108
+ ...conflicting ? { conflictingRecord: { model: conflicting.model, id: conflicting.id } } : {},
7109
+ ...current ? { current } : {}
7110
+ };
7111
+ }
7022
7112
  function declaredTypeOf(store) {
7023
7113
  const models = store.declaredTypes();
7024
7114
  const name = store.marks().db3Type?.name;
@@ -7171,6 +7261,7 @@ var init_BaseModel = __esm({
7171
7261
  model: mutations[0].model,
7172
7262
  recordId: mutations[0].id,
7173
7263
  error,
7264
+ ...refusalRecords(error),
7174
7265
  writes: mutations.map((m) => ({
7175
7266
  model: m.model,
7176
7267
  recordId: m.id,
@@ -9882,7 +9973,8 @@ var init_BaseModel = __esm({
9882
9973
  for (const [field, value] of Object.entries(dataToSave)) {
9883
9974
  if (value !== void 0) postMutation[field] = value;
9884
9975
  }
9885
- for (const constraint of schema.resolvedUniqueConstraints) {
9976
+ const selfJudged = store.marks().localOnly === true;
9977
+ for (const constraint of selfJudged ? [] : schema.resolvedUniqueConstraints) {
9886
9978
  if (!store.constraintInForce(constraint.name)) continue;
9887
9979
  const values = constraint.fields.map((field) => postMutation[field]);
9888
9980
  if (values.some((value) => value === void 0 || value === null)) continue;
@@ -9937,6 +10029,7 @@ var init_BaseModel = __esm({
9937
10029
  model: modelName,
9938
10030
  recordId: this.id,
9939
10031
  error,
10032
+ ...refusalRecords(error),
9940
10033
  writes: [
9941
10034
  {
9942
10035
  model: modelName,
@@ -9994,6 +10087,7 @@ var init_BaseModel = __esm({
9994
10087
  model: modelName,
9995
10088
  recordId: this.id,
9996
10089
  error,
10090
+ ...refusalRecords(error),
9997
10091
  writes: [{ model: modelName, recordId: this.id, kind: "delete", seq: 0 }]
9998
10092
  });
9999
10093
  }
@@ -10086,7 +10180,7 @@ var init_BaseModel = __esm({
10086
10180
  if (result && "entry" in result) seq = result.entry.seq;
10087
10181
  } catch (error) {
10088
10182
  if (error instanceof RecordLogWriteRefusedError) {
10089
- report({ documentId: docId, model: modelName, recordId: id, error, writes: [write] });
10183
+ report({ documentId: docId, model: modelName, recordId: id, error, ...refusalRecords(error), writes: [write] });
10090
10184
  }
10091
10185
  throw error;
10092
10186
  }
@@ -11894,6 +11988,7 @@ __export(browser_exports, {
11894
11988
  RecordLogClient: () => RecordLogClient,
11895
11989
  RecordLogDocumentBinding: () => RecordLogDocumentBinding,
11896
11990
  RecordLogDocumentSession: () => RecordLogDocumentSession,
11991
+ RecordLogLocalIndexError: () => RecordLogLocalIndexError,
11897
11992
  RecordLogRecords: () => RecordLogRecords,
11898
11993
  RecordLogSender: () => RecordLogSender,
11899
11994
  RecordLogSessions: () => RecordLogSessions,
@@ -11963,6 +12058,8 @@ __export(browser_exports, {
11963
12058
  isRecordLogStoreResponse: () => isRecordLogStoreResponse,
11964
12059
  lineBytes: () => lineBytes,
11965
12060
  loadSchemaFromTomlString: () => loadSchemaFromTomlString,
12061
+ localConstraints: () => localConstraints,
12062
+ localIndexList: () => localIndexList,
11966
12063
  omitStringsetConstraints: () => omitStringsetConstraints,
11967
12064
  parseSnapshotChunkPath: () => parseSnapshotChunkPath,
11968
12065
  planRecordLogDelete: () => planRecordLogDelete,
@@ -12584,7 +12681,8 @@ async function guardedLoadSqlJs(locateFile) {
12584
12681
  });
12585
12682
  try {
12586
12683
  const initPromise = (0, import_sql10.default)({
12587
- locateFile,
12684
+ // Whatever the build calls its wasm, it is the `sql-wasm.wasm` resolved above.
12685
+ locateFile: (file) => file.endsWith(".wasm") ? wasmPath : locateFile(file),
12588
12686
  // Layer 1: emscripten onAbort.
12589
12687
  onAbort: (reason) => abortReject?.(
12590
12688
  isLinkError(reason) ? recordMismatch(reason) : toError(reason)
@@ -13630,6 +13728,9 @@ function dispatchRecordLogStoreCommand(store, command) {
13630
13728
  case "findIdByFields":
13631
13729
  value = store.findIdByFields(c.model, c.fields, c.values);
13632
13730
  break;
13731
+ case "duplicateKeys":
13732
+ value = store.duplicateKeys(c.model, c.fields, c.limit);
13733
+ break;
13633
13734
  case "queryView":
13634
13735
  value = store.queryView(c.model, c.filter, c.options);
13635
13736
  break;
@@ -13687,6 +13788,9 @@ function dispatchRecordLogStoreCommand(store, command) {
13687
13788
  case "setState":
13688
13789
  value = store.setState(c);
13689
13790
  break;
13791
+ case "changeLocalIndexes":
13792
+ value = store.changeLocalIndexes(c);
13793
+ break;
13690
13794
  default: {
13691
13795
  const unknown = c;
13692
13796
  throw new Error(`Unknown record-log store command ${JSON.stringify(unknown?.kind)}`);
@@ -13716,15 +13820,54 @@ function changedModelsOf(reply) {
13716
13820
 
13717
13821
  // src/record-log-client/store.ts
13718
13822
  var import_ulid3 = require("ulid");
13719
- init_types2();
13823
+
13824
+ // src/record-log/constraints.ts
13825
+ function constraintKey(row, fields) {
13826
+ const values = fields.map((field) => row[field]);
13827
+ return values.some((v) => v === void 0 || v === null) ? null : values;
13828
+ }
13829
+ function checkConstraints(trial, touched, constraints) {
13830
+ const rows = touched.map((key) => ({ key, row: trial.row(key) }));
13831
+ for (const constraint of constraints) {
13832
+ const mine = rows.filter(
13833
+ (x) => x.row !== null && x.key.model === constraint.model
13834
+ );
13835
+ if (!mine.length) continue;
13836
+ const ids = rows.filter((x) => x.key.model === constraint.model).map((x) => x.key.id);
13837
+ const held = /* @__PURE__ */ new Map();
13838
+ for (const { key, row } of mine) {
13839
+ const values = constraintKey(row, constraint.fields);
13840
+ if (values === null) continue;
13841
+ const text = JSON.stringify(values);
13842
+ const other = held.get(text);
13843
+ if (other) return { constraint, key: values, record: key, conflicting: other };
13844
+ held.set(text, key);
13845
+ const holder = trial.holder(constraint.model, constraint.fields, values, ids);
13846
+ if (holder !== null) {
13847
+ return {
13848
+ constraint,
13849
+ key: values,
13850
+ record: key,
13851
+ conflicting: { model: constraint.model, id: holder }
13852
+ };
13853
+ }
13854
+ }
13855
+ }
13856
+ return null;
13857
+ }
13858
+
13859
+ // src/record-log-client/store.ts
13860
+ init_resolve();
13861
+ init_results();
13720
13862
 
13721
13863
  // src/utils/fieldLookupSql.ts
13722
13864
  init_sql();
13865
+ var ID_PREDICATE = "_id IS ?";
13723
13866
  function fieldLookupPredicates(modelName, fields) {
13724
13867
  const literal2 = isValidIdentifier(modelName) && fields.every((f) => isValidIdentifier(f));
13725
13868
  if (literal2) {
13726
13869
  const predicates2 = fields.map(
13727
- (field) => `json_extract(_data, '$.${field}') IS ?`
13870
+ (field) => field === "id" ? ID_PREDICATE : `json_extract(_data, '$.${field}') IS ?`
13728
13871
  );
13729
13872
  return {
13730
13873
  where: [`_type = ${quoteStringLiteral(modelName)}`, ...predicates2].join(
@@ -13734,7 +13877,9 @@ function fieldLookupPredicates(modelName, fields) {
13734
13877
  bindPaths: false
13735
13878
  };
13736
13879
  }
13737
- const predicates = fields.map(() => `json_extract(_data, '$.' || ?) IS ?`);
13880
+ const predicates = fields.map(
13881
+ (field) => field === "id" ? ID_PREDICATE : `json_extract(_data, '$.' || ?) IS ?`
13882
+ );
13738
13883
  return {
13739
13884
  where: ["_type = ?", ...predicates].join(" AND "),
13740
13885
  bindType: true,
@@ -13744,12 +13889,60 @@ function fieldLookupPredicates(modelName, fields) {
13744
13889
  function fieldLookupBindings(predicates, modelName, fields, values) {
13745
13890
  const bindings = predicates.bindType ? [modelName] : [];
13746
13891
  for (let i = 0; i < fields.length; i++) {
13747
- if (predicates.bindPaths) bindings.push(fields[i]);
13892
+ if (predicates.bindPaths && fields[i] !== "id") bindings.push(fields[i]);
13748
13893
  bindings.push(values[i]);
13749
13894
  }
13750
13895
  return bindings;
13751
13896
  }
13752
13897
 
13898
+ // src/record-log/sql.ts
13899
+ init_resolve();
13900
+ init_results();
13901
+
13902
+ // src/record-log/state.ts
13903
+ init_stringSetOrder();
13904
+ init_types2();
13905
+
13906
+ // src/schema/JsonSchemaDDL.ts
13907
+ init_sql();
13908
+ init_sql();
13909
+ var DURABLE_OBJECT_SCHEMA_OPTIONS = Object.freeze({ includeDocIdColumn: false, memberShape: "keyed" });
13910
+
13911
+ // src/record-log/schema.ts
13912
+ var META_KEYS = Object.freeze({
13913
+ /** The log number the next accepted entry gets. */
13914
+ nextLsn: "next_lsn",
13915
+ /** The current epoch. */
13916
+ currentEpoch: "epoch_current",
13917
+ /** The epoch open ahead of the current one. */
13918
+ nextEpoch: "epoch_next",
13919
+ /** Epochs at or below this are frozen. */
13920
+ epochFloor: "epoch_floor",
13921
+ /** Entries whose writer had not applied the log up to this are refused. */
13922
+ cursorFloor: "cursor_floor",
13923
+ /** The bulk load in progress, as JSON, when there is one. */
13924
+ loadInProgress: "load_in_progress"
13925
+ });
13926
+
13927
+ // src/record-log/stamps.ts
13928
+ init_types2();
13929
+ init_stringSetOrder();
13930
+
13931
+ // src/record-log/sql.ts
13932
+ init_types2();
13933
+ function jsonData(column = "_data") {
13934
+ return `json(${column}) AS _data`;
13935
+ }
13936
+ function rowWithId(id, row) {
13937
+ if (Object.prototype.hasOwnProperty.call(row, "id")) return row;
13938
+ return { id, ...row };
13939
+ }
13940
+ var SELECT_ROW = `SELECT ${jsonData()}, _stamps, _dead, _lsn FROM records WHERE _type = ? AND _id = ?`;
13941
+
13942
+ // src/record-log-client/store.ts
13943
+ init_types2();
13944
+ init_condition();
13945
+
13753
13946
  // src/record-log-client/viewReader.ts
13754
13947
  init_aggregateBuilder();
13755
13948
  init_CursorManager();
@@ -14117,6 +14310,7 @@ function db3ViewTranslator(model, options = {}) {
14117
14310
  table: "record_log_view",
14118
14311
  documentColumn: DOCUMENT_COLUMN,
14119
14312
  stringSets: "json_each",
14313
+ jsonbData: true,
14120
14314
  ...options.document !== void 0 ? { baseConditions: [`${DOCUMENT_COLUMN} = ${sqlText2(options.document)}`] } : {},
14121
14315
  ...options.tieBreak ? { tieBreakFields: [DOCUMENT_COLUMN] } : {}
14122
14316
  });
@@ -14194,7 +14388,7 @@ function readViewPage(sql, model, filter, options, limits = {}) {
14194
14388
  row = stripCursorSortValues(parsed, aliased);
14195
14389
  if (excluding) row = applyIncludeProjection(row, selected);
14196
14390
  } else {
14197
- row = JSON.parse(String(columns._data));
14391
+ row = rowWithId(String(columns._id), JSON.parse(String(columns._data)));
14198
14392
  mint = row;
14199
14393
  }
14200
14394
  row = canonicalSets(row, setFields);
@@ -14357,6 +14551,7 @@ function syncRecordLogIndexes(sql, docId, indexes) {
14357
14551
  if (indexes) {
14358
14552
  sql.exec(`DELETE FROM record_log_indexes WHERE doc_id = ?`, docId);
14359
14553
  for (const entry of indexes) {
14554
+ if (entry.members === true) continue;
14360
14555
  const refusal = usable(entry);
14361
14556
  if (refusal) {
14362
14557
  Logger.warn(`[record-log] ${docId}: index '${entry.name}' skipped: ${refusal}; queries on it scan.`);
@@ -15265,103 +15460,6 @@ init_guess();
15265
15460
 
15266
15461
  // src/record-log-client/maintenance.ts
15267
15462
  init_logger();
15268
- function storedDocuments(sql) {
15269
- const documents = /* @__PURE__ */ new Set();
15270
- try {
15271
- for (const row of sql.exec(
15272
- `SELECT doc_id FROM record_log_state UNION SELECT doc_id FROM record_log_pending`
15273
- )) {
15274
- documents.add(String(row.doc_id));
15275
- }
15276
- } catch {
15277
- }
15278
- return Array.from(documents);
15279
- }
15280
- function purgeDocumentQueryRows(sql, docId) {
15281
- const tables = Array.from(
15282
- sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'")
15283
- ).map((row) => String(row.name));
15284
- const columnsOf = /* @__PURE__ */ new Map();
15285
- for (const table of tables) {
15286
- let columns = [];
15287
- try {
15288
- columns = Array.from(sql.exec(`PRAGMA table_info(${quote(table)})`)).map((row) => String(row.name));
15289
- } catch {
15290
- }
15291
- columnsOf.set(table, columns);
15292
- }
15293
- const derived = tables.filter((table) => columnsOf.get(table).includes("_meta_doc_id"));
15294
- for (const parent of derived) {
15295
- for (const junction of legacyJunctionsOf(parent, tables, columnsOf)) {
15296
- sql.exec(
15297
- `DELETE FROM ${quote(junction.table)} WHERE ${quote(junction.foreignKey)} IN (SELECT "id" FROM ${quote(parent)} WHERE "_meta_doc_id" = ?)`,
15298
- docId
15299
- );
15300
- sql.exec(
15301
- `DELETE FROM ${quote(junction.table)} WHERE ${quote(junction.foreignKey)} NOT IN (SELECT "id" FROM ${quote(parent)})`
15302
- );
15303
- }
15304
- }
15305
- for (const parent of derived) {
15306
- sql.exec(`DELETE FROM ${quote(parent)} WHERE "_meta_doc_id" = ?`, docId);
15307
- }
15308
- }
15309
- var RECORD_LOG_STORAGE_VERSION = 2;
15310
- function migrateRecordLogStore(sql, options) {
15311
- let current = 1;
15312
- try {
15313
- const [row] = Array.from(sql.exec(`SELECT value FROM record_log_meta WHERE key = 'storage_version'`));
15314
- if (row) current = Number(row.value);
15315
- } catch {
15316
- }
15317
- if (current >= RECORD_LOG_STORAGE_VERSION) return { migrated: false };
15318
- sql.transaction(() => {
15319
- for (const docId of storedDocuments(sql)) purgeDocumentQueryRows(sql, docId);
15320
- if (options.db3Only) dropDocumentQueryTables(sql);
15321
- sql.exec(`DROP TABLE IF EXISTS record_log_projection`);
15322
- for (const row of Array.from(
15323
- sql.exec(
15324
- `SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'record_log_view' AND (name LIKE 'idx\\_record\\_log\\_view\\_f%' ESCAPE '\\' OR name LIKE 'idx\\_record\\_log\\_view\\_u%' ESCAPE '\\')`
15325
- )
15326
- )) {
15327
- sql.exec(`DROP INDEX IF EXISTS ${quote(String(row.name))}`);
15328
- }
15329
- sql.exec(`CREATE TABLE IF NOT EXISTS record_log_meta (key TEXT PRIMARY KEY, value TEXT)`);
15330
- sql.exec(
15331
- `INSERT INTO record_log_meta (key, value) VALUES ('storage_version', ?)
15332
- ON CONFLICT (key) DO UPDATE SET value = excluded.value`,
15333
- String(RECORD_LOG_STORAGE_VERSION)
15334
- );
15335
- });
15336
- Logger.info(`[record-log] the local store was migrated to storage version ${RECORD_LOG_STORAGE_VERSION} (db3 query tables ${options.db3Only ? "dropped" : "emptied of db3 rows"}).`);
15337
- return { migrated: true };
15338
- }
15339
- function dropDocumentQueryTables(sql) {
15340
- const tables = Array.from(sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'")).map((row) => String(row.name));
15341
- const columnsOf = /* @__PURE__ */ new Map();
15342
- for (const table of tables) {
15343
- let columns = [];
15344
- try {
15345
- columns = Array.from(sql.exec(`PRAGMA table_info(${quote(table)})`)).map((row) => String(row.name));
15346
- } catch {
15347
- }
15348
- columnsOf.set(table, columns);
15349
- }
15350
- const derived = tables.filter((table) => columnsOf.get(table).includes("_meta_doc_id"));
15351
- const junctions = derived.flatMap((parent) => legacyJunctionsOf(parent, tables, columnsOf).map((j) => j.table));
15352
- for (const table of /* @__PURE__ */ new Set([...junctions, ...derived])) sql.exec(`DROP TABLE IF EXISTS ${quote(table)}`);
15353
- }
15354
- function legacyJunctionsOf(parent, tables, columnsOf) {
15355
- const model = parent.startsWith("model_") ? parent.slice("model_".length) : parent;
15356
- const foreignKey = `${model}_id`;
15357
- return tables.filter((table) => table.startsWith(`${parent}_`)).filter((table) => {
15358
- const columns = columnsOf.get(table) ?? [];
15359
- return columns.includes("value") && !columns.includes("_meta_doc_id") && columns.includes(foreignKey);
15360
- }).map((table) => ({ table, foreignKey }));
15361
- }
15362
- function quote(identifier) {
15363
- return `"${identifier.replace(/"/g, '""')}"`;
15364
- }
15365
15463
 
15366
15464
  // src/record-log-client/schema.ts
15367
15465
  var RECORD_LOG_CLIENT_TABLES = Object.freeze([
@@ -15410,7 +15508,9 @@ function recordLogClientDDL() {
15410
15508
  segment TEXT,
15411
15509
  staged INTEGER,
15412
15510
  typed TEXT,
15413
- db3_type TEXT
15511
+ db3_type TEXT,
15512
+ local_only INTEGER NOT NULL DEFAULT 0,
15513
+ local_indexes TEXT
15414
15514
  )`,
15415
15515
  `CREATE TABLE IF NOT EXISTS record_log_writers (
15416
15516
  doc_id TEXT NOT NULL,
@@ -15501,20 +15601,188 @@ function recordLogClientDDL() {
15501
15601
  )`
15502
15602
  ];
15503
15603
  }
15604
+ var RECORD_LOG_LOCAL_ONLY_COLUMNS = Object.freeze([
15605
+ {
15606
+ table: "record_log_state",
15607
+ column: "local_only",
15608
+ add: `ALTER TABLE record_log_state ADD COLUMN local_only INTEGER NOT NULL DEFAULT 0`
15609
+ },
15610
+ { table: "record_log_state", column: "local_indexes", add: `ALTER TABLE record_log_state ADD COLUMN local_indexes TEXT` }
15611
+ ]);
15504
15612
  var RECORD_LOG_CLIENT_ADDED_COLUMNS = Object.freeze([
15505
15613
  { table: "record_log_state", column: "receipt", add: `ALTER TABLE record_log_state ADD COLUMN receipt TEXT` },
15506
15614
  { table: "record_log_state", column: "segment", add: `ALTER TABLE record_log_state ADD COLUMN segment TEXT` },
15507
15615
  { table: "record_log_state", column: "staged", add: `ALTER TABLE record_log_state ADD COLUMN staged INTEGER` },
15508
15616
  { table: "record_log_state", column: "typed", add: `ALTER TABLE record_log_state ADD COLUMN typed TEXT` },
15509
- { table: "record_log_state", column: "db3_type", add: `ALTER TABLE record_log_state ADD COLUMN db3_type TEXT` }
15617
+ { table: "record_log_state", column: "db3_type", add: `ALTER TABLE record_log_state ADD COLUMN db3_type TEXT` },
15618
+ ...RECORD_LOG_LOCAL_ONLY_COLUMNS
15510
15619
  ]);
15511
15620
  function recordLogFieldIndexName(kind, model, name, table = "view") {
15512
15621
  const tag = kind === "field" ? "f" : "u";
15513
15622
  return `idx_record_log_${table}_${tag}${model.length}_${model.toLowerCase()}_${name.toLowerCase()}`;
15514
15623
  }
15515
15624
 
15625
+ // src/record-log-client/maintenance.ts
15626
+ function storedDocuments(sql) {
15627
+ const documents = /* @__PURE__ */ new Set();
15628
+ try {
15629
+ for (const row of sql.exec(
15630
+ `SELECT doc_id FROM record_log_state UNION SELECT doc_id FROM record_log_pending`
15631
+ )) {
15632
+ documents.add(String(row.doc_id));
15633
+ }
15634
+ } catch {
15635
+ }
15636
+ return Array.from(documents);
15637
+ }
15638
+ function purgeDocumentQueryRows(sql, docId) {
15639
+ const tables = Array.from(
15640
+ sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'")
15641
+ ).map((row) => String(row.name));
15642
+ const columnsOf = /* @__PURE__ */ new Map();
15643
+ for (const table of tables) {
15644
+ let columns = [];
15645
+ try {
15646
+ columns = Array.from(sql.exec(`PRAGMA table_info(${quote(table)})`)).map((row) => String(row.name));
15647
+ } catch {
15648
+ }
15649
+ columnsOf.set(table, columns);
15650
+ }
15651
+ const derived = tables.filter((table) => columnsOf.get(table).includes("_meta_doc_id"));
15652
+ for (const parent of derived) {
15653
+ for (const junction of legacyJunctionsOf(parent, tables, columnsOf)) {
15654
+ sql.exec(
15655
+ `DELETE FROM ${quote(junction.table)} WHERE ${quote(junction.foreignKey)} IN (SELECT "id" FROM ${quote(parent)} WHERE "_meta_doc_id" = ?)`,
15656
+ docId
15657
+ );
15658
+ sql.exec(
15659
+ `DELETE FROM ${quote(junction.table)} WHERE ${quote(junction.foreignKey)} NOT IN (SELECT "id" FROM ${quote(parent)})`
15660
+ );
15661
+ }
15662
+ }
15663
+ for (const parent of derived) {
15664
+ sql.exec(`DELETE FROM ${quote(parent)} WHERE "_meta_doc_id" = ?`, docId);
15665
+ }
15666
+ }
15667
+ var RECORD_LOG_STORAGE_VERSION = 4;
15668
+ var DATA_TABLES = ["record_log_rows", "record_log_view", "record_log_staged_base"];
15669
+ function migrateRecordLogStore(sql, options) {
15670
+ let current = 1;
15671
+ try {
15672
+ const [row] = Array.from(sql.exec(`SELECT value FROM record_log_meta WHERE key = 'storage_version'`));
15673
+ if (row) current = Number(row.value);
15674
+ } catch {
15675
+ }
15676
+ if (current >= RECORD_LOG_STORAGE_VERSION) return { migrated: false };
15677
+ if (current < 2) dropDb3QueryRows(sql, options);
15678
+ const converted = current < 3 ? convertToJsonb(sql) : null;
15679
+ sql.transaction(() => {
15680
+ addLocalOnlyColumns(sql);
15681
+ writeStorageVersion(sql, RECORD_LOG_STORAGE_VERSION);
15682
+ });
15683
+ converted?.report();
15684
+ return { migrated: true };
15685
+ }
15686
+ function addLocalOnlyColumns(sql) {
15687
+ const present = Array.from(sql.exec(`SELECT name FROM pragma_table_info('record_log_state')`)).map((row) => String(row.name));
15688
+ if (present.length === 0) return;
15689
+ for (const { column, add } of RECORD_LOG_LOCAL_ONLY_COLUMNS) {
15690
+ if (!present.includes(column)) sql.exec(add);
15691
+ }
15692
+ }
15693
+ function dropDb3QueryRows(sql, options) {
15694
+ sql.transaction(() => {
15695
+ for (const docId of storedDocuments(sql)) purgeDocumentQueryRows(sql, docId);
15696
+ if (options.db3Only) dropDocumentQueryTables(sql);
15697
+ sql.exec(`DROP TABLE IF EXISTS record_log_projection`);
15698
+ for (const row of Array.from(
15699
+ sql.exec(
15700
+ `SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'record_log_view' AND (name LIKE 'idx\\_record\\_log\\_view\\_f%' ESCAPE '\\' OR name LIKE 'idx\\_record\\_log\\_view\\_u%' ESCAPE '\\')`
15701
+ )
15702
+ )) {
15703
+ sql.exec(`DROP INDEX IF EXISTS ${quote(String(row.name))}`);
15704
+ }
15705
+ writeStorageVersion(sql, 2);
15706
+ });
15707
+ Logger.info(`[record-log] the local store was migrated to storage version 2 (db3 query tables ${options.db3Only ? "dropped" : "emptied of db3 rows"}).`);
15708
+ }
15709
+ function convertToJsonb(sql) {
15710
+ const present = new Set(
15711
+ Array.from(sql.exec(`SELECT name FROM sqlite_master WHERE type = 'table'`)).map((row) => String(row.name))
15712
+ );
15713
+ const tables = DATA_TABLES.filter((table) => present.has(table));
15714
+ const documents = (where2) => tables.length === 0 ? [] : Array.from(
15715
+ sql.exec(`${tables.map((table) => `SELECT doc_id FROM ${table}${where2}`).join(" UNION ")} ORDER BY doc_id`)
15716
+ ).map((row) => String(row.doc_id));
15717
+ const remaining = documents(` WHERE typeof(_data) = 'text'`);
15718
+ const total = documents("").length;
15719
+ const resumed = tables.some(
15720
+ (table) => Array.from(sql.exec(`SELECT 1 FROM ${table} WHERE typeof(_data) = 'blob' LIMIT 1`)).length > 0
15721
+ );
15722
+ let rewritten = 0;
15723
+ for (const docId of remaining) {
15724
+ sql.transaction(() => {
15725
+ for (const table of tables) {
15726
+ sql.exec(
15727
+ `UPDATE ${table} SET _data = jsonb(json_remove(_data, '$.id')) WHERE doc_id = ? AND typeof(_data) = 'text'`,
15728
+ docId
15729
+ );
15730
+ const [changed] = Array.from(sql.exec(`SELECT changes() AS n`));
15731
+ rewritten += Number(changed?.n ?? 0);
15732
+ }
15733
+ });
15734
+ }
15735
+ return {
15736
+ report: () => {
15737
+ if (total === 0) return;
15738
+ Logger.info(
15739
+ `[record-log] the local store was converted to storage version 3` + (resumed ? ` (resumed: ${remaining.length} of ${total} document(s) remained)` : "") + `: ${remaining.length} document(s), ${rewritten} row(s) rewritten as JSONB without id.`
15740
+ );
15741
+ }
15742
+ };
15743
+ }
15744
+ function writeStorageVersion(sql, version) {
15745
+ sql.exec(`CREATE TABLE IF NOT EXISTS record_log_meta (key TEXT PRIMARY KEY, value TEXT)`);
15746
+ sql.exec(
15747
+ `INSERT INTO record_log_meta (key, value) VALUES ('storage_version', ?)
15748
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value`,
15749
+ String(version)
15750
+ );
15751
+ }
15752
+ function dropDocumentQueryTables(sql) {
15753
+ const tables = Array.from(sql.exec("SELECT name FROM sqlite_master WHERE type = 'table'")).map((row) => String(row.name));
15754
+ const columnsOf = /* @__PURE__ */ new Map();
15755
+ for (const table of tables) {
15756
+ let columns = [];
15757
+ try {
15758
+ columns = Array.from(sql.exec(`PRAGMA table_info(${quote(table)})`)).map((row) => String(row.name));
15759
+ } catch {
15760
+ }
15761
+ columnsOf.set(table, columns);
15762
+ }
15763
+ const derived = tables.filter((table) => columnsOf.get(table).includes("_meta_doc_id"));
15764
+ const junctions = derived.flatMap((parent) => legacyJunctionsOf(parent, tables, columnsOf).map((j) => j.table));
15765
+ for (const table of /* @__PURE__ */ new Set([...junctions, ...derived])) sql.exec(`DROP TABLE IF EXISTS ${quote(table)}`);
15766
+ }
15767
+ function legacyJunctionsOf(parent, tables, columnsOf) {
15768
+ const model = parent.startsWith("model_") ? parent.slice("model_".length) : parent;
15769
+ const foreignKey = `${model}_id`;
15770
+ return tables.filter((table) => table.startsWith(`${parent}_`)).filter((table) => {
15771
+ const columns = columnsOf.get(table) ?? [];
15772
+ return columns.includes("value") && !columns.includes("_meta_doc_id") && columns.includes(foreignKey);
15773
+ }).map((table) => ({ table, foreignKey }));
15774
+ }
15775
+ function quote(identifier) {
15776
+ return `"${identifier.replace(/"/g, '""')}"`;
15777
+ }
15778
+
15516
15779
  // src/record-log-client/store.ts
15517
15780
  init_types();
15781
+ function localIndexesText(indexes) {
15782
+ return JSON.stringify(
15783
+ [...indexes].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map(({ name, model, fields, unique, named }) => [name, model, fields, unique, named ?? null])
15784
+ );
15785
+ }
15518
15786
  function recordLogRowRevision(row) {
15519
15787
  if (row === null) return null;
15520
15788
  const text = JSON.stringify(row);
@@ -15552,6 +15820,14 @@ function writtenValue(value) {
15552
15820
  if (typeof value === "number" || typeof value === "string") return value;
15553
15821
  return JSON.stringify(value);
15554
15822
  }
15823
+ function storedData(row) {
15824
+ const { id: _id, ...fields } = row;
15825
+ void _id;
15826
+ return JSON.stringify(fields);
15827
+ }
15828
+ function storedRow(id, data) {
15829
+ return rowWithId(String(id), JSON.parse(String(data)));
15830
+ }
15555
15831
  function rowsOf2(sql, query, ...bindings) {
15556
15832
  return Array.from(sql.exec(query, ...bindings));
15557
15833
  }
@@ -15654,6 +15930,29 @@ var SqlRecordLogTables = class {
15654
15930
  this.ensureState();
15655
15931
  this.sql.exec(`UPDATE record_log_state SET last_catch_up_at = ? WHERE doc_id = ?`, at, this.docId);
15656
15932
  }
15933
+ /** Whether the db3 lives only on this device (#5155). */
15934
+ localOnly() {
15935
+ return Number(this.state()?.local_only ?? 0) === 1;
15936
+ }
15937
+ setLocalOnly(localOnly) {
15938
+ this.ensureState();
15939
+ this.sql.exec(`UPDATE record_log_state SET local_only = ? WHERE doc_id = ?`, localOnly ? 1 : 0, this.docId);
15940
+ }
15941
+ /** A local-only db3's index registrations, by name. */
15942
+ localIndexes() {
15943
+ const text = this.state()?.local_indexes;
15944
+ if (!text) return [];
15945
+ try {
15946
+ return JSON.parse(String(text));
15947
+ } catch {
15948
+ return [];
15949
+ }
15950
+ }
15951
+ setLocalIndexes(indexes) {
15952
+ this.ensureState();
15953
+ const sorted = [...indexes].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
15954
+ this.sql.exec(`UPDATE record_log_state SET local_indexes = ? WHERE doc_id = ?`, JSON.stringify(sorted), this.docId);
15955
+ }
15657
15956
  generation() {
15658
15957
  const state = this.state();
15659
15958
  if (state?.replacing !== null && state?.replacing !== void 0) return Number(state.replacing);
@@ -15741,8 +16040,14 @@ var SqlRecordLogTables = class {
15741
16040
  const write = () => writing ??= { replacing: this.isReplacing(), generation: this.generation() };
15742
16041
  return {
15743
16042
  row: (key) => {
15744
- const [row] = rowsOf2(sql, `SELECT _data FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id = ?`, docId, key.model, key.id);
15745
- return row ? JSON.parse(String(row._data)) : null;
16043
+ const [row] = rowsOf2(
16044
+ sql,
16045
+ `SELECT ${jsonData()} FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id = ?`,
16046
+ docId,
16047
+ key.model,
16048
+ key.id
16049
+ );
16050
+ return row ? storedRow(key.id, row._data) : null;
15746
16051
  },
15747
16052
  set: (key, row) => {
15748
16053
  const { replacing, generation } = write();
@@ -15750,12 +16055,12 @@ var SqlRecordLogTables = class {
15750
16055
  sql.exec(`DELETE FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id = ?`, docId, key.model, key.id);
15751
16056
  }
15752
16057
  sql.exec(
15753
- `INSERT INTO record_log_rows (doc_id, _type, _id, _data, _gen) VALUES (?, ?, ?, ?, ?)
16058
+ `INSERT INTO record_log_rows (doc_id, _type, _id, _data, _gen) VALUES (?, ?, ?, jsonb(?), ?)
15754
16059
  ON CONFLICT (doc_id, _type, _id) DO UPDATE SET _data = excluded._data, _gen = excluded._gen`,
15755
16060
  docId,
15756
16061
  key.model,
15757
16062
  key.id,
15758
- JSON.stringify(row),
16063
+ storedData(row),
15759
16064
  generation
15760
16065
  );
15761
16066
  },
@@ -15809,13 +16114,13 @@ var SqlRecordLogTables = class {
15809
16114
  return (key) => {
15810
16115
  const [kept] = rowsOf2(
15811
16116
  this.sql,
15812
- `SELECT _data FROM record_log_staged_base WHERE doc_id = ? AND _type = ? AND _id = ?`,
16117
+ `SELECT ${jsonData()} FROM record_log_staged_base WHERE doc_id = ? AND _type = ? AND _id = ?`,
15813
16118
  this.docId,
15814
16119
  key.model,
15815
16120
  key.id
15816
16121
  );
15817
16122
  if (!kept) return confirmed.row(key);
15818
- return kept._data === null || kept._data === void 0 ? null : JSON.parse(String(kept._data));
16123
+ return kept._data === null || kept._data === void 0 ? null : storedRow(key.id, kept._data);
15819
16124
  };
15820
16125
  }
15821
16126
  clearStagedBase() {
@@ -16173,14 +16478,15 @@ var RecordLogStore = class {
16173
16478
  lowestPending: Number(row.lowest),
16174
16479
  pending: Number(row.pending)
16175
16480
  }));
16176
- const [state] = rowsOf2(this.sql, `SELECT last_catch_up_at FROM record_log_state WHERE doc_id = ?`, this.docId);
16481
+ const [state] = rowsOf2(this.sql, `SELECT * FROM record_log_state WHERE doc_id = ?`, this.docId);
16177
16482
  return {
16178
16483
  cursor: this.tables.cursor(),
16179
16484
  rows: Number(count?.n ?? 0),
16180
16485
  writers,
16181
16486
  replacing: this.tables.isReplacing(),
16182
16487
  staged: this.tables.staged(),
16183
- lastCatchUpAt: state?.last_catch_up_at === null || state?.last_catch_up_at === void 0 ? null : Number(state.last_catch_up_at)
16488
+ lastCatchUpAt: state?.last_catch_up_at === null || state?.last_catch_up_at === void 0 ? null : Number(state.last_catch_up_at),
16489
+ ...state ? { localOnly: Number(state.local_only ?? 0) === 1 } : {}
16184
16490
  };
16185
16491
  }
16186
16492
  /** This client's writer, or `null` before one is minted. */
@@ -16331,9 +16637,37 @@ var RecordLogStore = class {
16331
16637
  unacked: writer ? this.unackedOf(writer) : [],
16332
16638
  receipt: latestReceipt(this.tables.receipts()),
16333
16639
  segment: this.tables.heldSegment(),
16334
- ...this.tables.typeState()
16640
+ ...this.tables.typeState(),
16641
+ models: this.modelsHeld(),
16642
+ localOnly: Number(state?.local_only ?? 0) === 1,
16643
+ localIndexes: this.tables.localIndexes()
16335
16644
  };
16336
16645
  }
16646
+ /**
16647
+ * The models this copy holds, sorted and distinct: those with a view or
16648
+ * confirmed row, and those an unjudged entry of any writer touches.
16649
+ */
16650
+ modelsHeld() {
16651
+ const docId = this.docId;
16652
+ const skipScan = (table) => `WITH RECURSIVE t(m) AS (
16653
+ SELECT MIN(_type) FROM ${table} WHERE doc_id = ?
16654
+ UNION ALL SELECT (SELECT MIN(_type) FROM ${table} WHERE doc_id = ? AND _type > t.m) FROM t WHERE t.m IS NOT NULL)
16655
+ SELECT m AS _type FROM t WHERE m IS NOT NULL`;
16656
+ const held = /* @__PURE__ */ new Set();
16657
+ for (const table of ["record_log_view", "record_log_rows"]) {
16658
+ for (const row of rowsOf2(this.sql, skipScan(table), docId, docId)) held.add(String(row._type));
16659
+ }
16660
+ for (const row of rowsOf2(
16661
+ this.sql,
16662
+ `SELECT DISTINCT k._type AS _type FROM record_log_pending p JOIN record_log_pending_keys k
16663
+ ON k.doc_id = p.doc_id AND k.writer = p.writer AND k.seq = p.seq
16664
+ WHERE p.doc_id = ? AND p.void = 0 AND p.acked IS NULL`,
16665
+ docId
16666
+ )) {
16667
+ held.add(String(row._type));
16668
+ }
16669
+ return [...held].sort();
16670
+ }
16337
16671
  /** A writer's unacknowledged, unwithdrawn entries and the records each touches. */
16338
16672
  unackedOf(writer) {
16339
16673
  const bySeq = /* @__PURE__ */ new Map();
@@ -16362,12 +16696,12 @@ var RecordLogStore = class {
16362
16696
  read(model, id) {
16363
16697
  const [row] = rowsOf2(
16364
16698
  this.sql,
16365
- `SELECT _data FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id = ?`,
16699
+ `SELECT ${jsonData()} FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id = ?`,
16366
16700
  this.docId,
16367
16701
  model,
16368
16702
  id
16369
16703
  );
16370
- return row ? JSON.parse(String(row._data)) : null;
16704
+ return row ? storedRow(id, row._data) : null;
16371
16705
  }
16372
16706
  /** Several records' view rows, in the order asked for; a missing one is `null`. */
16373
16707
  readMany(model, ids) {
@@ -16377,12 +16711,12 @@ var RecordLogStore = class {
16377
16711
  for (let at = 0; at < unique.length; at += 500) {
16378
16712
  const slice = unique.slice(at, at + 500);
16379
16713
  for (const row of this.sql.exec(
16380
- `SELECT _id, _data FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id IN (${slice.map(() => "?").join(", ")})`,
16714
+ `SELECT _id, ${jsonData()} FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id IN (${slice.map(() => "?").join(", ")})`,
16381
16715
  this.docId,
16382
16716
  model,
16383
16717
  ...slice
16384
16718
  )) {
16385
- found.set(String(row._id), JSON.parse(String(row._data)));
16719
+ found.set(String(row._id), storedRow(row._id, row._data));
16386
16720
  }
16387
16721
  }
16388
16722
  return ids.map((id) => found.get(id) ?? null);
@@ -16391,9 +16725,9 @@ var RecordLogStore = class {
16391
16725
  readRowsAfter(model, after, limit) {
16392
16726
  return rowsOf2(
16393
16727
  this.sql,
16394
- after === null ? `SELECT _data FROM record_log_view WHERE doc_id = ? AND _type = ? ORDER BY _id LIMIT ?` : `SELECT _data FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id > ? ORDER BY _id LIMIT ?`,
16728
+ after === null ? `SELECT _id, ${jsonData()} FROM record_log_view WHERE doc_id = ? AND _type = ? ORDER BY _id LIMIT ?` : `SELECT _id, ${jsonData()} FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id > ? ORDER BY _id LIMIT ?`,
16395
16729
  ...after === null ? [this.docId, model, limit] : [this.docId, model, after, limit]
16396
- ).map((row) => JSON.parse(String(row._data)));
16730
+ ).map((row) => storedRow(row._id, row._data));
16397
16731
  }
16398
16732
  /** One page of a model's record ids in id order, after `after`. */
16399
16733
  recordIdsAfter(model, after, limit) {
@@ -16407,6 +16741,22 @@ var RecordLogStore = class {
16407
16741
  findIdByFields(model, fields, values) {
16408
16742
  return findHolder(this.sql, "record_log_view", this.docId, model, fields, values, []);
16409
16743
  }
16744
+ /**
16745
+ * Up to `limit` keys over `fields` that records of `model` in the view
16746
+ * share, null-free keys only, in key order: what a unique registration on
16747
+ * a local-only db3 is refused for (#5155), as the room reads its records.
16748
+ */
16749
+ duplicateKeys(model, fields, limit = 10) {
16750
+ const columns = fields.map((field) => `json_extract(_data, '$.${field}')`);
16751
+ return rowsOf2(
16752
+ this.sql,
16753
+ `SELECT ${columns.map((c, i) => `${c} AS k${i}`).join(", ")}, COUNT(*) AS n FROM record_log_view
16754
+ WHERE doc_id = ? AND _type = ? AND ${columns.map((c) => `${c} IS NOT NULL`).join(" AND ")}
16755
+ GROUP BY ${columns.join(", ")} HAVING COUNT(*) > 1 ORDER BY ${columns.join(", ")} LIMIT ${Math.max(1, Math.floor(limit))}`,
16756
+ this.docId,
16757
+ model
16758
+ ).map((row) => ({ values: fields.map((_, i) => row[`k${i}`]), count: Number(row.n) }));
16759
+ }
16410
16760
  /**
16411
16761
  * The records of `model` in the view matching `filter`, one page of them:
16412
16762
  * the model API's filter grammar on any field, declared or not, answered by
@@ -16673,12 +17023,12 @@ var RecordLogStore = class {
16673
17023
  this.sql.exec(`DELETE FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id = ?`, docId, key.model, key.id);
16674
17024
  } else {
16675
17025
  this.sql.exec(
16676
- `INSERT INTO record_log_view (doc_id, _type, _id, _data) VALUES (?, ?, ?, ?)
17026
+ `INSERT INTO record_log_view (doc_id, _type, _id, _data) VALUES (?, ?, ?, jsonb(?))
16677
17027
  ON CONFLICT (doc_id, _type, _id) DO UPDATE SET _data = excluded._data`,
16678
17028
  docId,
16679
17029
  key.model,
16680
17030
  key.id,
16681
- JSON.stringify(row)
17031
+ storedData(row)
16682
17032
  );
16683
17033
  }
16684
17034
  changed.push(key);
@@ -16701,12 +17051,14 @@ var RecordLogStore = class {
16701
17051
  /**
16702
17052
  * Commit local writes, one entry each, in one transaction: the budget
16703
17053
  * check, the pending entry and the guess on the view. A write whose
16704
- * `expect` no longer holds lands nothing and answers `stale`.
17054
+ * `expect` no longer holds lands nothing and answers `stale`. A db3 that
17055
+ * lives only on this device commits through {@link commitLocally}.
16705
17056
  *
16706
17057
  * @throws RecordLogWriteRefusedError `DOCUMENT_EPOCH_BUDGET` when both
16707
17058
  * epochs this client may write into are full; nothing of the command lands.
16708
17059
  */
16709
17060
  commitEntries(command) {
17061
+ if (this.tables.localOnly()) return this.sql.transaction(() => this.commitLocally(command));
16710
17062
  return this.sql.transaction(
16711
17063
  () => this.tables.countingEpochs(() => {
16712
17064
  const client = this.client(command.writer);
@@ -16742,6 +17094,153 @@ var RecordLogStore = class {
16742
17094
  })
16743
17095
  );
16744
17096
  }
17097
+ /**
17098
+ * Commit the writes of a db3 that lives only on this device (#5155). No
17099
+ * room will judge them, so the store does, as the room would: each write
17100
+ * is resolved against the confirmed rows (an upsert lands on the live
17101
+ * record holding its value), its guards are judged (`ifNotExists` fails on
17102
+ * a live record, `condition` on no live record or one that does not match,
17103
+ * an increment on a record neither live nor created by the entry), and the
17104
+ * rows it would leave are checked against the store's unique constraints.
17105
+ * An accepted write is written and confirmed at once by a result of the
17106
+ * store's own making (the next log number, the open epoch, its changes),
17107
+ * so it leaves the pending log as it lands and the cursor advances by one.
17108
+ * The reply carries what such a `receive` answers. No write budget
17109
+ * applies: nothing else writes to the db3.
17110
+ *
17111
+ * @throws RecordLogWriteRefusedError `DOCUMENT_CONSTRAINT_VIOLATED`,
17112
+ * `DB3_CONDITION_NOT_MET`, `DB3_RECORD_NOT_FOUND` or
17113
+ * `DOCUMENT_ENTRY_INVALID` (`details.scope: "local"`, with the room's
17114
+ * `conflicting`, `constraint` and `current`); nothing of the command lands.
17115
+ */
17116
+ commitLocally(command) {
17117
+ const client = this.client(command.writer);
17118
+ const results = [];
17119
+ const touched = [];
17120
+ const acknowledged = [];
17121
+ const settled = [];
17122
+ const settlements = [];
17123
+ for (const write of command.writes) {
17124
+ const stale = (write.expect ?? []).some(
17125
+ ({ model, id, revision }) => recordLogRowRevision(this.read(model, id)) !== revision
17126
+ );
17127
+ if (stale) {
17128
+ results.push({ stale: true });
17129
+ continue;
17130
+ }
17131
+ const judged = this.judgeLocally(write);
17132
+ const [m, ...also] = write.mutations;
17133
+ const entry = client.write(m, {
17134
+ also,
17135
+ ...write.upsertOn !== void 0 ? { upsertOn: write.upsertOn } : {},
17136
+ ts: command.ts ?? Date.now()
17137
+ });
17138
+ const out = client.receive({
17139
+ l: this.tables.cursor() + 1,
17140
+ e: this.tables.epochs().open,
17141
+ w: command.writer,
17142
+ seq: entry.seq,
17143
+ changes: judged.changes,
17144
+ ...judged.alias ? { alias: judged.alias } : {}
17145
+ });
17146
+ touched.push(...out.touched);
17147
+ acknowledged.push(...out.acknowledged);
17148
+ settled.push(...out.settled);
17149
+ settlements.push(...out.settlements ?? []);
17150
+ results.push(judged.resolved ? { entry, resolved: judged.resolved } : { entry });
17151
+ }
17152
+ const changed = this.settleView(touched);
17153
+ return { results, changed, cursor: this.tables.cursor(), acknowledged, settled, settlements };
17154
+ }
17155
+ /**
17156
+ * Judge one write of a local-only db3 against the confirmed rows, as the
17157
+ * room judges an entry: answers its changes, and for an upsert the record
17158
+ * it landed on and its alias when that is another record.
17159
+ *
17160
+ * @throws RecordLogWriteRefusedError when the room would refuse it.
17161
+ */
17162
+ judgeLocally(write) {
17163
+ const docId = this.docId;
17164
+ const confirmed = this.tables.confirmed();
17165
+ const constraints = this.tables.constraints();
17166
+ const [m, ...also] = write.mutations;
17167
+ const entry = { m, ...also.length ? { also } : {}, ...write.upsertOn !== void 0 ? { upsertOn: write.upsertOn } : {} };
17168
+ const refuse = (code, message, details = {}) => {
17169
+ throw new RecordLogWriteRefusedError(code, docId, message, { scope: "local", ...details });
17170
+ };
17171
+ if (write.upsertOn !== void 0 && !constraints.some((c) => c.model === m.model && c.fields.length === 1 && c.fields[0] === write.upsertOn)) {
17172
+ refuse(
17173
+ "DOCUMENT_ENTRY_INVALID",
17174
+ `upsertOn names ${write.upsertOn}, which no single-field unique constraint of ${m.model} covers`
17175
+ );
17176
+ }
17177
+ const resolved = resolveEntry(confirmed, entry, constraints);
17178
+ const created = /* @__PURE__ */ new Set();
17179
+ mutationsOf(entry).forEach((sent, at) => {
17180
+ const target = resolved.mutations[at];
17181
+ const key = { model: target.model, id: target.id };
17182
+ if (target.kind === "create") created.add(keyText2(key));
17183
+ if (sent.kind !== "increment" && sent.condition === void 0 && sent.ifNotExists === void 0) return;
17184
+ const where2 = at === 0 ? "" : `write ${at + 1} of the transaction: `;
17185
+ const record = `${target.model} id=${target.id}`;
17186
+ const row = confirmed.row(key);
17187
+ const current = { model: target.model, id: target.id, row };
17188
+ if (sent.kind === "increment" && !created.has(keyText2(key)) && row === null) {
17189
+ refuse("DB3_RECORD_NOT_FOUND", `${where2}${record} has no live record to increment`, { current });
17190
+ }
17191
+ if (sent.ifNotExists && row !== null) {
17192
+ refuse("DB3_CONDITION_NOT_MET", `${where2}ifNotExists failed: ${record} already exists`, { current });
17193
+ }
17194
+ if (sent.condition !== void 0 && (row === null || !conditionHolds(this.sql, target.model, target.id, row, sent.condition))) {
17195
+ refuse(
17196
+ "DB3_CONDITION_NOT_MET",
17197
+ `${where2}the condition on ${record} is not met${row === null ? " (a record with no live row meets none)" : ""}`,
17198
+ { current }
17199
+ );
17200
+ }
17201
+ });
17202
+ const before = /* @__PURE__ */ new Map();
17203
+ const after = /* @__PURE__ */ new Map();
17204
+ const keys = [];
17205
+ resolved.mutations.forEach((mutation, at) => {
17206
+ const { condition: _condition, ifNotExists: _ifNotExists, ...applied } = mutation;
17207
+ void _condition;
17208
+ void _ifNotExists;
17209
+ const key = { model: applied.model, id: applied.id };
17210
+ const text = keyText2(key);
17211
+ if (!before.has(text)) {
17212
+ const row2 = confirmed.row(key);
17213
+ before.set(text, row2);
17214
+ after.set(text, row2);
17215
+ keys.push(key);
17216
+ }
17217
+ const row = plainRowAfter(after.get(text) ?? null, applied);
17218
+ if (applied.kind === "increment" && row) {
17219
+ const field = Object.keys(applied.fields ?? {}).find((f) => !Number.isFinite(row[f]));
17220
+ if (field !== void 0) {
17221
+ refuse("DOCUMENT_ENTRY_INVALID", `${at === 0 ? "" : `write ${at + 1} of the transaction: `}increment of \`${field}\` overflows`, {
17222
+ current: { model: key.model, id: key.id, row: after.get(text) ?? null }
17223
+ });
17224
+ }
17225
+ }
17226
+ after.set(text, row);
17227
+ });
17228
+ const trial = {
17229
+ row: (key) => after.has(keyText2(key)) ? after.get(keyText2(key)) ?? null : confirmed.row(key),
17230
+ holder: (model, fields, values, excluding = []) => confirmed.holder(model, fields, values, excluding)
17231
+ };
17232
+ const violation = checkConstraints(trial, keys, constraints);
17233
+ if (violation) {
17234
+ refuse(
17235
+ "DOCUMENT_CONSTRAINT_VIOLATED",
17236
+ `unique constraint "${violation.constraint.name}" of ${violation.constraint.model}: ${violation.conflicting.id} already holds the key`,
17237
+ { constraint: violation.constraint.name, conflicting: { model: violation.conflicting.model, id: violation.conflicting.id } }
17238
+ );
17239
+ }
17240
+ const changes = keys.map((key) => changeBetween(key, before.get(keyText2(key)) ?? null, after.get(keyText2(key)) ?? null)).filter((change) => change !== null);
17241
+ const landed = write.upsertOn !== void 0 ? { model: m.model, id: resolved.alias?.to ?? m.id } : void 0;
17242
+ return { changes, ...landed ? { resolved: landed } : {}, ...resolved.alias ? { alias: resolved.alias } : {} };
17243
+ }
16745
17244
  /** Apply what the room relayed, item by item. */
16746
17245
  receive(command) {
16747
17246
  return this.sql.transaction(() => {
@@ -17111,9 +17610,34 @@ var RecordLogStore = class {
17111
17610
  this.tables.setPermission(command.permission);
17112
17611
  }
17113
17612
  if (command.type) this.tables.setType(command.type);
17613
+ if (command.localOnly !== void 0) this.tables.setLocalOnly(command.localOnly);
17614
+ if (command.localIndexes) this.tables.setLocalIndexes(command.localIndexes);
17114
17615
  return this.marks();
17115
17616
  });
17116
17617
  }
17618
+ /**
17619
+ * Replace a local-only db3's index registrations and the constraints it
17620
+ * enforces, in one transaction (#5155), only while its registrations are
17621
+ * still `from` and, when `unique` names a key, no two records of the view
17622
+ * share it: a registration is judged against the registrations and rows it
17623
+ * changes, and no write lands between the check and the constraint.
17624
+ * Answers `moved` (nothing written) when another change came first, and
17625
+ * `duplicates` (nothing written) naming up to `unique.limit` shared keys.
17626
+ */
17627
+ changeLocalIndexes(command) {
17628
+ return this.sql.transaction(() => {
17629
+ if (localIndexesText(this.tables.localIndexes()) !== localIndexesText(command.from)) {
17630
+ return { outcome: "moved", marks: this.marks() };
17631
+ }
17632
+ if (command.unique) {
17633
+ const duplicates = this.duplicateKeys(command.unique.model, command.unique.fields, command.unique.limit);
17634
+ if (duplicates.length > 0) return { outcome: "duplicates", duplicates, marks: this.marks() };
17635
+ }
17636
+ this.tables.setLocalIndexes(command.to);
17637
+ this.tables.setConstraints(command.constraints);
17638
+ return { outcome: "changed", marks: this.marks() };
17639
+ });
17640
+ }
17117
17641
  /**
17118
17642
  * The client's copy of its open epoch is full: it moves to the next epoch
17119
17643
  * the room has opened, the move a write's budget check makes on its own.
@@ -20185,9 +20709,11 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
20185
20709
  let pending = this.mirror.pending;
20186
20710
  let lowest = this.mirror.lowestPending;
20187
20711
  const committed = [];
20712
+ const confirmed = reply.acknowledged !== void 0;
20188
20713
  for (const result of reply.results) {
20189
20714
  if (!("entry" in result)) continue;
20190
20715
  nextSeq = Math.max(nextSeq, result.entry.seq + 1);
20716
+ if (confirmed) continue;
20191
20717
  pending++;
20192
20718
  lowest = lowest === null ? result.entry.seq : Math.min(lowest, result.entry.seq);
20193
20719
  this.unacked.set(result.entry.seq, keysOf(result.entry));
@@ -20195,6 +20721,11 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
20195
20721
  committed.push(result.entry);
20196
20722
  }
20197
20723
  this.mirror = { ...this.mirror, nextSeq, pending, lowestPending: lowest };
20724
+ if (confirmed) {
20725
+ const own = this.mirror.writer;
20726
+ this.acknowledged((reply.acknowledged ?? []).filter((a) => a.writer === own).map((a) => a.seq));
20727
+ this.noteSettled(reply);
20728
+ }
20198
20729
  if (committed.length) {
20199
20730
  for (const listener of [...this.commitListeners]) {
20200
20731
  try {
@@ -20501,6 +21032,10 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
20501
21032
  syncIndexes(indexes) {
20502
21033
  return this.host.dispatch({ kind: "syncIndexes", ...indexes ? { indexes: indexes.map((i) => ({ ...i, fields: [...i.fields] })) } : {} });
20503
21034
  }
21035
+ /** Up to `limit` keys over `fields` that records of `model` in the view share (the store's `duplicateKeys`). */
21036
+ duplicateKeys(model, fields, limit) {
21037
+ return this.host.dispatch({ kind: "duplicateKeys", model, fields: [...fields], ...limit !== void 0 ? { limit } : {} });
21038
+ }
20504
21039
  /** The store's view indexes as the room lists its own, `(model, fields, unique)`. */
20505
21040
  indexTuples() {
20506
21041
  return this.host.dispatch({ kind: "indexTuples" });
@@ -20750,6 +21285,27 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
20750
21285
  return this.mirror;
20751
21286
  });
20752
21287
  }
21288
+ /**
21289
+ * Replace a local-only db3's index registrations and constraints in one
21290
+ * store transaction (the store's `changeLocalIndexes`, #5155): written only
21291
+ * while the stored registrations are `from` and no two records share the
21292
+ * `unique` key; once written, the view indexes become `indexes`. Nothing
21293
+ * else scheduled here interleaves with it.
21294
+ */
21295
+ changeLocalIndexes(change) {
21296
+ return this.run("changeLocalIndexes", async () => {
21297
+ const reply = await this.host.dispatch({
21298
+ kind: "changeLocalIndexes",
21299
+ from: change.from.map((r) => ({ ...r, fields: [...r.fields] })),
21300
+ to: change.to.map((r) => ({ ...r, fields: [...r.fields] })),
21301
+ constraints: change.constraints.map((c) => ({ ...c, fields: [...c.fields] })),
21302
+ ...change.unique ? { unique: { ...change.unique, fields: [...change.unique.fields] } } : {}
21303
+ });
21304
+ this.mirror = reply.marks;
21305
+ if (reply.outcome === "changed") await this.syncIndexes(change.indexes);
21306
+ return reply;
21307
+ });
21308
+ }
20753
21309
  /**
20754
21310
  * The declarations of the db3's type the room sent this device (#5020),
20755
21311
  * per model each declared field's kind; `null` while the db3 is not known
@@ -21386,6 +21942,10 @@ function wireEntryOf(entry) {
21386
21942
  ...entry.upsertOn !== void 0 ? { upsertOn: entry.upsertOn } : {}
21387
21943
  };
21388
21944
  }
21945
+ function modelsOf2(entry) {
21946
+ if (entry.void || !entry.m) return [];
21947
+ return [...new Set([entry.m, ...entry.also ?? []].map((mutation) => mutation.model))];
21948
+ }
21389
21949
  var RecordLogDocumentSession = class {
21390
21950
  /**
21391
21951
  * @param docId - The document.
@@ -21408,7 +21968,10 @@ var RecordLogDocumentSession = class {
21408
21968
  );
21409
21969
  this.stopCommits = store.onCommitted((entries) => {
21410
21970
  if (this.phase !== "open") return;
21411
- for (const entry of entries) this.sender.enqueue(wireEntryOf(entry));
21971
+ for (const entry of entries) {
21972
+ this.declareFirstWrites(entry);
21973
+ this.sender.enqueue(wireEntryOf(entry));
21974
+ }
21412
21975
  });
21413
21976
  }
21414
21977
  phase = "idle";
@@ -21427,6 +21990,11 @@ var RecordLogDocumentSession = class {
21427
21990
  held = [];
21428
21991
  /** The open in progress sent its declaration and entries ahead of `record.opened`, or `null`. */
21429
21992
  ahead = null;
21993
+ /**
21994
+ * The models this open's declarations named (#5115): a model first written
21995
+ * while open that is not among them is declared before its entry.
21996
+ */
21997
+ declaredThisOpen = /* @__PURE__ */ new Set();
21430
21998
  /** `record.open` frames sent on this connection; only its first may send frames ahead. */
21431
21999
  openedOnConnection = 0;
21432
22000
  /** Set while the frames sent ahead are flushed: the sender may send before the open completes. */
@@ -21567,6 +22135,10 @@ var RecordLogDocumentSession = class {
21567
22135
  */
21568
22136
  start() {
21569
22137
  return this.serially(async () => {
22138
+ if (this.store.marks().localOnly) {
22139
+ Logger.debug(`[record-log] ${this.docId}: lives only on this device; not opened on the socket`);
22140
+ return;
22141
+ }
21570
22142
  if (this.phase === "open") {
21571
22143
  this.host.synced(this.docId);
21572
22144
  return;
@@ -21587,6 +22159,7 @@ var RecordLogDocumentSession = class {
21587
22159
  this.host.syncFailed(this.docId, "not connected");
21588
22160
  return;
21589
22161
  }
22162
+ this.store.resumeAcknowledgements?.();
21590
22163
  this.phase = "opening";
21591
22164
  const generation = this.generation;
21592
22165
  const own = this.store.writer();
@@ -21632,6 +22205,7 @@ var RecordLogDocumentSession = class {
21632
22205
  );
21633
22206
  }
21634
22207
  const accepts = RECORD_LOG_ACCEPTS.filter((token) => token !== "building" || !waited);
22208
+ this.declaredThisOpen = /* @__PURE__ */ new Set();
21635
22209
  this.sendFrame({
21636
22210
  type: "record.open",
21637
22211
  writer: current.writer,
@@ -21654,7 +22228,7 @@ var RecordLogDocumentSession = class {
21654
22228
  const ahead = { declarations: null, refused: false, seqs: [] };
21655
22229
  this.ahead = ahead;
21656
22230
  if (typed !== "yes") {
21657
- const models = this.host.declarations();
22231
+ const models = this.declarationsFor(pending);
21658
22232
  ahead.declarations = JSON.stringify(models);
21659
22233
  this.sender.enqueueControl({ type: "record.declare", models });
21660
22234
  }
@@ -21667,6 +22241,36 @@ var RecordLogDocumentSession = class {
21667
22241
  }
21668
22242
  ahead.seqs = this.sender.inFlightSeqs();
21669
22243
  }
22244
+ /**
22245
+ * The declarations this open carries (#5115): the host's answer for the
22246
+ * models the copy holds, as the marks last read name them, united with the
22247
+ * models of `pending`, the entries in hand (marks read before a commit
22248
+ * made since do not name its models). The models it names are this open's.
22249
+ */
22250
+ declarationsFor(pending) {
22251
+ const held = new Set(this.store.marks().models ?? []);
22252
+ for (const entry of pending) for (const model of modelsOf2(entry)) held.add(model);
22253
+ const models = this.host.declarations(this.docId, [...held].sort());
22254
+ this.declaredThisOpen = new Set(Object.keys(models));
22255
+ return models;
22256
+ }
22257
+ /**
22258
+ * A committed entry's models this open has not declared go in a
22259
+ * `record.declare` queued before it (#5115), so the room holds their
22260
+ * indexes and constraints before it applies the entry. A typed db3 takes
22261
+ * none (#5020), nor does a model the host has no declaration of.
22262
+ */
22263
+ declareFirstWrites(entry) {
22264
+ if (this.store.marks().typed === "yes") return;
22265
+ const fresh = modelsOf2(entry).filter((model) => !this.declaredThisOpen.has(model));
22266
+ if (!fresh.length) return;
22267
+ const answer = this.host.declarations(this.docId, fresh);
22268
+ const models = {};
22269
+ for (const model of fresh) if (answer[model] !== void 0) models[model] = answer[model];
22270
+ if (!Object.keys(models).length) return;
22271
+ for (const model of Object.keys(models)) this.declaredThisOpen.add(model);
22272
+ this.sender.enqueueControl({ type: "record.declare", models });
22273
+ }
21670
22274
  /**
21671
22275
  * The numbers sent ahead under the writer being opened that the room has
21672
22276
  * not answered: none once it refused them, and none an answer held so far
@@ -22575,7 +23179,7 @@ var RecordLogDocumentSession = class {
22575
23179
  if (this.store.marks().typed === "yes") {
22576
23180
  if (ahead.declarations === null) this.host.declared?.(this.docId);
22577
23181
  } else {
22578
- const models = this.host.declarations();
23182
+ const models = this.declarationsFor(pending);
22579
23183
  if (JSON.stringify(models) !== ahead.declarations) this.sender.enqueueControl({ type: "record.declare", models });
22580
23184
  }
22581
23185
  for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
@@ -22593,7 +23197,7 @@ var RecordLogDocumentSession = class {
22593
23197
  }
22594
23198
  this.sender.requeueInFlight(unsent.map(wireEntryOf));
22595
23199
  if (this.store.marks().typed === "yes") this.host.declared?.(this.docId);
22596
- else this.sender.enqueueControl({ type: "record.declare", models: this.host.declarations() });
23200
+ else this.sender.enqueueControl({ type: "record.declare", models: this.declarationsFor(pending) });
22597
23201
  for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
22598
23202
  return this.synced();
22599
23203
  }
@@ -22616,6 +23220,8 @@ var RecordLogDocumentSession = class {
22616
23220
  connected: () => this.phase === "draining" && this.current?.writer === writer && this.connected()
22617
23221
  });
22618
23222
  this.orphanSender = sender;
23223
+ const models = this.orphanDeclarations(unsent);
23224
+ if (models) sender.enqueueControl({ type: "record.declare", models });
22619
23225
  for (const entry of unsent) sender.enqueue(wireEntryOf(entry));
22620
23226
  sender.kick();
22621
23227
  if (this.outstanding.size) {
@@ -22641,6 +23247,24 @@ var RecordLogDocumentSession = class {
22641
23247
  this.orphanSender = null;
22642
23248
  await this.openNext();
22643
23249
  }
23250
+ /**
23251
+ * The declarations an earlier writer's entries go behind (#5115): those of
23252
+ * every model they write that the host declares into this db3. An earlier
23253
+ * session may have written them offline after its open declared what the
23254
+ * copy held and had bound then, and a binding made since says nothing of
23255
+ * what went, so none is left out. A host that does not scope declared
23256
+ * every model at the earlier open, as before #5115, and the drain keeps
23257
+ * today's frames. A typed db3 takes none (#5020).
23258
+ */
23259
+ orphanDeclarations(unsent) {
23260
+ if (!this.host.scopesDeclarations || this.store.marks().typed === "yes") return null;
23261
+ const written = [...new Set(unsent.flatMap(modelsOf2))].sort();
23262
+ if (!written.length) return null;
23263
+ const answer = this.host.declarations(this.docId, written);
23264
+ const models = {};
23265
+ for (const model of written) if (answer[model] !== void 0) models[model] = answer[model];
23266
+ return Object.keys(models).length ? models : null;
23267
+ }
22644
23268
  /** Answers for an orphan writer's entries arrived. */
22645
23269
  answered(seqs) {
22646
23270
  if (!this.current?.orphan) return;
@@ -22786,9 +23410,11 @@ var RecordLogDocumentSession = class {
22786
23410
  if (!this.current || !Number.isInteger(expected)) return;
22787
23411
  Logger.info(`[record-log] ${this.docId}: the room is missing entries from ${expected}; resending`);
22788
23412
  const pending = await this.store.pendingOf(this.current.writer);
22789
- this.senderOf(this.current.writer)?.resendFrom(
23413
+ const sender = this.senderOf(this.current.writer);
23414
+ const sent = new Set(sender?.inFlightSeqs() ?? []);
23415
+ sender?.resendFrom(
22790
23416
  expected,
22791
- pending.filter((p) => p.acked === void 0).map(wireEntryOf)
23417
+ pending.filter((p) => p.acked === void 0 && sent.has(p.seq)).map(wireEntryOf)
22792
23418
  );
22793
23419
  }
22794
23420
  /**
@@ -23085,7 +23711,8 @@ var RecordLogSessions = class {
23085
23711
  {
23086
23712
  connection: () => this.connection,
23087
23713
  awaitTypeBeforeDeclaring: this.host.awaitTypeBeforeDeclaring === true,
23088
- declarations: () => this.host.declarations(),
23714
+ scopesDeclarations: this.host.scopesDeclarations === true,
23715
+ declarations: (id, held) => this.host.declarations(id, held),
23089
23716
  notify: (records) => this.host.notify(records),
23090
23717
  reportRefused: (event) => this.host.reportRefused(event),
23091
23718
  synced: (id) => {
@@ -23158,12 +23785,239 @@ var RecordLogSessions = class {
23158
23785
 
23159
23786
  // src/record-log-client/binding.ts
23160
23787
  init_types();
23788
+
23789
+ // src/record-log-client/local-only.ts
23790
+ init_reservedFields();
23791
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
23792
+ var fieldsKey = (fields) => JSON.stringify(fields);
23793
+ var sameFieldSet = (a, b) => a.length === b.length && [...a].sort().join("\0") === [...b].sort().join("\0");
23794
+ function entriesOf(fields) {
23795
+ return fields instanceof Map ? [...fields.entries()] : Object.entries(fields);
23796
+ }
23797
+ function isSetField(declaration, field) {
23798
+ return entriesOf(declaration.fields).some(([name, options]) => name === field && options?.type === "stringset");
23799
+ }
23800
+ function fieldIndexName(model, field) {
23801
+ return `idx_records_${model.toLowerCase()}_${field.toLowerCase()}`;
23802
+ }
23803
+ function namedIndexName(model, name) {
23804
+ return `idx_named_${model.toLowerCase()}_${name.toLowerCase()}`;
23805
+ }
23806
+ function constraintIndexName(model, constraint) {
23807
+ const name = constraint.replace(/[^A-Za-z0-9_]/g, "_");
23808
+ const safe = IDENTIFIER.test(name) ? name : `c_${name}`;
23809
+ return `idx_uc_${model.toLowerCase()}_${safe.toLowerCase()}`;
23810
+ }
23811
+ function declaredConstraints(declarations) {
23812
+ const out = [];
23813
+ for (const declaration of declarations) {
23814
+ for (const constraint of declaration.uniqueConstraints) {
23815
+ if (constraint.fields.length === 0 || constraint.fields.some((field) => isSetField(declaration, field))) continue;
23816
+ out.push({ model: declaration.model, name: constraint.name, fields: [...constraint.fields] });
23817
+ }
23818
+ }
23819
+ return out;
23820
+ }
23821
+ function declarationIndexes(declarations) {
23822
+ const out = [];
23823
+ for (const declaration of declarations) {
23824
+ const { model } = declaration;
23825
+ if (!IDENTIFIER.test(model)) continue;
23826
+ const wants = /* @__PURE__ */ new Map();
23827
+ for (const [field, options] of entriesOf(declaration.fields)) {
23828
+ if (field === "id" || options?.type === "stringset" || !IDENTIFIER.test(field)) continue;
23829
+ if (options?.indexed !== true && options?.unique !== true) continue;
23830
+ wants.set(fieldsKey([field]), {
23831
+ name: fieldIndexName(model, field),
23832
+ model,
23833
+ fields: [field],
23834
+ unique: false,
23835
+ origins: [{ kind: "declaration", unique: false }]
23836
+ });
23837
+ }
23838
+ for (const constraint of declaredConstraints([declaration])) {
23839
+ const fields = constraint.fields;
23840
+ if (fields.length === 1 && fields[0] === "id" || !fields.every((f) => IDENTIFIER.test(f))) continue;
23841
+ const wanted2 = wants.get(fieldsKey(fields));
23842
+ if (wanted2) {
23843
+ wanted2.unique = true;
23844
+ wanted2.origins = [{ kind: "declaration", unique: true }];
23845
+ continue;
23846
+ }
23847
+ wants.set(fieldsKey(fields), {
23848
+ name: constraintIndexName(model, constraint.name),
23849
+ model,
23850
+ fields: [...fields],
23851
+ unique: true,
23852
+ origins: [{ kind: "declaration", unique: true }]
23853
+ });
23854
+ }
23855
+ out.push(...wants.values());
23856
+ }
23857
+ return out;
23858
+ }
23859
+ function localIndexList(declarations, registrations) {
23860
+ const byDefinition = /* @__PURE__ */ new Map();
23861
+ for (const index of declarationIndexes(declarations)) byDefinition.set(fieldsKey([index.model, ...index.fields]), index);
23862
+ for (const registration of registrations) {
23863
+ const key = fieldsKey([registration.model, ...registration.fields]);
23864
+ const held = byDefinition.get(key);
23865
+ const origin = { kind: "named", unique: registration.unique };
23866
+ if (held) {
23867
+ held.origins = [...held.origins.filter((o) => o.kind !== "named"), origin];
23868
+ held.unique = held.origins.some((o) => o.unique);
23869
+ continue;
23870
+ }
23871
+ byDefinition.set(key, {
23872
+ name: registration.name,
23873
+ model: registration.model,
23874
+ fields: [...registration.fields],
23875
+ unique: registration.unique,
23876
+ origins: [origin]
23877
+ });
23878
+ }
23879
+ return [...byDefinition.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
23880
+ }
23881
+ function localConstraints(declarations, registrations) {
23882
+ const declared = declaredConstraints(declarations);
23883
+ const out = [...declared];
23884
+ for (const index of localIndexList(declarations, registrations)) {
23885
+ if (!index.unique || !index.origins.some((o) => o.kind === "named" && o.unique)) continue;
23886
+ if (declared.some((c) => c.model === index.model && sameFieldSet(c.fields, index.fields))) continue;
23887
+ const declaration = declarations.find((d) => d.model === index.model);
23888
+ if (declaration && index.fields.some((field) => isSetField(declaration, field))) continue;
23889
+ out.push({ model: index.model, name: index.name, fields: [...index.fields] });
23890
+ }
23891
+ return out;
23892
+ }
23893
+ var LOCAL_INDEX_MAX_DUPLICATES = 10;
23894
+ var RecordLogLocalIndexError = class _RecordLogLocalIndexError extends Error {
23895
+ /**
23896
+ * @param code - The room's code (`DB3_INDEX_INVALID`, `DB3_INDEX_NOT_UNIQUE`, ...).
23897
+ * @param message - What is wrong, as the room says it.
23898
+ * @param details - What the refusal names (`duplicates`, `origins`, `index`, `field`).
23899
+ */
23900
+ constructor(code, message, details = {}) {
23901
+ super(message);
23902
+ this.code = code;
23903
+ this.details = details;
23904
+ this.name = "RecordLogLocalIndexError";
23905
+ Object.setPrototypeOf(this, _RecordLogLocalIndexError.prototype);
23906
+ }
23907
+ };
23908
+ var invalid = (message) => new RecordLogLocalIndexError("DB3_INDEX_INVALID", message);
23909
+ function parseLocalRegistration(body) {
23910
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
23911
+ throw invalid("An index registration is an object: { model, field | fields, unique?, name? }");
23912
+ }
23913
+ const raw = body;
23914
+ const identifier = (value) => typeof value === "string" && IDENTIFIER.test(value);
23915
+ if (!identifier(raw.model)) throw invalid("model must be an identifier (letters, digits and _, not starting with a digit)");
23916
+ if (raw.field === void 0 === (raw.fields === void 0)) throw invalid("Give exactly one of field and fields");
23917
+ const fields = raw.field !== void 0 ? [raw.field] : raw.fields;
23918
+ if (!Array.isArray(fields) || fields.length === 0) throw invalid("fields must be a non-empty array of field names");
23919
+ for (const field of fields) {
23920
+ if (!identifier(field)) throw invalid(`Field ${JSON.stringify(field)} must be an identifier`);
23921
+ if (field === "id") throw invalid("id needs no index: the primary key serves it");
23922
+ const reserved = checkReservedFieldName(field);
23923
+ if (reserved) throw invalid(reserved);
23924
+ }
23925
+ if (new Set(fields).size !== fields.length) throw invalid("fields must not repeat a field");
23926
+ if (raw.unique !== void 0 && typeof raw.unique !== "boolean") throw invalid("unique must be true or false");
23927
+ if (raw.name !== void 0 && !identifier(raw.name)) throw invalid("name must be an identifier");
23928
+ const unique = raw.unique === true;
23929
+ if (fields.length > 1 && (raw.name === void 0 || !unique)) {
23930
+ throw invalid("An index over several fields is a unique constraint: give it a name and unique: true");
23931
+ }
23932
+ return { model: raw.model, fields, unique, ...raw.name !== void 0 ? { name: raw.name } : {} };
23933
+ }
23934
+ function localIndexNotUnique(model, fields, duplicates) {
23935
+ return new RecordLogLocalIndexError(
23936
+ "DB3_INDEX_NOT_UNIQUE",
23937
+ `Live ${model} records share ${fields.join(", ")}: resolve the duplicates before registering a unique index`,
23938
+ { duplicates }
23939
+ );
23940
+ }
23941
+ function registerLocalIndex(declarations, registrations, body, duplicates) {
23942
+ const { model, fields, unique, name } = parseLocalRegistration(body);
23943
+ const declaration = declarations.find((d) => d.model === model);
23944
+ for (const field of fields) {
23945
+ if (declaration && isSetField(declaration, field)) {
23946
+ throw new RecordLogLocalIndexError(
23947
+ "DB3_INDEX_SET_FIELD",
23948
+ `${model}.${field} is a string set, and a set field takes no index: $contains and facets read its members from the record itself`,
23949
+ { field }
23950
+ );
23951
+ }
23952
+ }
23953
+ const list = localIndexList(declarations, registrations);
23954
+ const existing = list.find((index2) => index2.model === model && fieldsKey(index2.fields) === fieldsKey(fields));
23955
+ const existingNamed = existing ? registrations.find((r) => r.name === existing.name)?.named ?? null : null;
23956
+ if (name !== void 0) {
23957
+ const holder = registrations.find((r) => r.model === model && r.named === name && fieldsKey(r.fields) !== fieldsKey(fields));
23958
+ if (holder) {
23959
+ throw new RecordLogLocalIndexError("DB3_INDEX_NAME_TAKEN", `${model} already has an index named ${name} (${holder.name}) over other fields`, {
23960
+ index: holder.name
23961
+ });
23962
+ }
23963
+ if (existing && existingNamed !== name) {
23964
+ throw new RecordLogLocalIndexError(
23965
+ "DB3_INDEX_EXISTS",
23966
+ `${existing.name} already indexes ${model} on ${fields.join(", ")}: register it without a name, or drop it first`,
23967
+ { index: existing.name }
23968
+ );
23969
+ }
23970
+ }
23971
+ if (unique) {
23972
+ const shared = duplicates(model, fields);
23973
+ if (shared.length > 0) throw localIndexNotUnique(model, fields, shared);
23974
+ }
23975
+ const indexName = existing?.name ?? (name !== void 0 ? namedIndexName(model, name) : fieldIndexName(model, fields[0]));
23976
+ const registration = {
23977
+ name: indexName,
23978
+ model,
23979
+ fields: [...fields],
23980
+ unique,
23981
+ ...name ?? existingNamed ? { named: name ?? existingNamed } : {}
23982
+ };
23983
+ const next = [...registrations.filter((r) => !(r.model === model && fieldsKey(r.fields) === fieldsKey(fields))), registration];
23984
+ const index = localIndexList(declarations, next).find((i) => i.name === indexName);
23985
+ return { registrations: next, index };
23986
+ }
23987
+ function dropLocalIndex(declarations, registrations, name) {
23988
+ const index = localIndexList(declarations, registrations).find((i) => i.name === name);
23989
+ if (!index) throw new RecordLogLocalIndexError("DB3_INDEX_NOT_FOUND", `No registered index is named ${name}`, { index: name });
23990
+ const remaining = index.origins.filter((o) => o.kind !== "named");
23991
+ if (remaining.length > 0) {
23992
+ throw new RecordLogLocalIndexError(
23993
+ "DB3_INDEX_IN_USE",
23994
+ `${name} is kept by ${remaining.map((o) => o.kind).join(" and ")}: change the declaration to drop it`,
23995
+ { index: name, origins: remaining }
23996
+ );
23997
+ }
23998
+ return registrations.filter((r) => r.name !== name);
23999
+ }
24000
+
24001
+ // src/record-log-client/binding.ts
23161
24002
  var RECORD_LOG_TEARDOWN_DRAIN_BOUND_MS = 2e3;
23162
24003
  function isRecordLogResident(state, createdLocally = false) {
23163
- if (createdLocally) return true;
24004
+ if (createdLocally || state.localOnly === true) return true;
23164
24005
  if (state.lastCatchUpAt === null || state.lastCatchUpAt === void 0) return false;
23165
24006
  return !state.replacing || state.staged === true;
23166
24007
  }
24008
+ function declarationOf(schema) {
24009
+ const fields = {};
24010
+ for (const [field, options] of schema.fields) {
24011
+ const kept = {};
24012
+ for (const [key, value] of Object.entries(options ?? {})) {
24013
+ if (typeof value === "function" || value === void 0) continue;
24014
+ kept[key] = value;
24015
+ }
24016
+ fields[field] = kept;
24017
+ }
24018
+ const uniqueConstraints = schema.options?.uniqueConstraints;
24019
+ return { fields, ...uniqueConstraints?.length ? { uniqueConstraints } : {} };
24020
+ }
23167
24021
  var RecordLogDocumentBinding = class {
23168
24022
  /**
23169
24023
  * @param dbEngine - The instance's engine.
@@ -23180,7 +24034,9 @@ var RecordLogDocumentBinding = class {
23180
24034
  // A db3 this device has not heard about may be typed: its first open
23181
24035
  // declares only once the room says it is not (#5020).
23182
24036
  awaitTypeBeforeDeclaring: true,
23183
- declarations: () => this.declarations(),
24037
+ // Each db3 is declared the models it uses (#5115).
24038
+ scopesDeclarations: true,
24039
+ declarations: (docId, held) => this.declarations(docId, held),
23184
24040
  notify: (records) => this.notify(records),
23185
24041
  reportRefused: (event) => this.ormContext.reportRecordLogWriteRefused(event)
23186
24042
  });
@@ -23455,26 +24311,27 @@ var RecordLogDocumentBinding = class {
23455
24311
  });
23456
24312
  }
23457
24313
  /**
23458
- * Every active model's declaration as `record.declare` carries it: its
23459
- * fields with their JSON options, and its compound unique constraints.
24314
+ * The declarations `record.declare` carries into `docId` (#5115): of the
24315
+ * `held` models (those its copy holds or this client writes there) with
24316
+ * an active class, of the models whose default db3 is `docId`, and, when
24317
+ * `docId` is the global default db3, of every active model without a
24318
+ * default db3 of its own elsewhere, since a save naming no db3 lands
24319
+ * there. Each is its fields with their JSON options and its compound
24320
+ * unique constraints. With no `docId`, every active model's.
23460
24321
  */
23461
- declarations() {
24322
+ declarations(docId, held = []) {
23462
24323
  const out = {};
24324
+ const wanted2 = new Set(held);
24325
+ const globalDefault = docId !== void 0 && this.ormContext.getGlobalDefaultDocumentId() === docId;
23463
24326
  for (const [, modelClass] of this.modelRegistry.getActiveModels()) {
23464
24327
  const schema = modelClass.getSchema?.();
23465
24328
  const name = schema?.options?.name;
23466
24329
  if (!name) continue;
23467
- const fields = {};
23468
- for (const [field, options] of schema.fields) {
23469
- const kept = {};
23470
- for (const [key, value] of Object.entries(options ?? {})) {
23471
- if (typeof value === "function" || value === void 0) continue;
23472
- kept[key] = value;
23473
- }
23474
- fields[field] = kept;
24330
+ if (docId !== void 0 && !wanted2.has(name)) {
24331
+ const bound = this.ormContext.getDocumentIdForModel(name);
24332
+ if (bound !== docId && !(globalDefault && bound === void 0)) continue;
23475
24333
  }
23476
- const uniqueConstraints = schema.options?.uniqueConstraints;
23477
- out[name] = { fields, ...uniqueConstraints?.length ? { uniqueConstraints } : {} };
24334
+ out[name] = declarationOf(schema);
23478
24335
  }
23479
24336
  return out;
23480
24337
  }
@@ -23488,9 +24345,122 @@ var RecordLogDocumentBinding = class {
23488
24345
  async connect(docId) {
23489
24346
  const store = await this.open(docId);
23490
24347
  store.resumeAcknowledgements();
23491
- await store.syncIndexes();
24348
+ if (store.marks().localOnly) await this.applyLocalDeclarations(docId);
24349
+ else await store.syncIndexes();
23492
24350
  if (this.opened.get(docId) === store) this.connected.add(docId);
23493
24351
  }
24352
+ /**
24353
+ * Mark bound `docId` as a db3 that lives only on this device (#5155): from
24354
+ * now its store judges and confirms its own writes, its session sends
24355
+ * nothing, and it is resident once connected. The mark is the store's, so
24356
+ * every later bind finds it.
24357
+ */
24358
+ async markLocalOnly(docId) {
24359
+ const store = this.opened.get(docId);
24360
+ if (!store || store.marks().localOnly) return;
24361
+ await store.setState({ localOnly: true });
24362
+ }
24363
+ /**
24364
+ * Make a bound local-only db3's constraints and view indexes what this
24365
+ * instance's models declare and what was registered on it here
24366
+ * (`localConstraints`, `localIndexList`): at every bind, when a model
24367
+ * registers later, and after a registration or a drop. Nothing happens for
24368
+ * a db3 that syncs.
24369
+ */
24370
+ async applyLocalDeclarations(docId) {
24371
+ const store = this.opened.get(docId);
24372
+ if (!store || !store.marks().localOnly) return;
24373
+ await this.changeLocalIndexes(store, (current) => ({ registrations: current }));
24374
+ }
24375
+ /**
24376
+ * Change a bound local-only db3's registrations to what `plan` makes of
24377
+ * the ones its store holds, with the constraints and view indexes that
24378
+ * follow, in one store transaction (#5155): the change is written only
24379
+ * while the store still holds the registrations it was planned from and,
24380
+ * for a unique key, no two records share it; planned again from the
24381
+ * store's registrations when another change came first (a concurrent
24382
+ * registration, another client of the store). Answers the registrations
24383
+ * written.
24384
+ *
24385
+ * @throws RecordLogLocalIndexError when `plan` refuses, or `DB3_INDEX_NOT_UNIQUE` when records share the key.
24386
+ */
24387
+ async changeLocalIndexes(store, plan) {
24388
+ let current = (await store.refreshMarks()).localIndexes ?? [];
24389
+ for (; ; ) {
24390
+ const { registrations, unique } = plan(current);
24391
+ const declarations = this.modelDeclarations();
24392
+ const reply = await store.changeLocalIndexes({
24393
+ from: current,
24394
+ to: registrations,
24395
+ constraints: localConstraints(declarations, registrations),
24396
+ ...unique ? { unique: { ...unique, limit: LOCAL_INDEX_MAX_DUPLICATES } } : {},
24397
+ indexes: localIndexList(declarations, registrations).map(({ name, model, fields, unique: unique2 }) => ({ name, model, fields: [...fields], unique: unique2 }))
24398
+ });
24399
+ if (reply.outcome === "changed") return registrations;
24400
+ if (reply.outcome === "duplicates") throw localIndexNotUnique(unique.model, unique.fields, reply.duplicates);
24401
+ current = reply.marks.localIndexes ?? [];
24402
+ }
24403
+ }
24404
+ /**
24405
+ * A bound local-only db3's index list (`localIndexList`), as the room
24406
+ * lists its registry; `null` when `docId` is not a local-only db3 bound
24407
+ * here.
24408
+ */
24409
+ localIndexes(docId) {
24410
+ const store = this.opened.get(docId);
24411
+ if (!store || !store.marks().localOnly) return null;
24412
+ return localIndexList(this.modelDeclarations(), store.marks().localIndexes ?? []);
24413
+ }
24414
+ /**
24415
+ * Register an index on a bound local-only db3 by the room's rules
24416
+ * (`registerLocalIndex`): kept in its store, and its constraints and view
24417
+ * indexes made to match before this resolves, judged against the
24418
+ * registrations and records the store holds as it writes. Answers the
24419
+ * index as the list now shows it; `null` when `docId` is not a local-only
24420
+ * db3 bound here.
24421
+ *
24422
+ * @throws RecordLogLocalIndexError when the room would refuse it.
24423
+ */
24424
+ async registerLocalIndex(docId, registration) {
24425
+ const store = this.opened.get(docId);
24426
+ if (!store || !store.marks().localOnly) return null;
24427
+ const { model, fields, unique } = parseLocalRegistration(registration);
24428
+ let index = null;
24429
+ await this.changeLocalIndexes(store, (current) => {
24430
+ const planned = registerLocalIndex(this.modelDeclarations(), current, registration, () => []);
24431
+ index = planned.index;
24432
+ return { registrations: planned.registrations, ...unique ? { unique: { model, fields } } : {} };
24433
+ });
24434
+ return index;
24435
+ }
24436
+ /**
24437
+ * Drop a registration's index on a bound local-only db3 by the room's
24438
+ * rules (`dropLocalIndex`); its constraints and view indexes follow before
24439
+ * this resolves. `false` when `docId` is not a local-only db3 bound here.
24440
+ *
24441
+ * @throws RecordLogLocalIndexError when the room would refuse it.
24442
+ */
24443
+ async dropLocalIndex(docId, name) {
24444
+ const store = this.opened.get(docId);
24445
+ if (!store || !store.marks().localOnly) return false;
24446
+ await this.changeLocalIndexes(store, (current) => ({ registrations: dropLocalIndex(this.modelDeclarations(), current, name) }));
24447
+ return true;
24448
+ }
24449
+ /** Every active model's fields and resolved unique constraints, as a local-only db3's schema is derived from. */
24450
+ modelDeclarations() {
24451
+ const out = [];
24452
+ for (const [, modelClass] of this.modelRegistry.getActiveModels()) {
24453
+ const schema = modelClass.getSchema?.();
24454
+ const name = schema?.options?.name;
24455
+ if (!name) continue;
24456
+ out.push({
24457
+ model: name,
24458
+ fields: schema.fields,
24459
+ uniqueConstraints: schema.resolvedUniqueConstraints ?? []
24460
+ });
24461
+ }
24462
+ return out;
24463
+ }
23494
24464
  /**
23495
24465
  * Cache the room's index list for `docId` and reconcile the store's
23496
24466
  * lookup indexes; without a list, reconcile from the cache. `null` when
@@ -23802,6 +24772,7 @@ var DocumentManagerImpl = class {
23802
24772
  opened = await this.recordLog.open(docId);
23803
24773
  await this.withdrawIfOvertaken(docId, epoch, opened);
23804
24774
  this.recordLog.setCreatedLocally(docId, options?.createdLocally !== false);
24775
+ if (options?.localOnly) await this.recordLog.markLocalOnly(docId);
23805
24776
  if (options?.type) await this.recordLog.seedType(docId, options.type);
23806
24777
  await this.recordLog.adoptPermission(docId, permissionHint);
23807
24778
  await this.withdrawIfOvertaken(docId, epoch, opened);
@@ -23847,6 +24818,7 @@ var DocumentManagerImpl = class {
23847
24818
  async rebindRecordLogDocument(docId, yDoc, permissionHint, options, epoch) {
23848
24819
  Logger.info(`[DocumentManager] Rebinding format-3 document ${docId} in place (permission: ${permissionHint})`);
23849
24820
  if (options?.createdLocally !== void 0) this.recordLog.setCreatedLocally(docId, options.createdLocally);
24821
+ if (options?.localOnly) await this.recordLog.markLocalOnly(docId);
23850
24822
  if (options?.type) await this.recordLog.seedType(docId, options.type);
23851
24823
  await this.recordLog.adoptPermission(docId, permissionHint);
23852
24824
  await this.modelRegistry.initializeAllForDocument(yDoc, this.dbEngine, docId, permissionHint, 3);
@@ -23899,6 +24871,9 @@ var DocumentManagerImpl = class {
23899
24871
  await binding.permissionChanged(docId, permission);
23900
24872
  },
23901
24873
  syncIndexes: (docId, indexes) => binding.syncIndexes(docId, indexes),
24874
+ localIndexes: (docId) => binding.localIndexes(docId),
24875
+ registerLocalIndex: (docId, registration) => binding.registerLocalIndex(docId, registration),
24876
+ dropLocalIndex: (docId, name) => binding.dropLocalIndex(docId, name),
23902
24877
  storedState: (docId) => binding.probe(docId),
23903
24878
  syncMarks: (docId) => binding.storeOf(docId)?.marks() ?? null,
23904
24879
  pending: async (docId) => {
@@ -24053,6 +25028,7 @@ var DocumentManagerImpl = class {
24053
25028
  3
24054
25029
  );
24055
25030
  await this.recordLog.hydrateModel(docId, modelName);
25031
+ await this.recordLog.applyLocalDeclarations(docId);
24056
25032
  return;
24057
25033
  }
24058
25034
  const touched = /* @__PURE__ */ new Set();