js-bao 0.12.0-alpha.17 → 0.12.0-alpha.19

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
@@ -892,7 +892,7 @@ var init_patterns = __esm({
892
892
 
893
893
  // src/engines/queryTableKey.ts
894
894
  function queryTableUpsert(quotedTable, columns, values) {
895
- const quoted3 = columns.map(quoteIdentifier);
895
+ const quoted4 = columns.map(quoteIdentifier);
896
896
  const placeholders = columns.map(() => "?").join(", ");
897
897
  const docAt = columns.indexOf(DOC);
898
898
  const idAt = columns.indexOf(ID);
@@ -902,7 +902,7 @@ function queryTableUpsert(quotedTable, columns, values) {
902
902
  const onConflict = updates.length > 0 ? `ON CONFLICT DO UPDATE SET ${updates.join(", ")}` : "ON CONFLICT DO NOTHING";
903
903
  return [
904
904
  {
905
- sql: `INSERT INTO ${quotedTable} (${quoted3.join(
905
+ sql: `INSERT INTO ${quotedTable} (${quoted4.join(
906
906
  ", "
907
907
  )}) VALUES (${placeholders}) ${onConflict};`,
908
908
  params: [...values]
@@ -919,7 +919,7 @@ function queryTableUpsert(quotedTable, columns, values) {
919
919
  });
920
920
  }
921
921
  statements.push({
922
- sql: `INSERT INTO ${quotedTable} (${quoted3.join(
922
+ sql: `INSERT INTO ${quotedTable} (${quoted4.join(
923
923
  ", "
924
924
  )}) SELECT ${placeholders} WHERE NOT EXISTS (SELECT 1 FROM ${quotedTable} WHERE ${quoteIdentifier(
925
925
  ID
@@ -971,11 +971,11 @@ function junctionInsert(quotedJunction, quotedForeignKey, quotedParent, recordId
971
971
  }
972
972
  const quotedId = quoteIdentifier(ID);
973
973
  const quotedDoc = quoteIdentifier(DOC);
974
- const held = `SELECT 1 FROM ${quotedJunction} WHERE ${quotedForeignKey} = ? AND ${quoteIdentifier(
974
+ const held2 = `SELECT 1 FROM ${quotedJunction} WHERE ${quotedForeignKey} = ? AND ${quoteIdentifier(
975
975
  "value"
976
976
  )} = ?`;
977
977
  return {
978
- sql: `INSERT INTO ${quotedJunction} ${columns} SELECT ?, ?, ?, p.${quotedDoc} FROM ${quotedParent} AS p WHERE p.${quotedId} = ? AND NOT EXISTS (${held} AND ${quotedDoc} IS p.${quotedDoc}) UNION ALL SELECT ?, ?, ?, NULL WHERE NOT EXISTS (SELECT 1 FROM ${quotedParent} WHERE ${quotedId} = ?) AND NOT EXISTS (${held});`,
978
+ sql: `INSERT INTO ${quotedJunction} ${columns} SELECT ?, ?, ?, p.${quotedDoc} FROM ${quotedParent} AS p WHERE p.${quotedId} = ? AND NOT EXISTS (${held2} AND ${quotedDoc} IS p.${quotedDoc}) UNION ALL SELECT ?, ?, ?, NULL WHERE NOT EXISTS (SELECT 1 FROM ${quotedParent} WHERE ${quotedId} = ?) AND NOT EXISTS (${held2});`,
979
979
  params: [
980
980
  id,
981
981
  recordId,
@@ -1841,32 +1841,32 @@ var init_DocumentQueryTranslator = __esm({
1841
1841
  if (!includeFields.includes("id")) {
1842
1842
  includeFields.unshift("id");
1843
1843
  }
1844
- const quoted3 = includeFields.map((field) => this.getQuotedField(field));
1844
+ const quoted4 = includeFields.map((field) => this.getQuotedField(field));
1845
1845
  if (selectDocument) {
1846
- quoted3.push(quoteIdentifier(DOCUMENT_TIEBREAKER));
1846
+ quoted4.push(quoteIdentifier(DOCUMENT_TIEBREAKER));
1847
1847
  }
1848
1848
  for (const field of aliasedSortFields ?? []) {
1849
- quoted3.push(
1849
+ quoted4.push(
1850
1850
  `${this.quotedSortField(field)} AS ${quoteIdentifier(
1851
1851
  cursorSortAlias(field)
1852
1852
  )}`
1853
1853
  );
1854
1854
  }
1855
- return quoted3.join(", ");
1855
+ return quoted4.join(", ");
1856
1856
  } else if (hasExcludes) {
1857
1857
  const allFields = Array.from(this.schema.keys());
1858
1858
  const selectedFields = allFields.filter(
1859
1859
  (field) => !excludeFields.includes(field)
1860
1860
  );
1861
- const quoted3 = selectedFields.map((field) => this.getQuotedField(field));
1861
+ const quoted4 = selectedFields.map((field) => this.getQuotedField(field));
1862
1862
  for (const field of aliasedSortFields ?? []) {
1863
- quoted3.push(
1863
+ quoted4.push(
1864
1864
  `${this.quotedSortField(field)} AS ${quoteIdentifier(
1865
1865
  cursorSortAlias(field)
1866
1866
  )}`
1867
1867
  );
1868
1868
  }
1869
- return quoted3.join(", ");
1869
+ return quoted4.join(", ");
1870
1870
  }
1871
1871
  return "*";
1872
1872
  }
@@ -2199,9 +2199,9 @@ function judgeMaxDrift(maxDrift, documents, sync, drift, now = Date.now()) {
2199
2199
  if (!maxDrift) return;
2200
2200
  for (const db3Id of documents) {
2201
2201
  if (sync?.[db3Id]?.localOnly) continue;
2202
- const own2 = drift?.[db3Id] ?? null;
2203
- if (own2 === null || maxDrift.entries !== void 0 && own2.entriesBehind > maxDrift.entries || maxDrift.ageMs !== void 0 && now - own2.asOf > maxDrift.ageMs) {
2204
- throw new Db3DriftExceededError(db3Id, own2, maxDrift, now);
2202
+ const own3 = drift?.[db3Id] ?? null;
2203
+ if (own3 === null || maxDrift.entries !== void 0 && own3.entriesBehind > maxDrift.entries || maxDrift.ageMs !== void 0 && now - own3.asOf > maxDrift.ageMs) {
2204
+ throw new Db3DriftExceededError(db3Id, own3, maxDrift, now);
2205
2205
  }
2206
2206
  }
2207
2207
  }
@@ -2297,7 +2297,7 @@ function scanSignalsFor(model, filter, options, context) {
2297
2297
  const out = [];
2298
2298
  const root = signalFor(model, filter ?? {}, options?.sort, indexes, context.isSetField);
2299
2299
  if (root) out.push(root);
2300
- const walk = (specs, prefix) => {
2300
+ const walk2 = (specs, prefix) => {
2301
2301
  if (!Array.isArray(specs)) return;
2302
2302
  for (const spec of specs) {
2303
2303
  if (!isPlainObject(spec) || typeof spec.model !== "string") continue;
@@ -2311,10 +2311,10 @@ function scanSignalsFor(model, filter, options, context) {
2311
2311
  leg = signalFor(spec.model, { id: { $in: [LEG_KEY] }, ...extra }, void 0, indexes, context.isSetField);
2312
2312
  }
2313
2313
  if (leg) out.push({ ...leg, path });
2314
- walk(spec.include, path);
2314
+ walk2(spec.include, path);
2315
2315
  }
2316
2316
  };
2317
- walk(options?.include, "");
2317
+ walk2(options?.include, "");
2318
2318
  return out;
2319
2319
  }
2320
2320
  var RANGES, LEG_KEY, isPlainObject, isPlainObjectOrArray, Indexes;
@@ -3240,15 +3240,661 @@ var init_vectorFields = __esm({
3240
3240
  }
3241
3241
  });
3242
3242
 
3243
+ // src/query/filterFields.ts
3244
+ function keep(target, key, value) {
3245
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
3246
+ }
3247
+ function mapFilterFields(filter, rename) {
3248
+ if (!isPlainObject2(filter)) return filter;
3249
+ let changed = false;
3250
+ const out = {};
3251
+ const extra = [];
3252
+ for (const [key, value] of Object.entries(filter)) {
3253
+ let nextKey = key;
3254
+ let nextValue = value;
3255
+ if (key === "$and" || key === "$or") {
3256
+ if (Array.isArray(value)) {
3257
+ const mapped = value.map((branch) => mapFilterFields(branch, rename));
3258
+ if (mapped.some((branch, i) => branch !== value[i])) nextValue = mapped;
3259
+ }
3260
+ } else if (key === "$near") {
3261
+ if (isPlainObject2(value)) {
3262
+ const field = typeof value.field === "string" ? rename(value.field) : value.field;
3263
+ const inner = value.filter === void 0 ? void 0 : mapFilterFields(value.filter, rename);
3264
+ if (field !== value.field || inner !== value.filter) {
3265
+ nextValue = { ...value, ...field !== void 0 ? { field } : {}, ...inner !== void 0 ? { filter: inner } : {} };
3266
+ }
3267
+ }
3268
+ } else if (key === "$search") {
3269
+ if (isPlainObject2(value) && Array.isArray(value.fields)) {
3270
+ const fields = value.fields.map((field) => typeof field === "string" ? rename(field) : field);
3271
+ if (fields.some((field, i) => field !== value.fields[i])) nextValue = { ...value, fields };
3272
+ }
3273
+ } else if (!key.startsWith("$")) {
3274
+ nextKey = rename(key);
3275
+ }
3276
+ if (nextKey !== key || nextValue !== value) changed = true;
3277
+ if (Object.prototype.hasOwnProperty.call(out, nextKey)) {
3278
+ extra.push({ [nextKey]: nextValue });
3279
+ continue;
3280
+ }
3281
+ keep(out, nextKey, nextValue);
3282
+ }
3283
+ if (!changed) return filter;
3284
+ if (!extra.length) return out;
3285
+ const conditions = [];
3286
+ const rest = {};
3287
+ for (const [key, value] of Object.entries(out)) {
3288
+ if (extra.some((e) => Object.prototype.hasOwnProperty.call(e, key))) conditions.push({ [key]: value });
3289
+ else keep(rest, key, value);
3290
+ }
3291
+ const and = Array.isArray(rest.$and) ? rest.$and : [];
3292
+ return { ...rest, $and: [...and, ...conditions, ...extra] };
3293
+ }
3294
+ var isPlainObject2;
3295
+ var init_filterFields = __esm({
3296
+ "src/query/filterFields.ts"() {
3297
+ "use strict";
3298
+ isPlainObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3299
+ }
3300
+ });
3301
+
3302
+ // src/models/fieldNames.ts
3303
+ function keep2(target, key, value) {
3304
+ if (key === "__proto__") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
3305
+ else target[key] = value;
3306
+ }
3307
+ function fieldNameMapOf(fields) {
3308
+ let map = null;
3309
+ const entries = fields instanceof Map ? fields.entries() : Object.entries(fields);
3310
+ for (const [name, options] of entries) {
3311
+ const stored = options?.storedAs;
3312
+ if (typeof stored !== "string" || stored === name) continue;
3313
+ map ??= { accepted: {}, current: {} };
3314
+ keep2(map.accepted, name, stored);
3315
+ keep2(map.accepted, stored, stored);
3316
+ keep2(map.current, stored, name);
3317
+ }
3318
+ return map;
3319
+ }
3320
+ function storedNameOf(map, name) {
3321
+ return map && own(map.accepted, name) ? map.accepted[name] : name;
3322
+ }
3323
+ function currentNameOf(map, stored) {
3324
+ return map && own(map.current, stored) ? map.current[stored] : stored;
3325
+ }
3326
+ function toStoredData(model, map, data) {
3327
+ if (!map || !isObject(data)) return data;
3328
+ let changed = false;
3329
+ const seen = /* @__PURE__ */ new Map();
3330
+ const out = {};
3331
+ for (const [key, value] of Object.entries(data)) {
3332
+ const stored = storedNameOf(map, key);
3333
+ const earlier = seen.get(stored);
3334
+ if (earlier !== void 0) throw new FieldNamedTwiceError(model, stored, [earlier, key]);
3335
+ seen.set(stored, key);
3336
+ if (stored !== key) changed = true;
3337
+ keep2(out, stored, value);
3338
+ }
3339
+ return changed ? out : data;
3340
+ }
3341
+ function toStoredFilter(map, filter) {
3342
+ return map && filter ? mapFilterFields(filter, (field) => storedNameOf(map, field)) : filter;
3343
+ }
3344
+ function toStoredKeys(map, value) {
3345
+ if (!map) return value;
3346
+ if (Array.isArray(value)) return value.map((v) => typeof v === "string" ? storedNameOf(map, v) : v);
3347
+ if (!isObject(value)) return value;
3348
+ const out = {};
3349
+ for (const [key, v] of Object.entries(value)) keep2(out, storedNameOf(map, key), v);
3350
+ return out;
3351
+ }
3352
+ function toStoredIncludes(namesOf, parent, include) {
3353
+ if (!Array.isArray(include)) return include;
3354
+ const parentMap = namesOf(parent);
3355
+ return include.map((spec) => {
3356
+ if (!isObject(spec) || typeof spec.model !== "string") return spec;
3357
+ const target = namesOf(spec.model);
3358
+ const out = { ...spec };
3359
+ if (typeof spec.sourceField === "string") out.sourceField = storedNameOf(parentMap, spec.sourceField);
3360
+ if (typeof spec.localField === "string") out.localField = storedNameOf(parentMap, spec.localField);
3361
+ if (typeof spec.foreignKey === "string") out.foreignKey = storedNameOf(target, spec.foreignKey);
3362
+ if (spec.filter !== void 0) out.filter = toStoredFilter(target, spec.filter);
3363
+ if (spec.sort !== void 0) out.sort = toStoredKeys(target, spec.sort);
3364
+ if (spec.projection !== void 0) out.projection = toStoredKeys(target, spec.projection);
3365
+ if (spec.include !== void 0) out.include = toStoredIncludes(namesOf, spec.model, spec.include);
3366
+ return out;
3367
+ });
3368
+ }
3369
+ function namesAnyModel(namesOf, model, include) {
3370
+ if (namesOf(model)) return true;
3371
+ if (!Array.isArray(include)) return false;
3372
+ return include.some((spec) => isObject(spec) && typeof spec.model === "string" && namesAnyModel(namesOf, spec.model, spec.include));
3373
+ }
3374
+ function storedLevel(map, level) {
3375
+ if (typeof level === "string") return storedNameOf(map, level);
3376
+ if (isObject(level) && typeof level.field === "string") return { ...level, field: storedNameOf(map, level.field) };
3377
+ return level;
3378
+ }
3379
+ function spellingsOf(map, stored) {
3380
+ const out = [stored];
3381
+ for (const [name, target] of Object.entries(map.accepted)) if (target === stored && name !== stored) out.push(name);
3382
+ return out;
3383
+ }
3384
+ function storedSortKey(map, key, groupBy, operations) {
3385
+ if (key === "count") return key;
3386
+ const spelled = (stored, form) => spellingsOf(map, stored).some((name) => form(name) === key);
3387
+ let membership = 0;
3388
+ for (const level of groupBy) {
3389
+ if (!isObject(level) || typeof level.field !== "string" || typeof level.contains !== "string") continue;
3390
+ const index = membership++;
3391
+ const contains = level.contains;
3392
+ const forms = [(f) => `ss_${f}_${index}`, (f) => `has_${f}_${contains}`, (f) => `${f}::${contains}`];
3393
+ for (const form of forms) if (spelled(level.field, form)) return form(level.field);
3394
+ }
3395
+ for (const op of operations) {
3396
+ if (!isObject(op) || typeof op.type !== "string" || op.type === "count" || typeof op.field !== "string") continue;
3397
+ const type = op.type;
3398
+ const form = (f) => `${type}_${f}`;
3399
+ if (spelled(op.field, form)) return form(op.field);
3400
+ }
3401
+ for (const level of groupBy) {
3402
+ if (!isObject(level) || typeof level.field !== "string" || typeof level.period !== "string") continue;
3403
+ const period = level.period;
3404
+ const form = (f) => `${f}_${period}`;
3405
+ if (spelled(level.field, form)) return form(level.field);
3406
+ }
3407
+ return storedNameOf(map, key);
3408
+ }
3409
+ function toStoredAggregate(map, options) {
3410
+ if (!map || !isObject(options)) return options;
3411
+ const out = { ...options };
3412
+ if (Array.isArray(options.groupBy)) out.groupBy = options.groupBy.map((level) => storedLevel(map, level));
3413
+ if (Array.isArray(options.operations)) out.operations = options.operations.map((op) => storedLevel(map, op));
3414
+ if (options.filter !== void 0) out.filter = toStoredFilter(map, options.filter);
3415
+ if (isObject(options.sort) && typeof options.sort.field === "string") {
3416
+ const groupBy = Array.isArray(out.groupBy) ? out.groupBy : [];
3417
+ const operations = Array.isArray(out.operations) ? out.operations : [];
3418
+ out.sort = { ...options.sort, field: storedSortKey(map, options.sort.field, groupBy, operations) };
3419
+ }
3420
+ return out;
3421
+ }
3422
+ function toCurrentRow(namesOf, model, row, include) {
3423
+ if (!isObject(row)) return row;
3424
+ const map = namesOf(model);
3425
+ const hasRelated = isObject(row._related) && Array.isArray(include) && include.length > 0;
3426
+ if (!map && !hasRelated) return row;
3427
+ const out = {};
3428
+ const owned = /* @__PURE__ */ new Set();
3429
+ if (map) {
3430
+ for (const key of Object.keys(row)) {
3431
+ if (key !== "id" && !key.startsWith("_") && own(map.current, key) && map.current[key] !== key) owned.add(map.current[key]);
3432
+ }
3433
+ }
3434
+ for (const [key, value] of Object.entries(row)) {
3435
+ if (key === "id" || key.startsWith("_")) {
3436
+ keep2(out, key, value);
3437
+ continue;
3438
+ }
3439
+ if (map && !own(map.current, key) && owned.has(key)) continue;
3440
+ keep2(out, currentNameOf(map, key), value);
3441
+ }
3442
+ if (hasRelated) {
3443
+ const related = { ...row._related };
3444
+ for (const spec of include) {
3445
+ if (!isObject(spec) || typeof spec.model !== "string") continue;
3446
+ const as = typeof spec.as === "string" && spec.as !== "" ? spec.as : spec.model;
3447
+ if (!own(related, as)) continue;
3448
+ const value = related[as];
3449
+ related[as] = Array.isArray(value) ? value.map((r) => toCurrentRow(namesOf, spec.model, r, spec.include)) : toCurrentRow(namesOf, spec.model, value, spec.include);
3450
+ }
3451
+ out._related = related;
3452
+ }
3453
+ return out;
3454
+ }
3455
+ function currentAggregateKeys(map, sent) {
3456
+ const group = /* @__PURE__ */ new Map();
3457
+ const row = /* @__PURE__ */ new Map();
3458
+ const unknown = [];
3459
+ for (const level of Array.isArray(sent.groupBy) ? sent.groupBy : []) {
3460
+ const field = typeof level === "string" ? level : isObject(level) && typeof level.field === "string" ? level.field : void 0;
3461
+ if (field === void 0) continue;
3462
+ const make = (f) => typeof level === "string" ? f : aggregationGroupKey({ ...level, field: f });
3463
+ if (own(map.accepted, field)) group.set(make(field), make(currentNameOf(map, storedNameOf(map, field))));
3464
+ else unknown.push({ map: group, make });
3465
+ }
3466
+ for (const op of Array.isArray(sent.operations) ? sent.operations : []) {
3467
+ if (!isObject(op) || typeof op.type !== "string" || op.type === "count" || typeof op.field !== "string") continue;
3468
+ const make = (f) => aggregationOperationKey({ ...op, field: f });
3469
+ if (own(map.accepted, op.field)) row.set(make(op.field), make(currentNameOf(map, storedNameOf(map, op.field))));
3470
+ else unknown.push({ map: row, make });
3471
+ }
3472
+ for (const { map: target, make } of unknown) {
3473
+ for (const [stored, current] of Object.entries(map.current)) {
3474
+ const key = make(stored);
3475
+ if (!target.has(key)) target.set(key, make(current));
3476
+ }
3477
+ }
3478
+ return { group, row };
3479
+ }
3480
+ function toCurrentAggregateRows(map, sent, rows) {
3481
+ if (!map || !Array.isArray(rows) || !isObject(sent)) return rows;
3482
+ const keys = currentAggregateKeys(map, sent);
3483
+ const renamed = (m, key) => m.get(key) ?? key;
3484
+ return rows.map((row) => {
3485
+ if (!isObject(row)) return row;
3486
+ const out = {};
3487
+ for (const [key, value] of Object.entries(row)) {
3488
+ if (key === "group" && isObject(value)) {
3489
+ const group = {};
3490
+ for (const [g, v] of Object.entries(value)) keep2(group, renamed(keys.group, g), v);
3491
+ out.group = group;
3492
+ } else {
3493
+ keep2(out, renamed(keys.row, key), value);
3494
+ }
3495
+ }
3496
+ return out;
3497
+ });
3498
+ }
3499
+ function resolveUpsertTarget(name, constraintNames, map) {
3500
+ if (!map || constraintNames.includes(name)) return name;
3501
+ return storedNameOf(map, name);
3502
+ }
3503
+ function declareFieldNameTypes(schemas, types) {
3504
+ const list = Array.isArray(schemas) ? schemas.map((schema) => [String(schema.name ?? ""), schema]) : Object.entries(schemas);
3505
+ for (const [name, schema] of list) {
3506
+ if (!schema || !own(types, name)) continue;
3507
+ const merged = [.../* @__PURE__ */ new Set([...declaredTypes.get(schema) ?? [], ...types[name]])].sort();
3508
+ declaredTypes.set(schema, merged);
3509
+ }
3510
+ }
3511
+ function fieldNameTypesOf(schema) {
3512
+ return schema && declaredTypes.get(schema) || [];
3513
+ }
3514
+ function fieldNamesOfClass(modelClass) {
3515
+ const getSchema = modelClass?.getSchema;
3516
+ if (typeof getSchema !== "function") return null;
3517
+ try {
3518
+ return getSchema.call(modelClass)?.fieldNames ?? null;
3519
+ } catch {
3520
+ return null;
3521
+ }
3522
+ }
3523
+ var FieldNamedTwiceError, own, isObject, declaredTypes;
3524
+ var init_fieldNames = __esm({
3525
+ "src/models/fieldNames.ts"() {
3526
+ "use strict";
3527
+ init_filterFields();
3528
+ init_aggregationRows();
3529
+ FieldNamedTwiceError = class extends Error {
3530
+ /** Always `INVALID_ARGUMENT`. */
3531
+ code = "INVALID_ARGUMENT";
3532
+ /** The model whose data named the field twice. */
3533
+ model;
3534
+ /** The field's stored name. */
3535
+ stored;
3536
+ /** The two names the data used, in the order it used them. */
3537
+ names;
3538
+ /**
3539
+ * @param model - The model.
3540
+ * @param stored - The field's stored name.
3541
+ * @param names - The two names the data used.
3542
+ */
3543
+ constructor(model, stored, names) {
3544
+ super(
3545
+ `${model}: the record data names one field twice, as ${names.map((n) => JSON.stringify(n)).join(" and ")} (stored as ${JSON.stringify(stored)}); name it once`
3546
+ );
3547
+ this.name = "FieldNamedTwiceError";
3548
+ this.model = model;
3549
+ this.stored = stored;
3550
+ this.names = names;
3551
+ }
3552
+ };
3553
+ own = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
3554
+ isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3555
+ declaredTypes = /* @__PURE__ */ new WeakMap();
3556
+ }
3557
+ });
3558
+
3559
+ // src/models/jsonFields.ts
3560
+ function quoted(text, path) {
3561
+ for (let i = 0; i < text.length; i++) {
3562
+ const unit = text.charCodeAt(i);
3563
+ if (unit >= 55296 && unit <= 56319) {
3564
+ const next = text.charCodeAt(i + 1);
3565
+ if (next >= 56320 && next <= 57343) {
3566
+ i++;
3567
+ continue;
3568
+ }
3569
+ }
3570
+ if (unit >= 55296 && unit <= 57343) throw new Refusal("surrogate", path, `${path} holds a lone surrogate, which JSON text cannot carry`);
3571
+ }
3572
+ return JSON.stringify(text);
3573
+ }
3574
+ function kindOf(value) {
3575
+ if (value === void 0) return "undefined";
3576
+ if (typeof value !== "object") return typeof value;
3577
+ return Object.prototype.toString.call(value).slice(8, -1);
3578
+ }
3579
+ function canonical(value, path) {
3580
+ if (value === null) return "null";
3581
+ if (value === true) return "true";
3582
+ if (value === false) return "false";
3583
+ if (typeof value === "number") {
3584
+ if (!Number.isFinite(value)) throw new Refusal("number", path, `${path} is ${String(value)}; JSON holds finite numbers only`);
3585
+ if (Math.abs(value) > MAX_EXACT) {
3586
+ throw new Refusal("number", path, `${path} is ${String(value)}; a db3 JSON value holds numbers up to 2^53 in magnitude (store a larger one as a string)`);
3587
+ }
3588
+ return Object.is(value, -0) ? "0" : String(value);
3589
+ }
3590
+ if (typeof value === "string") return quoted(value, path);
3591
+ if (Array.isArray(value)) {
3592
+ const items = [];
3593
+ for (let i = 0; i < value.length; i++) items.push(canonical(value[i], `${path}[${i}]`));
3594
+ return `[${items.join(",")}]`;
3595
+ }
3596
+ if (typeof value === "object" && Object.prototype.toString.call(value) === "[object Object]") {
3597
+ const record = value;
3598
+ const keys = Object.keys(record).filter((key) => record[key] !== void 0).sort();
3599
+ return `{${keys.map((key) => `${quoted(key, path)}:${canonical(record[key], `${path}.${key}`)}`).join(",")}}`;
3600
+ }
3601
+ throw new Refusal("type", path, `${path} is ${kindOf(value)}; a db3 JSON value holds only objects, arrays, strings, numbers, booleans and null`);
3602
+ }
3603
+ function canonicalDb3Json(value) {
3604
+ if (value === null || typeof value !== "object" || Array.isArray(value) || Object.prototype.toString.call(value) !== "[object Object]") {
3605
+ const what = Array.isArray(value) ? "an array" : value === null ? "null" : kindOf(value);
3606
+ return { ok: false, kind: "root", path: "value", reason: `the value is ${what}; a db3 JSON field holds an object` };
3607
+ }
3608
+ try {
3609
+ return { ok: true, text: canonical(value, "value") };
3610
+ } catch (error) {
3611
+ if (error instanceof Refusal) return { ok: false, kind: error.kind, path: error.path, reason: error.reason };
3612
+ throw error;
3613
+ }
3614
+ }
3615
+ function isType(value, type) {
3616
+ if (type === "array") return Array.isArray(value);
3617
+ if (type === "object") return isNode(value);
3618
+ if (type === "string") return typeof value === "string";
3619
+ if (type === "number") return typeof value === "number" && !Number.isNaN(value);
3620
+ if (type === "integer") return Number.isInteger(value);
3621
+ if (type === "boolean") return typeof value === "boolean";
3622
+ if (type === "null") return value === null;
3623
+ return true;
3624
+ }
3625
+ function enumTaggedOneOf(schema) {
3626
+ const members = schema.oneOf;
3627
+ if (!Array.isArray(members) || members.length < 2) return null;
3628
+ if (!members.every((m) => isNode(m) && m.type === "object")) return null;
3629
+ if (ONE_OF_SIBLINGS.some((key) => hasOwn(schema, key))) return null;
3630
+ const literals = members.map((m) => {
3631
+ const found = /* @__PURE__ */ new Map();
3632
+ if (!isNode(m.properties)) return found;
3633
+ for (const [name, sub] of Object.entries(m.properties)) {
3634
+ if (isNode(sub) && Array.isArray(sub.enum) && sub.enum.length === 1 && isScalarTag(sub.enum[0])) found.set(name, sub.enum[0]);
3635
+ }
3636
+ return found;
3637
+ });
3638
+ const candidates = [...literals[0].keys()].filter((name) => {
3639
+ if (!literals.every((map) => map.has(name))) return false;
3640
+ return new Set(literals.map((map) => JSON.stringify(map.get(name)))).size === literals.length;
3641
+ });
3642
+ if (candidates.length !== 1) return null;
3643
+ return { discriminant: candidates[0], members: members.map((m, i) => ({ tag: literals[i].get(candidates[0]), schema: m })) };
3644
+ }
3645
+ function requiredTagOneOf(members) {
3646
+ const objects = members.filter((m) => isNode(m) && m.type === "object");
3647
+ if (objects.length < 2 || objects.length !== members.length) return null;
3648
+ const tags = objects.map((m) => {
3649
+ const found = /* @__PURE__ */ new Map();
3650
+ if (!isNode(m.properties)) return found;
3651
+ for (const [name, sub] of Object.entries(m.properties)) {
3652
+ if (!isNode(sub)) continue;
3653
+ if (Array.isArray(sub.enum) && sub.enum.length === 1 && isScalarTag(sub.enum[0])) found.set(name, sub.enum[0]);
3654
+ else if (hasOwn(sub, "const") && isScalarTag(sub.const)) found.set(name, sub.const);
3655
+ }
3656
+ return found;
3657
+ });
3658
+ const candidates = [...tags[0].keys()].filter((name) => {
3659
+ if (!tags.every((map) => map.has(name))) return false;
3660
+ if (!objects.every((m) => Array.isArray(m.required) && m.required.includes(name))) return false;
3661
+ return new Set(tags.map((map) => JSON.stringify(map.get(name)))).size === tags.length;
3662
+ });
3663
+ if (candidates.length !== 1) return null;
3664
+ return { discriminant: candidates[0], members: objects.map((schema, i) => ({ tag: tags[i].get(candidates[0]), schema })) };
3665
+ }
3666
+ function bounds(value, schema, path, issues) {
3667
+ const fail2 = (message) => issues.push({ path, message });
3668
+ if (typeof value === "number") {
3669
+ if (typeof schema.minimum === "number" && value < schema.minimum) fail2(`${path} must be >= ${schema.minimum}`);
3670
+ if (typeof schema.maximum === "number" && value > schema.maximum) fail2(`${path} must be <= ${schema.maximum}`);
3671
+ }
3672
+ if (typeof value === "string") {
3673
+ const length = [...value].length;
3674
+ const tooShort = typeof schema.minLength === "number" && length < schema.minLength;
3675
+ const tooLong = typeof schema.maxLength === "number" && length > schema.maxLength;
3676
+ if (tooShort) fail2(`${path} must be at least ${schema.minLength} characters`);
3677
+ if (tooLong) fail2(`${path} must be at most ${schema.maxLength} characters`);
3678
+ if (typeof schema.pattern === "string" && !tooShort && !tooLong) {
3679
+ let pattern = null;
3680
+ try {
3681
+ pattern = new RegExp(schema.pattern, "u");
3682
+ } catch {
3683
+ fail2(`${path} cannot be checked: the schema's pattern ${JSON.stringify(schema.pattern)} is not a valid regular expression`);
3684
+ }
3685
+ if (pattern && !pattern.test(value)) fail2(`${path} must match the pattern ${schema.pattern}`);
3686
+ }
3687
+ }
3688
+ if (Array.isArray(value)) {
3689
+ if (typeof schema.minItems === "number" && value.length < schema.minItems) fail2(`${path} must have at least ${schema.minItems} items`);
3690
+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems) {
3691
+ fail2(`${path} must have at most ${schema.maxItems} items`);
3692
+ return true;
3693
+ }
3694
+ }
3695
+ return false;
3696
+ }
3697
+ function walk(value, schema, path, issues) {
3698
+ if (!isNode(schema)) return;
3699
+ const fail2 = (at, message) => issues.push({ path: at, message });
3700
+ const union = enumTaggedOneOf(schema);
3701
+ if (union) {
3702
+ if (!isNode(value)) return void fail2(path, `${path} must be object`);
3703
+ bounds(value, schema, path, issues);
3704
+ const tag = value[union.discriminant];
3705
+ const matched = union.members.find((m) => m.tag === tag);
3706
+ if (!matched) {
3707
+ const expected = union.members.map((m) => JSON.stringify(m.tag)).join(", ");
3708
+ return void fail2(`${path}.${union.discriminant}`, `${path}.${union.discriminant} ${JSON.stringify(tag)} matches no case (expected one of ${expected})`);
3709
+ }
3710
+ return walk(value, matched.schema, path, issues);
3711
+ }
3712
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
3713
+ if (types.length > 0 && !types.some((type) => isType(value, type))) return void fail2(path, `${path} must be ${types.join(" or ")}`);
3714
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value)) return void fail2(path, `${path} must be one of ${schema.enum.join(", ")}`);
3715
+ if (bounds(value, schema, path, issues)) return;
3716
+ if (isNode(value)) {
3717
+ const properties = isNode(schema.properties) ? schema.properties : {};
3718
+ const required = Array.isArray(schema.required) ? schema.required : [];
3719
+ for (const key of required) {
3720
+ if (!hasOwn(value, String(key))) fail2(`${path}.${key}`, `${path}.${key} is required`);
3721
+ }
3722
+ for (const [key, child] of Object.entries(properties)) {
3723
+ if (hasOwn(value, key)) walk(value[key], child, `${path}.${key}`, issues);
3724
+ }
3725
+ if (schema.additionalProperties === false) {
3726
+ for (const key of Object.keys(value)) {
3727
+ if (!hasOwn(properties, key)) fail2(`${path}.${key}`, `${path}.${key} is not allowed`);
3728
+ }
3729
+ }
3730
+ }
3731
+ if (Array.isArray(value) && isNode(schema.items)) {
3732
+ value.forEach((item, i) => walk(item, schema.items, `${path}[${i}]`, issues));
3733
+ }
3734
+ const oneOf = schema.oneOf;
3735
+ if (Array.isArray(oneOf) && oneOf.length > 0) {
3736
+ const tagged = requiredTagOneOf(oneOf);
3737
+ if (tagged) {
3738
+ if (!isNode(value)) return void fail2(path, `${path} must be object`);
3739
+ const tag = hasOwn(value, tagged.discriminant) ? value[tagged.discriminant] : void 0;
3740
+ const matched = tagged.members.find((m) => m.tag === tag);
3741
+ if (!matched) {
3742
+ const expected = tagged.members.map((m) => JSON.stringify(m.tag)).join(", ");
3743
+ return void fail2(`${path}.${tagged.discriminant}`, `${path}.${tagged.discriminant} ${JSON.stringify(tag)} matches no case (expected one of ${expected})`);
3744
+ }
3745
+ return walk(value, matched.schema, path, issues);
3746
+ }
3747
+ const matching = oneOf.filter((member) => {
3748
+ const trial = [];
3749
+ walk(value, member, path, trial);
3750
+ return trial.length === 0;
3751
+ }).length;
3752
+ if (matching === 0) fail2(path, `${path} matches no member of oneOf`);
3753
+ if (matching > 1) fail2(path, `${path} matches more than one member of oneOf`);
3754
+ }
3755
+ }
3756
+ function validateDb3Json(schema, value) {
3757
+ const issues = [];
3758
+ walk(value, schema, "value", issues);
3759
+ return issues;
3760
+ }
3761
+ function bindDb3JsonFields(modelClass, fields) {
3762
+ const schema = modelClass.getSchema?.();
3763
+ const modelName = schema?.options?.name ?? modelClass.name ?? "model";
3764
+ const bound = bindings.get(modelClass) ?? /* @__PURE__ */ new Map();
3765
+ for (const [named, def] of Object.entries(fields)) {
3766
+ const field = storedNameOf(schema?.fieldNames, named);
3767
+ if (!def || typeof def.id !== "string" || !isNode(def.schema)) {
3768
+ throw new Error(`bindDb3JsonFields: ${modelName}.${field} needs a def's id and its compiled schema; regenerate schema-defs.generated.ts with \`primitive functions codegen\`.`);
3769
+ }
3770
+ const declared = schema?.fields?.get?.(field);
3771
+ if (schema?.fields && declared?.type !== "string") {
3772
+ throw new Error(
3773
+ `bindDb3JsonFields: ${modelName}.${field} is ${declared ? `a ${declared.type} field` : "not declared"}; a JSON field is stored in a string field. Regenerate the models with js-bao-codegen-v2.`
3774
+ );
3775
+ }
3776
+ bound.set(field, { id: def.id, schema: def.schema });
3777
+ }
3778
+ bindings.set(modelClass, bound);
3779
+ }
3780
+ function db3JsonDefOf(modelClass, field) {
3781
+ for (let at = modelClass; at && at !== Function.prototype; at = Object.getPrototypeOf(at)) {
3782
+ const def = bindings.get(at)?.get(field);
3783
+ if (def) return def;
3784
+ }
3785
+ return void 0;
3786
+ }
3787
+ function db3JsonText(record, field) {
3788
+ const model = record;
3789
+ if (!db3JsonDefOf(model.constructor, field)) {
3790
+ const name = model.constructor?.getSchema?.()?.options?.name ?? model.constructor?.name ?? "model";
3791
+ throw new Error(`${name}.${field} is not a JSON field: db3JsonText reads a field bound to a schemas/ object def.`);
3792
+ }
3793
+ const stored = model.hasFieldChanged(field) ? model._localChanges?.[field] : model.getOriginalValue(field);
3794
+ return stored === null || stored === void 0 ? stored : String(stored);
3795
+ }
3796
+ function storeDb3JsonFields(record, data, fields) {
3797
+ for (const [field, options] of fields) {
3798
+ if (options?.type !== "string" || !db3JsonDefOf(record.constructor, field)) continue;
3799
+ const stored = db3JsonText(record, field);
3800
+ if (stored === void 0) delete data[field];
3801
+ else data[field] = stored;
3802
+ }
3803
+ }
3804
+ function encodeDb3JsonField(model, field, def, value) {
3805
+ if (value === null || value === void 0) return value;
3806
+ const encoded = canonicalDb3Json(value);
3807
+ if (!encoded.ok) throw new Db3JsonValueError({ model, field, def: def.id, path: encoded.path, reason: encoded.reason, kind: encoded.kind });
3808
+ const issues = validateDb3Json(def.schema, JSON.parse(encoded.text));
3809
+ if (issues.length > 0) {
3810
+ throw new Db3JsonValueError({ model, field, def: def.id, path: issues[0].path, reason: issues.map((issue) => issue.message).join("; "), kind: "schema" });
3811
+ }
3812
+ return encoded.text;
3813
+ }
3814
+ function deepFreeze(value) {
3815
+ if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
3816
+ for (const child of Object.values(value)) deepFreeze(child);
3817
+ Object.freeze(value);
3818
+ }
3819
+ return value;
3820
+ }
3821
+ function readDb3JsonField(model, field, stored) {
3822
+ if (stored === null || stored === void 0) return stored;
3823
+ if (typeof stored === "string") {
3824
+ if (decoded.has(stored)) return decoded.get(stored);
3825
+ let value;
3826
+ try {
3827
+ value = JSON.parse(stored);
3828
+ } catch {
3829
+ value = void 0;
3830
+ }
3831
+ if (isNode(value)) {
3832
+ deepFreeze(value);
3833
+ if (decoded.size >= DECODED_CACHE) decoded.delete(decoded.keys().next().value);
3834
+ decoded.set(stored, value);
3835
+ return value;
3836
+ }
3837
+ }
3838
+ const key = `${model}\0${field}`;
3839
+ if (!misreadFields.has(key)) {
3840
+ misreadFields.add(key);
3841
+ console.warn(`[js-bao] ${model}.${field}: a stored value is not JSON text of an object; it reads as undefined (its text stays readable through db3JsonText(record, "${field}"))`);
3842
+ }
3843
+ return void 0;
3844
+ }
3845
+ var Db3JsonValueError, Refusal, MAX_EXACT, isNode, hasOwn, isScalarTag, ONE_OF_SIBLINGS, bindings, misreadFields, decoded, DECODED_CACHE;
3846
+ var init_jsonFields = __esm({
3847
+ "src/models/jsonFields.ts"() {
3848
+ "use strict";
3849
+ init_fieldNames();
3850
+ Db3JsonValueError = class _Db3JsonValueError extends Error {
3851
+ code = "DB3_JSON_INVALID";
3852
+ model;
3853
+ field;
3854
+ def;
3855
+ path;
3856
+ reason;
3857
+ kind;
3858
+ constructor(details) {
3859
+ super(`${details.model}.${details.field} is typed by ${details.def}: ${details.reason}`);
3860
+ this.name = "Db3JsonValueError";
3861
+ this.model = details.model;
3862
+ this.field = details.field;
3863
+ this.def = details.def;
3864
+ this.path = details.path;
3865
+ this.reason = details.reason;
3866
+ this.kind = details.kind;
3867
+ Object.setPrototypeOf(this, _Db3JsonValueError.prototype);
3868
+ }
3869
+ };
3870
+ Refusal = class {
3871
+ constructor(kind, path, reason) {
3872
+ this.kind = kind;
3873
+ this.path = path;
3874
+ this.reason = reason;
3875
+ }
3876
+ };
3877
+ MAX_EXACT = 2 ** 53;
3878
+ isNode = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3879
+ hasOwn = (value, key) => value !== null && value !== void 0 && Object.prototype.hasOwnProperty.call(value, key);
3880
+ isScalarTag = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
3881
+ ONE_OF_SIBLINGS = ["type", "properties", "required", "additionalProperties", "items", "enum"];
3882
+ bindings = /* @__PURE__ */ new WeakMap();
3883
+ misreadFields = /* @__PURE__ */ new Set();
3884
+ decoded = /* @__PURE__ */ new Map();
3885
+ DECODED_CACHE = 256;
3886
+ }
3887
+ });
3888
+
3243
3889
  // src/query/indexPlacement.ts
3244
3890
  function findNearOperator(filter) {
3245
3891
  const seen = /* @__PURE__ */ new Set();
3246
- const walk = (value) => {
3892
+ const walk2 = (value) => {
3247
3893
  if (value === null || typeof value !== "object" || seen.has(value)) return null;
3248
3894
  seen.add(value);
3249
3895
  if (Array.isArray(value)) {
3250
3896
  for (const member of value) {
3251
- const found = walk(member);
3897
+ const found = walk2(member);
3252
3898
  if (found) return found;
3253
3899
  }
3254
3900
  return null;
@@ -3258,12 +3904,12 @@ function findNearOperator(filter) {
3258
3904
  const field = member?.field;
3259
3905
  return { field: typeof field === "string" ? field : null };
3260
3906
  }
3261
- const found = walk(member);
3907
+ const found = walk2(member);
3262
3908
  if (found) return found;
3263
3909
  }
3264
3910
  return null;
3265
3911
  };
3266
- return walk(filter);
3912
+ return walk2(filter);
3267
3913
  }
3268
3914
  function findNearInRead(model, filter, include) {
3269
3915
  const near = findNearOperator(filter);
@@ -3608,7 +4254,7 @@ var init_vectorIndex = __esm({
3608
4254
 
3609
4255
  // src/query/nearSearch.ts
3610
4256
  function hasNear(filter) {
3611
- return isPlainObject2(filter) && Object.prototype.hasOwnProperty.call(filter, "$near");
4257
+ return isPlainObject3(filter) && Object.prototype.hasOwnProperty.call(filter, "$near");
3612
4258
  }
3613
4259
  function parseNearRead(filter, include) {
3614
4260
  if (findNearInRead("", void 0, include)) throw nested();
@@ -3621,7 +4267,7 @@ function parseNearRead(filter, include) {
3621
4267
  throw new DocumentQueryError("$near is the only key of its filter: put the other conditions under $near.filter");
3622
4268
  }
3623
4269
  const near = outer.$near;
3624
- if (!isPlainObject2(near)) throw new DocumentQueryError("$near is { field, vector, k?, filter? }");
4270
+ if (!isPlainObject3(near)) throw new DocumentQueryError("$near is { field, vector, k?, filter? }");
3625
4271
  const extra = Object.keys(near).find((key) => !NEAR_KEYS.has(key));
3626
4272
  if (extra !== void 0) throw new DocumentQueryError(`$near takes field, vector, k and filter, not ${JSON.stringify(extra)}`);
3627
4273
  if (typeof near.field !== "string" || !IDENTIFIER.test(near.field)) throw new DocumentQueryError("$near.field must name the vector field");
@@ -3634,7 +4280,7 @@ function parseNearRead(filter, include) {
3634
4280
  throw new DocumentQueryError(`$near.k must be an integer from 1 to ${DB3_NEAR_MAX_K}`);
3635
4281
  }
3636
4282
  const inner = near.filter === void 0 ? {} : near.filter;
3637
- if (!isPlainObject2(inner)) throw new DocumentQueryError("$near.filter must be a filter object");
4283
+ if (!isPlainObject3(inner)) throw new DocumentQueryError("$near.filter must be a filter object");
3638
4284
  if (findNearInRead("", inner) || containsSearch(inner)) throw new DocumentQueryError("$near's filter takes neither $near nor $search");
3639
4285
  return { field: near.field, vector, k, filter: inner };
3640
4286
  }
@@ -3695,7 +4341,7 @@ function nearSubquery(read, viewTable, filterSql, filterParams = []) {
3695
4341
  params: [read.vector, read.vector, options, ...filterParams]
3696
4342
  };
3697
4343
  }
3698
- var DISTANCE_KEY, IDENTIFIER, NEAR_KEYS, isPlainObject2, nested, NearVectorInvalidError, quote, nearTieWindow;
4344
+ var DISTANCE_KEY, IDENTIFIER, NEAR_KEYS, isPlainObject3, nested, NearVectorInvalidError, quote, nearTieWindow;
3699
4345
  var init_nearSearch = __esm({
3700
4346
  "src/query/nearSearch.ts"() {
3701
4347
  "use strict";
@@ -3705,7 +4351,7 @@ var init_nearSearch = __esm({
3705
4351
  DISTANCE_KEY = "_distance";
3706
4352
  IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
3707
4353
  NEAR_KEYS = /* @__PURE__ */ new Set(["field", "vector", "k", "filter"]);
3708
- isPlainObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !ArrayBuffer.isView(value);
4354
+ isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !ArrayBuffer.isView(value);
3709
4355
  nested = () => new DocumentQueryError("$near is allowed only at the top level of a query's filter: it is the filter's only key, its other conditions under $near.filter");
3710
4356
  NearVectorInvalidError = class _NearVectorInvalidError extends DocumentQueryError {
3711
4357
  /** Always `DB3_VECTOR_INVALID`. */
@@ -4553,7 +5199,7 @@ var init_reservedFields = __esm({
4553
5199
  // src/record-log/textIndex.ts
4554
5200
  function parseTextIndexOptions(fields, raw) {
4555
5201
  if (raw === void 0) raw = {};
4556
- if (!isPlainObject3(raw)) throw new TextIndexOptionsError("text options must be an object: { tokenizer?, prefix?, weights? }", "text");
5202
+ if (!isPlainObject4(raw)) throw new TextIndexOptionsError("text options must be an object: { tokenizer?, prefix?, weights? }", "text");
4557
5203
  const unknown = Object.keys(raw).find((key) => !OPTION_KEYS.includes(key));
4558
5204
  if (unknown !== void 0) {
4559
5205
  throw new TextIndexOptionsError(`text.${unknown} is not a text index option: give tokenizer, prefix or weights`, unknown);
@@ -4570,7 +5216,7 @@ function parseTextIndexOptions(fields, raw) {
4570
5216
  );
4571
5217
  }
4572
5218
  const given = raw.weights ?? {};
4573
- if (!isPlainObject3(given)) throw new TextIndexOptionsError("text.weights must be an object of field: weight", "weights");
5219
+ if (!isPlainObject4(given)) throw new TextIndexOptionsError("text.weights must be an object of field: weight", "weights");
4574
5220
  for (const [field, weight] of Object.entries(given)) {
4575
5221
  if (!fields.includes(field)) {
4576
5222
  throw new TextIndexOptionsError(`text.weights.${field} names a field the index does not cover: ${fields.join(", ")}`, "weights");
@@ -4595,7 +5241,7 @@ function textTokenize(tokenizer) {
4595
5241
  function textTableDDL(table, fields, options) {
4596
5242
  const columns = fields.map((_, i) => textColumnAlias(i));
4597
5243
  const prefix = options.prefix.length > 0 ? `, prefix='${options.prefix.join(" ")}'` : "";
4598
- return `CREATE VIRTUAL TABLE ${quoted(table)} USING fts5(${columns.join(", ")}, content='', tokenize='${textTokenize(options.tokenizer)}'${prefix})`;
5244
+ return `CREATE VIRTUAL TABLE ${quoted2(table)} USING fts5(${columns.join(", ")}, content='', tokenize='${textTokenize(options.tokenizer)}'${prefix})`;
4599
5245
  }
4600
5246
  function textValueSql(row, fields) {
4601
5247
  return fields.map((field) => {
@@ -4604,12 +5250,12 @@ function textValueSql(row, fields) {
4604
5250
  });
4605
5251
  }
4606
5252
  function textInsertSql(table, fields) {
4607
- return `INSERT INTO ${quoted(table)} (${["rowid", ...fields.map((_, i) => textColumnAlias(i))].join(", ")})`;
5253
+ return `INSERT INTO ${quoted2(table)} (${["rowid", ...fields.map((_, i) => textColumnAlias(i))].join(", ")})`;
4608
5254
  }
4609
5255
  function textDeleteSql(table, fields) {
4610
- return `INSERT INTO ${quoted(table)} (${[quoted(table), "rowid", ...fields.map((_, i) => textColumnAlias(i))].join(", ")})`;
5256
+ return `INSERT INTO ${quoted2(table)} (${[quoted2(table), "rowid", ...fields.map((_, i) => textColumnAlias(i))].join(", ")})`;
4611
5257
  }
4612
- var TEXT_INDEX_TOKENIZERS, TEXT_INDEX_MAX_PREFIXES, TEXT_INDEX_MAX_PREFIX_LENGTH, OPTION_KEYS, TextIndexOptionsError, isPlainObject3, quoted, literal2;
5258
+ var TEXT_INDEX_TOKENIZERS, TEXT_INDEX_MAX_PREFIXES, TEXT_INDEX_MAX_PREFIX_LENGTH, OPTION_KEYS, TextIndexOptionsError, isPlainObject4, quoted2, literal2;
4613
5259
  var init_textIndex = __esm({
4614
5260
  "src/record-log/textIndex.ts"() {
4615
5261
  "use strict";
@@ -4624,8 +5270,8 @@ var init_textIndex = __esm({
4624
5270
  this.name = "TextIndexOptionsError";
4625
5271
  }
4626
5272
  };
4627
- isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4628
- quoted = (name) => `"${name.replace(/"/g, '""')}"`;
5273
+ isPlainObject4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5274
+ quoted2 = (name) => `"${name.replace(/"/g, '""')}"`;
4629
5275
  literal2 = (text) => `'${text.replace(/'/g, "''")}'`;
4630
5276
  }
4631
5277
  });
@@ -4681,7 +5327,7 @@ function textColumnsOf(fields) {
4681
5327
  return fields.map((field, i) => ({ field, alias: textColumnAlias(i) }));
4682
5328
  }
4683
5329
  function matchExpression(search, indexFields) {
4684
- const terms = search.terms.map((term) => quoted2(term.text) + (search.prefix ? "*" : ""));
5330
+ const terms = search.terms.map((term) => quoted3(term.text) + (search.prefix ? "*" : ""));
4685
5331
  const joined = terms.join(search.mode === "any" ? " OR " : " AND ");
4686
5332
  if (search.fields === null) return joined;
4687
5333
  const columns = textColumnsOf(indexFields);
@@ -4690,11 +5336,11 @@ function matchExpression(search, indexFields) {
4690
5336
  if (!column) {
4691
5337
  throw new DocumentQueryError(`$search.fields names ${field}, which the text index does not cover: ${indexFields.join(", ")}`);
4692
5338
  }
4693
- return quoted2(column.alias);
5339
+ return quoted3(column.alias);
4694
5340
  });
4695
5341
  return `{${selected.join(" ")}} : (${joined})`;
4696
5342
  }
4697
- var SEARCH_KEYS, TOKEN_CHARACTER, quoted2;
5343
+ var SEARCH_KEYS, TOKEN_CHARACTER, quoted3;
4698
5344
  var init_textSearch = __esm({
4699
5345
  "src/query/textSearch.ts"() {
4700
5346
  "use strict";
@@ -4702,7 +5348,7 @@ var init_textSearch = __esm({
4702
5348
  init_textIndex();
4703
5349
  SEARCH_KEYS = ["query", "mode", "prefix", "fields"];
4704
5350
  TOKEN_CHARACTER = /[\p{L}\p{N}\p{Co}]/u;
4705
- quoted2 = (text) => `"${text.replace(/"/g, '""')}"`;
5351
+ quoted3 = (text) => `"${text.replace(/"/g, '""')}"`;
4706
5352
  }
4707
5353
  });
4708
5354
 
@@ -4723,19 +5369,19 @@ function parseRecordRow(row) {
4723
5369
  return { id: _id, type: _type, ...parsed, ...decodeProjectedColumns(rest) };
4724
5370
  }
4725
5371
  function decodeProjectedColumns(columns) {
4726
- const decoded = {};
5372
+ const decoded2 = {};
4727
5373
  for (const [column, value] of Object.entries(columns)) {
4728
5374
  if (column.startsWith(CURSOR_SORT_ALIAS_PREFIX)) {
4729
- decoded[column] = parseJsonColumn(value);
5375
+ decoded2[column] = parseJsonColumn(value);
4730
5376
  continue;
4731
5377
  }
4732
5378
  if (!column.startsWith(PROJECTED_JSON_ALIAS_PREFIX)) {
4733
- decoded[column] = value;
5379
+ decoded2[column] = value;
4734
5380
  continue;
4735
5381
  }
4736
- decoded[column.slice(PROJECTED_JSON_ALIAS_PREFIX.length)] = parseJsonColumn(value);
5382
+ decoded2[column.slice(PROJECTED_JSON_ALIAS_PREFIX.length)] = parseJsonColumn(value);
4737
5383
  }
4738
- return decoded;
5384
+ return decoded2;
4739
5385
  }
4740
5386
  function parseJsonColumn(value) {
4741
5387
  if (typeof value !== "string") return value;
@@ -4755,7 +5401,7 @@ var init_recordRow = __esm({
4755
5401
  });
4756
5402
 
4757
5403
  // src/query/JsonQueryTranslator.ts
4758
- var SYSTEM_FIELDS2, QUERY_IN_LIST_MAX_VALUES, QUERY_STATEMENT_MAX_BOUND_PARAMS, SEARCH_ALIAS, SCORE_KEY, NEAR_ALIAS, JsonQueryTranslator;
5404
+ var SYSTEM_FIELDS2, QUERY_IN_LIST_MAX_VALUES, QUERY_STATEMENT_MAX_BOUND_PARAMS, UNSET_PATH, SEARCH_ALIAS, SCORE_KEY, NEAR_ALIAS, JsonQueryTranslator;
4759
5405
  var init_JsonQueryTranslator = __esm({
4760
5406
  "src/query/JsonQueryTranslator.ts"() {
4761
5407
  "use strict";
@@ -4771,6 +5417,7 @@ var init_JsonQueryTranslator = __esm({
4771
5417
  SYSTEM_FIELDS2 = /* @__PURE__ */ new Set(["id", "type"]);
4772
5418
  QUERY_IN_LIST_MAX_VALUES = 1e3;
4773
5419
  QUERY_STATEMENT_MAX_BOUND_PARAMS = 100;
5420
+ UNSET_PATH = "$._unset";
4774
5421
  SEARCH_ALIAS = "_search";
4775
5422
  SCORE_KEY = "_score";
4776
5423
  NEAR_ALIAS = "_near";
@@ -4868,7 +5515,7 @@ var init_JsonQueryTranslator = __esm({
4868
5515
  assertValidIdentifier(fieldName, "query field");
4869
5516
  this.fieldSqlCache.set(
4870
5517
  fieldName,
4871
- `json_extract(_data, '$.${fieldName}')`
5518
+ `json_extract(_data, ${this.dataPathLiteral(fieldName)})`
4872
5519
  );
4873
5520
  }
4874
5521
  }
@@ -5532,8 +6179,7 @@ var init_JsonQueryTranslator = __esm({
5532
6179
  if (SYSTEM_FIELDS2.has(fieldName)) {
5533
6180
  return `${this.table}.${quoteIdentifier(`_${fieldName}`)}`;
5534
6181
  }
5535
- assertValidIdentifier(fieldName, "query field");
5536
- return `json_extract(${this.table}._data, '$.${fieldName}')`;
6182
+ return `json_extract(${this.table}._data, ${this.dataPathLiteral(fieldName)})`;
5537
6183
  }
5538
6184
  /**
5539
6185
  * A membership condition over the array a record holds in `fieldName`
@@ -5550,7 +6196,7 @@ var init_JsonQueryTranslator = __esm({
5550
6196
  }
5551
6197
  /** The member index `fieldName`'s members are read from, or `null` (#5150). */
5552
6198
  memberIndexOf(fieldName) {
5553
- if (SYSTEM_FIELDS2.has(fieldName)) return null;
6199
+ if (SYSTEM_FIELDS2.has(fieldName) || this.options.unsetFields?.has(fieldName)) return null;
5554
6200
  return this.options.memberIndexTable?.(fieldName) ?? null;
5555
6201
  }
5556
6202
  /**
@@ -5562,12 +6208,32 @@ var init_JsonQueryTranslator = __esm({
5562
6208
  }
5563
6209
  /** `<table>._data, '$.<field>'`: the arguments that address a field's stored JSON. */
5564
6210
  dataPathSql(fieldName) {
5565
- return `${this.table}._data, '${this.dataPath(fieldName)}'`;
6211
+ return `${this.table}._data, ${this.dataPathLiteral(fieldName)}`;
5566
6212
  }
5567
- /** `$.<field>`: the JSON path of a field in `_data`. */
6213
+ /**
6214
+ * `$.<field>`: the JSON path of a field in `_data`, as a bound value. A
6215
+ * field unset only in some documents is bound at its stored path: each such
6216
+ * site sits behind a {@link dataPathLiteral} guard that reads it as unset
6217
+ * in those documents.
6218
+ */
5568
6219
  dataPath(fieldName) {
5569
6220
  assertValidIdentifier(fieldName, "query field");
5570
- return `$.${fieldName}`;
6221
+ if (!this.options.unsetFields?.has(fieldName)) return `$.${fieldName}`;
6222
+ return this.options.unsetFieldDocuments?.has(fieldName) ? `$.${fieldName}` : UNSET_PATH;
6223
+ }
6224
+ /**
6225
+ * The JSON path of a field in `_data` as SQL: the quoted path, or, for a
6226
+ * field unset in some documents only, a `CASE` on the row's document that
6227
+ * picks the unset path in those. Any other field's SQL is unchanged.
6228
+ */
6229
+ dataPathLiteral(fieldName) {
6230
+ assertValidIdentifier(fieldName, "query field");
6231
+ const documents = this.options.unsetFields?.has(fieldName) ? this.options.unsetFieldDocuments?.get(fieldName) : void 0;
6232
+ if (!documents) return `'${this.dataPath(fieldName)}'`;
6233
+ if (!documents.length) return `'$.${fieldName}'`;
6234
+ const column = `${this.table}.${quoteIdentifier(this.documentColumn)}`;
6235
+ const ids = documents.map((id) => `'${String(id).replace(/'/g, "''")}'`).join(", ");
6236
+ return `(CASE WHEN ${column} IN (${ids}) THEN '${UNSET_PATH}' ELSE '$.${fieldName}' END)`;
5571
6237
  }
5572
6238
  /**
5573
6239
  * Translate field condition to SQL
@@ -5824,10 +6490,10 @@ var init_JsonQueryTranslator = __esm({
5824
6490
  return value ? { sql: `${fieldSql} IS NOT NULL`, params: [] } : { sql: `${fieldSql} IS NULL`, params: [] };
5825
6491
  } else {
5826
6492
  return value ? {
5827
- sql: `json_type(_data, '$.${fieldName}') IS NOT NULL`,
6493
+ sql: `json_type(_data, ${this.dataPathLiteral(fieldName)}) IS NOT NULL`,
5828
6494
  params: []
5829
6495
  } : {
5830
- sql: `json_type(_data, '$.${fieldName}') IS NULL`,
6496
+ sql: `json_type(_data, ${this.dataPathLiteral(fieldName)}) IS NULL`,
5831
6497
  params: []
5832
6498
  };
5833
6499
  }
@@ -5964,13 +6630,12 @@ var init_JsonQueryTranslator = __esm({
5964
6630
  for (const field of includeFields) {
5965
6631
  if (field === "id" || field === "type") continue;
5966
6632
  selectParts.push(
5967
- `_data -> '$.${field}' AS ${quoteIdentifier(projectedJsonAlias(field))}`
6633
+ `_data -> ${this.dataPathLiteral(field)} AS ${quoteIdentifier(projectedJsonAlias(field))}`
5968
6634
  );
5969
6635
  }
5970
6636
  for (const field of aliasedSortFields ?? []) {
5971
- assertValidIdentifier(field, "query field");
5972
6637
  selectParts.push(
5973
- `_data -> '$.${field}' AS ${quoteIdentifier(cursorSortAlias(field))}`
6638
+ `_data -> ${this.dataPathLiteral(field)} AS ${quoteIdentifier(cursorSortAlias(field))}`
5974
6639
  );
5975
6640
  }
5976
6641
  return selectParts.join(", ");
@@ -6234,12 +6899,13 @@ var init_JsonQueryTranslator = __esm({
6234
6899
  });
6235
6900
 
6236
6901
  // src/record-log-client/condition.ts
6237
- function conditionTranslator(model) {
6902
+ function conditionTranslator(model, unsetFields) {
6238
6903
  return new JsonQueryTranslator(model, void 0, {
6239
6904
  includeDocId: false,
6240
6905
  table: CONDITION_TABLE,
6241
6906
  stringSets: "json_each",
6242
- setArraysInData: true
6907
+ setArraysInData: true,
6908
+ ...unsetFields?.size ? { unsetFields } : {}
6243
6909
  });
6244
6910
  }
6245
6911
  function sqlText(value) {
@@ -6256,14 +6922,14 @@ function conditionProblem(condition) {
6256
6922
  return `condition: ${error instanceof Error ? error.message : String(error)}`;
6257
6923
  }
6258
6924
  }
6259
- function conditionHolds(sql, model, id, row, condition) {
6260
- const { sql: where2, params } = conditionTranslator(model).translateFilter(condition);
6925
+ function conditionHolds(sql, model, id, row, condition, unsetFields) {
6926
+ const { sql: where2, params } = conditionTranslator(model, unsetFields).translateFilter(condition);
6261
6927
  const query = `WITH ${CONDITION_TABLE}(_id, _type, _data) AS (SELECT ${sqlText(id)}, ${sqlText(model)}, ?) SELECT 1 AS hit FROM ${CONDITION_TABLE}${where2 ? ` WHERE ${where2}` : ""}`;
6262
6928
  const [hit] = [...sql.exec(query, JSON.stringify(row), ...params)];
6263
6929
  return hit !== void 0;
6264
6930
  }
6265
- function storedConditionHolds(sql, model, id, condition) {
6266
- const { sql: where2, params } = conditionTranslator(model).translateFilter(condition);
6931
+ function storedConditionHolds(sql, model, id, condition, unsetFields) {
6932
+ const { sql: where2, params } = conditionTranslator(model, unsetFields).translateFilter(condition);
6267
6933
  const query = `WITH ${CONDITION_TABLE}(_id, _type, _data) AS (SELECT _id, _type, _data FROM records WHERE _type = ${sqlText(model)} AND _id = ${sqlText(id)} AND _dead = 0) SELECT 1 AS hit FROM ${CONDITION_TABLE}${where2 ? ` WHERE ${where2}` : ""}`;
6268
6934
  const [hit] = [...sql.exec(query, ...params)];
6269
6935
  return hit !== void 0;
@@ -6304,7 +6970,7 @@ var init_types = __esm({
6304
6970
  RECORD_LOG_UP_BATCH_MAX = 200;
6305
6971
  RECORD_LOG_FRAME_ENTRIES_MAX = 64;
6306
6972
  RECORD_LOG_FIRST_EPOCH = 1;
6307
- RECORD_LOG_WIRE_VERSION = 4;
6973
+ RECORD_LOG_WIRE_VERSION = 5;
6308
6974
  RecordLogStaleReceiptError = class _RecordLogStaleReceiptError extends Error {
6309
6975
  /**
6310
6976
  * @param attempt - The attempt the command carried.
@@ -6473,12 +7139,12 @@ function mergeRecordLogMutations(earlier, later) {
6473
7139
  const fields = { ...earlier.fields ?? {}, ...later.fields ?? {} };
6474
7140
  const stringSetDeltas = {};
6475
7141
  for (const [field, delta] of Object.entries(earlier.stringSetDeltas ?? {})) {
6476
- if (later.fields && hasOwn(later.fields, field)) continue;
7142
+ if (later.fields && hasOwn2(later.fields, field)) continue;
6477
7143
  stringSetDeltas[field] = Object.assign(memberMap(), delta);
6478
7144
  }
6479
7145
  for (const [field, delta] of Object.entries(later.stringSetDeltas ?? {})) {
6480
7146
  delete fields[field];
6481
- const merged = Object.assign(memberMap(), hasOwn(stringSetDeltas, field) ? stringSetDeltas[field] : {}, delta);
7147
+ const merged = Object.assign(memberMap(), hasOwn2(stringSetDeltas, field) ? stringSetDeltas[field] : {}, delta);
6482
7148
  if (kind === "create") {
6483
7149
  for (const [member, present] of Object.entries(merged)) if (!present) delete merged[member];
6484
7150
  }
@@ -6533,9 +7199,9 @@ function planRecordLogRecordWrite(input) {
6533
7199
  }
6534
7200
  const op = value;
6535
7201
  const delta = memberMap();
6536
- const held = existing && hasOwn(existing, key) && isStringArray(existing[key]) ? existing[key] : [];
7202
+ const held2 = existing && hasOwn2(existing, key) && isStringArray(existing[key]) ? existing[key] : [];
6537
7203
  if (kind === "patch") {
6538
- if (op.$clear === true) for (const member of held) delta[member] = false;
7204
+ if (op.$clear === true) for (const member of held2) delta[member] = false;
6539
7205
  for (const member of op.$remove ?? []) delta[member] = false;
6540
7206
  }
6541
7207
  for (const member of op.$add ?? []) delta[member] = true;
@@ -6564,41 +7230,41 @@ function planRecordLogDelete(model, recordId, condition) {
6564
7230
  function planRecordLogIncrement(model, recordId, fields, condition) {
6565
7231
  return { model, id: recordId, kind: "increment", fields: { ...fields }, ...guardsOf({ condition }) };
6566
7232
  }
6567
- function foldRecordLogIncrement(held, next) {
7233
+ function foldRecordLogIncrement(held2, next) {
6568
7234
  if (next.kind !== "increment") {
6569
- const mutation2 = held.mutation ? mergeRecordLogMutations(held.mutation, next) : next;
7235
+ const mutation2 = held2.mutation ? mergeRecordLogMutations(held2.mutation, next) : next;
6570
7236
  const named = /* @__PURE__ */ new Set([...Object.keys(next.fields ?? {}), ...Object.keys(next.stringSetDeltas ?? {})]);
6571
- const left = next.kind === "patch" && held.increment ? Object.entries(held.increment.fields ?? {}).filter(([field]) => !named.has(field)) : [];
7237
+ const left = next.kind === "patch" && held2.increment ? Object.entries(held2.increment.fields ?? {}).filter(([field]) => !named.has(field)) : [];
6572
7238
  if (left.length) {
6573
- return { mutation: mutation2, increment: { ...held.increment, fields: Object.fromEntries(left) } };
7239
+ return { mutation: mutation2, increment: { ...held2.increment, fields: Object.fromEntries(left) } };
6574
7240
  }
6575
- const dropped = held.increment?.condition;
7241
+ const dropped = held2.increment?.condition;
6576
7242
  return { mutation: dropped === void 0 ? mutation2 : { ...mutation2, ...conjoined(mutation2.condition, dropped) } };
6577
7243
  }
6578
- const absolute = held.mutation && held.mutation.kind !== "delete" ? held.mutation : void 0;
7244
+ const absolute = held2.mutation && held2.mutation.kind !== "delete" ? held2.mutation : void 0;
6579
7245
  const intoAbsolute = {};
6580
- const deltas = { ...held.increment?.fields ?? {} };
7246
+ const deltas = { ...held2.increment?.fields ?? {} };
6581
7247
  let accumulated = false;
6582
7248
  for (const [field, delta] of Object.entries(next.fields ?? {})) {
6583
- if (absolute && (absolute.kind === "create" || hasOwn(absolute.fields ?? {}, field))) {
7249
+ if (absolute && (absolute.kind === "create" || hasOwn2(absolute.fields ?? {}, field))) {
6584
7250
  intoAbsolute[field] = numericOf(absolute.fields?.[field]) + delta;
6585
7251
  } else {
6586
7252
  deltas[field] = (deltas[field] ?? 0) + delta;
6587
7253
  accumulated = true;
6588
7254
  }
6589
7255
  }
6590
- let mutation = held.mutation;
7256
+ let mutation = held2.mutation;
6591
7257
  if (absolute && Object.keys(intoAbsolute).length) {
6592
7258
  mutation = { ...absolute, fields: { ...absolute.fields ?? {}, ...intoAbsolute } };
6593
7259
  if (!accumulated) mutation = { ...mutation, ...conjoined(absolute.condition, next.condition) };
6594
7260
  }
6595
- if (!accumulated && !held.increment) return { ...mutation ? { mutation } : {} };
6596
- const { condition: _condition, ...base } = held.increment ?? next;
7261
+ if (!accumulated && !held2.increment) return { ...mutation ? { mutation } : {} };
7262
+ const { condition: _condition, ...base } = held2.increment ?? next;
6597
7263
  const increment = {
6598
7264
  ...base,
6599
7265
  kind: "increment",
6600
7266
  fields: deltas,
6601
- ...conjoined(held.increment?.condition, accumulated ? next.condition : void 0)
7267
+ ...conjoined(held2.increment?.condition, accumulated ? next.condition : void 0)
6602
7268
  };
6603
7269
  return { ...mutation ? { mutation } : {}, increment };
6604
7270
  }
@@ -6636,7 +7302,7 @@ function ruleProblem(m) {
6636
7302
  const deltas = Object.entries(m.fields ?? {});
6637
7303
  if (!deltas.length) return "an increment names no field";
6638
7304
  if (m.stringSetDeltas !== void 0) return "an increment carries no stringSetDeltas";
6639
- if (hasOwn(m.fields, "id")) return "an increment cannot change id";
7305
+ if (hasOwn2(m.fields, "id")) return "an increment cannot change id";
6640
7306
  for (const [name, delta] of deltas) {
6641
7307
  const problem = identifierProblem("field", name);
6642
7308
  if (problem) return `${problem}. Rename the field`;
@@ -6745,7 +7411,7 @@ function assertRecordLogEntry(documentId, mutations, report, options = {}) {
6745
7411
  report?.({ documentId, model: first.model, recordId: first.id, error, writes });
6746
7412
  throw error;
6747
7413
  }
6748
- var membersOf, isStringArray, memberMap, hasOwn, numericOf;
7414
+ var membersOf, isStringArray, memberMap, hasOwn2, numericOf;
6749
7415
  var init_write = __esm({
6750
7416
  "src/record-log-client/write.ts"() {
6751
7417
  "use strict";
@@ -6756,7 +7422,7 @@ var init_write = __esm({
6756
7422
  membersOf = (value) => value ? Array.from(value) : [];
6757
7423
  isStringArray = (value) => Array.isArray(value) && valueKind(value) === "stringset";
6758
7424
  memberMap = () => /* @__PURE__ */ Object.create(null);
6759
- hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
7425
+ hasOwn2 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
6760
7426
  numericOf = (value) => typeof value === "number" ? value : 0;
6761
7427
  }
6762
7428
  });
@@ -7066,9 +7732,9 @@ var init_guess = __esm({
7066
7732
  if (!text.startsWith(prefix)) continue;
7067
7733
  const id = text.slice(prefix.length);
7068
7734
  if (excluding.includes(id)) continue;
7069
- const held = fields.map((field) => row[field]);
7070
- if (held.some((v) => v === void 0 || v === null)) continue;
7071
- if (JSON.stringify(held) === wanted2) return id;
7735
+ const held2 = fields.map((field) => row[field]);
7736
+ if (held2.some((v) => v === void 0 || v === null)) continue;
7737
+ if (JSON.stringify(held2) === wanted2) return id;
7072
7738
  }
7073
7739
  return null;
7074
7740
  }
@@ -8622,6 +9288,76 @@ function whenIndexedCallSite(stack) {
8622
9288
  const outside = frames.find((frame) => !JS_BAO_FRAME.test(frame));
8623
9289
  return outside ? outside.slice(3) : stack;
8624
9290
  }
9291
+ function heldRevisionClears(instance, fieldKey) {
9292
+ const modelConstructor = instance.constructor;
9293
+ const store = modelConstructor.recordViewFor(instance.getDocumentId());
9294
+ if (!store?.declaredCleared) return false;
9295
+ const modelName = modelConstructor.getSchema()?.options?.name;
9296
+ return store.declaredCleared()?.[modelName]?.includes(fieldKey) === true;
9297
+ }
9298
+ function modelNamesOf(modelClass, model, own3) {
9299
+ return (name) => {
9300
+ if (name === model) return own3 ?? void 0;
9301
+ let registry;
9302
+ try {
9303
+ registry = resolveOrmContext(modelClass).modelRegistry;
9304
+ } catch {
9305
+ registry = void 0;
9306
+ }
9307
+ return fieldNamesOfClass(registry?.getModelClass?.(name)) ?? void 0;
9308
+ };
9309
+ }
9310
+ function storedQueryOptions(namesOf, model, options) {
9311
+ if (!options) return options;
9312
+ const map = namesOf(model);
9313
+ const out = { ...options };
9314
+ if (options.sort !== void 0) out.sort = toStoredKeys(map, options.sort);
9315
+ if (options.projection !== void 0) out.projection = toStoredKeys(map, options.projection);
9316
+ if (options.include !== void 0) out.include = toStoredIncludes(namesOf, model, options.include);
9317
+ return out;
9318
+ }
9319
+ function currentRows(rows, namesOf, model, include) {
9320
+ const related = Array.isArray(include) && include.length > 0;
9321
+ let out = null;
9322
+ for (let i = 0; i < rows.length; i++) {
9323
+ const row = rows[i];
9324
+ let next = row;
9325
+ if (row instanceof BaseModel2) {
9326
+ const held2 = row._related;
9327
+ if (held2 && related) {
9328
+ row._related = toCurrentRow(namesOf, model, { _related: held2 }, include)._related;
9329
+ }
9330
+ } else {
9331
+ next = toCurrentRow(namesOf, model, row, include);
9332
+ }
9333
+ if (next !== row && out === null) out = rows.slice(0, i);
9334
+ if (out !== null) out.push(next);
9335
+ }
9336
+ return out ?? rows;
9337
+ }
9338
+ function currentPage(page, namesOf, model, include) {
9339
+ if (!page || !Array.isArray(page.data)) return page;
9340
+ const data = currentRows(page.data, namesOf, model, include);
9341
+ return data === page.data ? page : { ...page, data };
9342
+ }
9343
+ function uniqueConstraintNamed(schema, name) {
9344
+ const constraints = schema?.resolvedUniqueConstraints ?? [];
9345
+ const named = constraints.find((c) => c.name === name);
9346
+ if (named || !schema?.fieldNames) return named;
9347
+ const stored = storedNameOf(schema.fieldNames, name);
9348
+ if (stored === name && !Object.prototype.hasOwnProperty.call(schema.fieldNames.current, name)) return void 0;
9349
+ return constraints.find((c) => c.fields.length === 1 && c.fields[0] === stored);
9350
+ }
9351
+ function upsertConstraintNamed(schema, store, model, token) {
9352
+ const declared = schema?.resolvedUniqueConstraints ?? [];
9353
+ const found = declared.find((c) => c.name === token);
9354
+ if (found) return found;
9355
+ return (store?.marks().constraints ?? []).find((c) => c.model === model && c.name === token);
9356
+ }
9357
+ function currentFieldsOf(schema, fields) {
9358
+ const names = schema?.fieldNames;
9359
+ return names ? fields.map((field) => currentNameOf(names, field)) : [...fields];
9360
+ }
8625
9361
  var import_ulid2, FORMAT2_ROW_PAGE, UniqueConstraintViolationError, VectorFieldFormatError, RecordNotFoundError, SCHEMA_ACCESSORS_KEY, RecordLogTransactionGroup, activeRecordLogTransactions, unboundRecordLogTransaction, recordLogTransactionsOpen, JS_BAO_FRAME, BaseModel2;
8626
9362
  var init_BaseModel = __esm({
8627
9363
  "src/models/BaseModel.ts"() {
@@ -8646,9 +9382,11 @@ var init_BaseModel = __esm({
8646
9382
  init_fieldCoercion();
8647
9383
  init_vector();
8648
9384
  init_vectorFields();
9385
+ init_jsonFields();
8649
9386
  init_indexPlacement();
8650
9387
  init_nearSearch();
8651
9388
  init_OrmContext();
9389
+ init_fieldNames();
8652
9390
  init_write();
8653
9391
  init_declared_types();
8654
9392
  init_types();
@@ -8724,14 +9462,14 @@ var init_BaseModel = __esm({
8724
9462
  if (write.existing) table.set(mutation, { ...write.existing });
8725
9463
  applyGuess(table, { m: mutation });
8726
9464
  const row = table.row(mutation);
8727
- const held = writes.get(key);
8728
- if (held) {
8729
- held.held = foldRecordLogIncrement(held.held, mutation);
8730
- held.upsertOn ??= write.upsertOn;
8731
- if (write.instance) held.instances.add(write.instance);
8732
- if (write.modelClass) held.classes.add(write.modelClass);
8733
- held.entry.row = row;
8734
- return held.entry;
9465
+ const held2 = writes.get(key);
9466
+ if (held2) {
9467
+ held2.held = foldRecordLogIncrement(held2.held, mutation);
9468
+ held2.upsertOn ??= write.upsertOn;
9469
+ if (write.instance) held2.instances.add(write.instance);
9470
+ if (write.modelClass) held2.classes.add(write.modelClass);
9471
+ held2.entry.row = row;
9472
+ return held2.entry;
8735
9473
  }
8736
9474
  const entry = { model: mutation.model, id: mutation.id, row, loaded: true };
8737
9475
  writes.set(key, {
@@ -9091,11 +9829,11 @@ var init_BaseModel = __esm({
9091
9829
  if (field === "id" || field === "type" || schema.fields.has(field)) return;
9092
9830
  throw new InvalidFieldError(`Unknown field: ${field} in model ${modelName}`, field, modelName);
9093
9831
  };
9094
- const walk = (node) => {
9832
+ const walk2 = (node) => {
9095
9833
  if (!node || typeof node !== "object" || Array.isArray(node)) return;
9096
9834
  for (const [key, value] of Object.entries(node)) {
9097
9835
  if (key === "$and" || key === "$or") {
9098
- if (Array.isArray(value)) value.forEach(walk);
9836
+ if (Array.isArray(value)) value.forEach(walk2);
9099
9837
  } else if (key === "$near") {
9100
9838
  const near = parseNearRead({ $near: value });
9101
9839
  const declared = schema.fields.get(near.field);
@@ -9106,13 +9844,13 @@ var init_BaseModel = __esm({
9106
9844
  );
9107
9845
  }
9108
9846
  nearVectorBytes(near, modelName, typeof declared.dims === "number" ? declared.dims : null);
9109
- walk(near.filter);
9847
+ walk2(near.filter);
9110
9848
  } else if (key !== "$search") {
9111
9849
  check(key);
9112
9850
  }
9113
9851
  }
9114
9852
  };
9115
- walk(filter);
9853
+ walk2(filter);
9116
9854
  const searched = !!filter && Object.prototype.hasOwnProperty.call(filter, "$search");
9117
9855
  const nearing = !!filter && Object.prototype.hasOwnProperty.call(filter, "$near");
9118
9856
  for (const field of Object.keys(options?.sort ?? {})) {
@@ -9180,21 +9918,25 @@ var init_BaseModel = __esm({
9180
9918
  * A plain db3 row as the model API answers it: each declared string set the
9181
9919
  * row carries holds an array, `[]` for none, as an instance reads it, and
9182
9920
  * each vector field its numbers (#5225), with the encoding `vectors` (the
9183
- * row's db3's type) or the model declares; and the same, through
9921
+ * row's db3's type) or the model declares, and each JSON field its object
9922
+ * (#5899); and the same, through
9184
9923
  * `_related`, for every included row of a registered model, at every
9185
9924
  * depth. `own` false shapes only the related rows.
9186
9925
  */
9187
- static shapeDb3Row(row, modelName, includes, own2 = true, vectors = null) {
9926
+ static shapeDb3Row(row, modelName, includes, own3 = true, vectors = null) {
9188
9927
  const registry = resolveOrmContext(this).modelRegistry;
9189
9928
  const shape = (record, model, specs, self2) => {
9190
9929
  if (self2) {
9191
- const fields = registry?.getModelClass(model)?.getSchema?.()?.fields;
9930
+ const modelClass = registry?.getModelClass(model);
9931
+ const fields = modelClass?.getSchema?.()?.fields;
9192
9932
  for (const [field, options] of fields ?? []) {
9193
9933
  if (!Object.prototype.hasOwnProperty.call(record, field)) continue;
9194
9934
  if (options?.type === "stringset" && !Array.isArray(record[field])) {
9195
9935
  record[field] = [];
9196
9936
  } else if (options?.type === "vector") {
9197
9937
  record[field] = readVectorValue(model, field, record[field], vectorEncodingFor(vectors, model, field, options));
9938
+ } else if (options?.type === "string" && modelClass && db3JsonDefOf(modelClass, field)) {
9939
+ record[field] = readDb3JsonField(model, field, record[field]);
9198
9940
  }
9199
9941
  }
9200
9942
  }
@@ -9206,7 +9948,7 @@ var init_BaseModel = __esm({
9206
9948
  }
9207
9949
  return record;
9208
9950
  };
9209
- return shape(row, modelName, includes, own2);
9951
+ return shape(row, modelName, includes, own3);
9210
9952
  }
9211
9953
  /**
9212
9954
  * The documents an unscoped statement spans: every connected format-1
@@ -9363,8 +10105,10 @@ var init_BaseModel = __esm({
9363
10105
  static attachFieldAccessors(modelClass, fields) {
9364
10106
  const attached = _BaseModel.attachFieldAccessorsSet(modelClass);
9365
10107
  const prototype = modelClass.prototype;
9366
- for (const fieldName of fields.keys()) {
9367
- if (fieldName === "id") continue;
10108
+ const names = fieldNamesOfClass(modelClass);
10109
+ for (const storedName of fields.keys()) {
10110
+ if (storedName === "id") continue;
10111
+ const fieldName = currentNameOf(names, storedName);
9368
10112
  if (attached.has(fieldName)) continue;
9369
10113
  const existingDescriptor = Object.getOwnPropertyDescriptor(
9370
10114
  prototype,
@@ -9377,10 +10121,10 @@ var init_BaseModel = __esm({
9377
10121
  configurable: true,
9378
10122
  enumerable: true,
9379
10123
  get() {
9380
- return this.getValue(fieldName);
10124
+ return this.getValue(storedName);
9381
10125
  },
9382
10126
  set(value) {
9383
- this.setValue(fieldName, value);
10127
+ this.setValue(storedName, value);
9384
10128
  }
9385
10129
  });
9386
10130
  attached.add(fieldName);
@@ -9408,6 +10152,7 @@ var init_BaseModel = __esm({
9408
10152
  schema.fields
9409
10153
  );
9410
10154
  }
10155
+ data = toStoredData(schema.options?.name ?? modelConstructor.name, schema.fieldNames, data);
9411
10156
  const idFieldOptions = schema.fields.get("id");
9412
10157
  if (data.id) {
9413
10158
  this.id = data.id;
@@ -9564,6 +10309,7 @@ var init_BaseModel = __esm({
9564
10309
  const format2Store = modelConstructor.recordViewFor(this._metaDocId);
9565
10310
  if (format2Store) {
9566
10311
  format2Store.assertReadable();
10312
+ if (format2Store.declaredCleared?.()?.[modelName]?.includes(fieldKey)) return void 0;
9567
10313
  const staged = recordLogTransactionsOpen > 0 ? stagedForRead(resolveOrmContext(modelConstructor), format2Store, modelName, this.id) : void 0;
9568
10314
  const row = staged !== void 0 ? staged : this._format2Row?.row ?? null;
9569
10315
  const value = row ? row[fieldKey] : void 0;
@@ -9700,9 +10446,14 @@ var init_BaseModel = __esm({
9700
10446
  `[getValue] Field '${fieldKey}' is StringSet type, returning StringSet instance`
9701
10447
  );
9702
10448
  }
10449
+ if (heldRevisionClears(this, fieldKey)) return new StringSet(this, fieldKey, []);
9703
10450
  return this.getOrCreateStringSet(fieldKey);
9704
10451
  }
10452
+ if (fieldOptions?.type === "string" && db3JsonDefOf(this.constructor, fieldKey)) {
10453
+ return readDb3JsonField(schema?.options?.name ?? this.constructor.name, fieldKey, db3JsonText(this, fieldKey));
10454
+ }
9705
10455
  if (this.hasLocalChange(fieldKey)) {
10456
+ if (heldRevisionClears(this, fieldKey)) return void 0;
9706
10457
  if (verboseEnabled) {
9707
10458
  Logger.verbose(
9708
10459
  `[getValue] Field '${fieldKey}' has local changes: ${this._localChanges[fieldKey]}`
@@ -9728,11 +10479,15 @@ var init_BaseModel = __esm({
9728
10479
  const fieldOptions = schema?.fields?.get(fieldKey);
9729
10480
  if (fieldOptions?.type === "stringset") {
9730
10481
  throw new Error(
9731
- `Cannot directly assign to StringSet field '${fieldKey}'. Use the StringSet methods (add, remove, clear) instead.`
10482
+ `Cannot directly assign to StringSet field '${currentNameOf(schema?.fieldNames, fieldKey)}'. Use the StringSet methods (add, remove, clear) instead.`
9732
10483
  );
9733
10484
  }
9734
10485
  if (!this._isLoadingFromYjs) {
9735
10486
  }
10487
+ const jsonDef = fieldOptions?.type === "string" ? db3JsonDefOf(this.constructor, fieldKey) : void 0;
10488
+ if (jsonDef) {
10489
+ value = encodeDb3JsonField(schema?.options?.name ?? this.constructor.name, fieldKey, jsonDef, value);
10490
+ }
9736
10491
  const changes = this.ensureLocalChanges();
9737
10492
  changes[fieldKey] = value;
9738
10493
  this._isDirty = true;
@@ -9775,12 +10530,19 @@ var init_BaseModel = __esm({
9775
10530
  throw new Error(`Field ${fieldKey} is required`);
9776
10531
  }
9777
10532
  }
9778
- validateBeforeSave() {
10533
+ /**
10534
+ * Check the model's own rules before a save writes it.
10535
+ *
10536
+ * @param cleared - Fields the db3's type clears: a build generated while
10537
+ * one was `required` still saves its other fields, as the room stores
10538
+ * nothing for it.
10539
+ */
10540
+ validateBeforeSave(cleared) {
9779
10541
  const schema = this.constructor.getSchema();
9780
10542
  for (const [fieldKey, fieldOptions] of schema.fields.entries()) {
9781
- const currentValue = fieldKey === "id" ? this.id : this.getValue(fieldKey);
9782
- if (fieldOptions.required && (currentValue === null || currentValue === void 0)) {
9783
- throw new Error(`Field ${fieldKey} is required before save`);
10543
+ const currentValue = fieldKey === "id" ? this.id : fieldOptions.type === "string" && db3JsonDefOf(this.constructor, fieldKey) ? db3JsonText(this, fieldKey) : this.getValue(fieldKey);
10544
+ if (fieldOptions.required && (currentValue === null || currentValue === void 0) && !cleared?.includes(fieldKey)) {
10545
+ throw new Error(`Field ${currentNameOf(schema.fieldNames, fieldKey)} is required before save`);
9784
10546
  }
9785
10547
  if (fieldOptions.type === "stringset" && currentValue instanceof StringSet) {
9786
10548
  if (fieldOptions.maxCount && currentValue.size > fieldOptions.maxCount) {
@@ -9802,16 +10564,18 @@ var init_BaseModel = __esm({
9802
10564
  }
9803
10565
  // State inspection helpers
9804
10566
  getChangedFields() {
9805
- return this._localChanges ? Object.keys(this._localChanges) : [];
10567
+ if (!this._localChanges) return [];
10568
+ const names = fieldNamesOfClass(this.constructor);
10569
+ return Object.keys(this._localChanges).map((field) => currentNameOf(names, field));
9806
10570
  }
9807
10571
  getOriginalValue(fieldKey) {
9808
- return this.getFromYjs(fieldKey);
10572
+ return this.getFromYjs(storedNameOf(fieldNamesOfClass(this.constructor), fieldKey));
9809
10573
  }
9810
10574
  getCurrentValue(fieldKey) {
9811
- return this.getValue(fieldKey);
10575
+ return this.getValue(storedNameOf(fieldNamesOfClass(this.constructor), fieldKey));
9812
10576
  }
9813
10577
  hasFieldChanged(fieldKey) {
9814
- return this.hasLocalChange(fieldKey);
10578
+ return this.hasLocalChange(storedNameOf(fieldNamesOfClass(this.constructor), fieldKey));
9815
10579
  }
9816
10580
  // StringSet support methods
9817
10581
  markStringSetChange(fieldName, operation, value) {
@@ -10978,36 +11742,56 @@ var init_BaseModel = __esm({
10978
11742
  }
10979
11743
  let upsertOnConstraint = null;
10980
11744
  let upsertOnKey = null;
11745
+ let upsertTarget = null;
10981
11746
  if (options?.upsertOn) {
10982
- const upsertField = options.upsertOn;
10983
- assertValidIdentifier(upsertField, "upsertOn field");
10984
- const upsertValue = this[upsertField];
10985
- if (upsertValue === null || upsertValue === void 0 || upsertValue === "") {
10986
- throw new Error(
10987
- `[${modelName}] upsertOn field '${upsertField}' must be present in data and not null/empty`
10988
- );
10989
- }
10990
- const constraint = schema.resolvedUniqueConstraints.find(
10991
- (c) => c.fields.length === 1 && c.fields[0] === upsertField
10992
- );
10993
- if (!constraint) {
10994
- throw new Error(
10995
- `[${modelName}] upsertOn field '${upsertField}' does not have a registered unique index`
11747
+ const upsertToken = options.upsertOn;
11748
+ assertValidIdentifier(upsertToken, "upsertOn field");
11749
+ const named = schema.fieldNames ? upsertConstraintNamed(schema, modelConstructor.getRecordLogStore(targetDocId), modelName, upsertToken) : void 0;
11750
+ if (named) {
11751
+ const values = named.fields.map((field) => this.getValue(field));
11752
+ if (values.some((value) => value === null || value === void 0 || value === "")) {
11753
+ throw new Error(
11754
+ `[${modelName}] upsertOn constraint '${upsertToken}' needs ${currentFieldsOf(schema, named.fields).join(", ")} present in data and not null/empty`
11755
+ );
11756
+ }
11757
+ const uniqueKey = modelConstructor._buildKeyFromValues([...named.fields], values, modelName, named.name);
11758
+ if (uniqueKey === null) {
11759
+ throw new Error(`[${modelName}] upsertOn: unable to build unique key for constraint '${upsertToken}'`);
11760
+ }
11761
+ upsertOnConstraint = { name: named.name, fields: [...named.fields] };
11762
+ upsertOnKey = uniqueKey;
11763
+ upsertTarget = { token: upsertToken, fields: [...named.fields] };
11764
+ } else {
11765
+ const upsertField = schema.fieldNames ? storedNameOf(schema.fieldNames, upsertToken) : upsertToken;
11766
+ const upsertValue = schema.fieldNames ? this.getValue(upsertField) : this[upsertField];
11767
+ if (upsertValue === null || upsertValue === void 0 || upsertValue === "") {
11768
+ throw new Error(
11769
+ `[${modelName}] upsertOn field '${upsertToken}' must be present in data and not null/empty`
11770
+ );
11771
+ }
11772
+ const constraint = schema.resolvedUniqueConstraints.find(
11773
+ (c) => c.fields.length === 1 && c.fields[0] === upsertField
10996
11774
  );
10997
- }
10998
- const uniqueKey = modelConstructor._buildKeyFromValues(
10999
- constraint.fields,
11000
- [upsertValue],
11001
- modelName,
11002
- constraint.name
11003
- );
11004
- if (uniqueKey === null) {
11005
- throw new Error(
11006
- `[${modelName}] upsertOn: unable to build unique key for field '${upsertField}'`
11775
+ if (!constraint) {
11776
+ throw new Error(
11777
+ `[${modelName}] upsertOn field '${upsertToken}' does not have a registered unique index`
11778
+ );
11779
+ }
11780
+ const uniqueKey = modelConstructor._buildKeyFromValues(
11781
+ constraint.fields,
11782
+ [upsertValue],
11783
+ modelName,
11784
+ constraint.name
11007
11785
  );
11786
+ if (uniqueKey === null) {
11787
+ throw new Error(
11788
+ `[${modelName}] upsertOn: unable to build unique key for field '${upsertToken}'`
11789
+ );
11790
+ }
11791
+ upsertOnConstraint = constraint;
11792
+ upsertOnKey = uniqueKey;
11793
+ upsertTarget = { token: upsertField, fields: [upsertField] };
11008
11794
  }
11009
- upsertOnConstraint = constraint;
11010
- upsertOnKey = uniqueKey;
11011
11795
  }
11012
11796
  if (!this.id) {
11013
11797
  Logger.error(
@@ -11041,8 +11825,11 @@ var init_BaseModel = __esm({
11041
11825
  modelName,
11042
11826
  docId: targetDocId,
11043
11827
  permissionHint,
11044
- upsertOnField: options?.upsertOn ?? null,
11045
- guards: { condition: options?.condition, ifNotExists: options?.ifNotExists }
11828
+ upsertTarget,
11829
+ guards: {
11830
+ condition: schema.fieldNames ? toStoredFilter(schema.fieldNames, options?.condition) : options?.condition,
11831
+ ifNotExists: options?.ifNotExists
11832
+ }
11046
11833
  })
11047
11834
  );
11048
11835
  this.clearLocalChanges();
@@ -11073,6 +11860,7 @@ var init_BaseModel = __esm({
11073
11860
  Logger.debug(`[${modelName}.save] _localChanges:`, this._localChanges);
11074
11861
  Logger.debug(`[${modelName}.save] _isDirty:`, this._isDirty);
11075
11862
  const dataToSave = this.getCurrentJSState();
11863
+ storeDb3JsonFields(this, dataToSave, schema.fields);
11076
11864
  Logger.debug(
11077
11865
  `[${modelName}.save] getCurrentJSState() returned:`,
11078
11866
  dataToSave
@@ -11237,7 +12025,7 @@ var init_BaseModel = __esm({
11237
12025
  );
11238
12026
  if (existingRecordIdWithNewKey && existingRecordIdWithNewKey !== this.id) {
11239
12027
  throw new UniqueConstraintViolationError(
11240
- `Unique constraint '${constraint.name}' violated for model '${modelName}' on fields [${constraint.fields.join(
12028
+ `Unique constraint '${constraint.name}' violated for model '${modelName}' on fields [${currentFieldsOf(schema, constraint.fields).join(
11241
12029
  ", "
11242
12030
  )}]. Attempted ID: ${this.id}. Value(s) starting with '${newUniqueKey.substring(
11243
12031
  0,
@@ -11245,7 +12033,7 @@ var init_BaseModel = __esm({
11245
12033
  )}...' already exist for record ID ${existingRecordIdWithNewKey}.`,
11246
12034
  modelName,
11247
12035
  constraint.name,
11248
- constraint.fields,
12036
+ currentFieldsOf(schema, constraint.fields),
11249
12037
  this.id,
11250
12038
  existingRecordIdWithNewKey
11251
12039
  );
@@ -11256,7 +12044,7 @@ var init_BaseModel = __esm({
11256
12044
  `[${modelName}] Save Check (Item '${this.id}'): index miss for '${constraint.name}', but engine fallback found conflicting index-less record ${conflictingRecordId}.`
11257
12045
  );
11258
12046
  throw new UniqueConstraintViolationError(
11259
- `Unique constraint '${constraint.name}' violated for model '${modelName}' on fields [${constraint.fields.join(
12047
+ `Unique constraint '${constraint.name}' violated for model '${modelName}' on fields [${currentFieldsOf(schema, constraint.fields).join(
11260
12048
  ", "
11261
12049
  )}]. Attempted ID: ${this.id}. Value(s) starting with '${newUniqueKey.substring(
11262
12050
  0,
@@ -11264,7 +12052,7 @@ var init_BaseModel = __esm({
11264
12052
  )}...' already exist for index-less record ID ${conflictingRecordId}.`,
11265
12053
  modelName,
11266
12054
  constraint.name,
11267
- constraint.fields,
12055
+ currentFieldsOf(schema, constraint.fields),
11268
12056
  this.id,
11269
12057
  conflictingRecordId
11270
12058
  );
@@ -11465,7 +12253,8 @@ var init_BaseModel = __esm({
11465
12253
  const persisted = fieldKey === "id" ? this.id : this.getValue(fieldKey);
11466
12254
  if (persisted !== null && persisted !== void 0) continue;
11467
12255
  }
11468
- this[fieldKey] = Date.now();
12256
+ if (schema.fieldNames) this.setValue(fieldKey, Date.now());
12257
+ else this[fieldKey] = Date.now();
11469
12258
  if (stamp === "create") {
11470
12259
  preTransactCreateStamps.add(fieldKey);
11471
12260
  }
@@ -11482,7 +12271,7 @@ var init_BaseModel = __esm({
11482
12271
  * locally.
11483
12272
  */
11484
12273
  async saveRecordLog(ctx) {
11485
- const { store, schema, modelName, docId, permissionHint, upsertOnField, guards } = ctx;
12274
+ const { store, schema, modelName, docId, permissionHint, upsertTarget, guards } = ctx;
11486
12275
  let committedSeq = null;
11487
12276
  const modelConstructor = this.constructor;
11488
12277
  const ormContext = resolveOrmContext(modelConstructor);
@@ -11527,8 +12316,10 @@ var init_BaseModel = __esm({
11527
12316
  }
11528
12317
  }
11529
12318
  const preTransactCreateStamps = this.applyAutoStampsForSave(schema, existing === null || asCreate);
11530
- this.validateBeforeSave();
12319
+ const heldCleared = store.declaredCleared?.()?.[modelName];
12320
+ this.validateBeforeSave(heldCleared);
11531
12321
  const dataToSave = this.getCurrentJSState();
12322
+ storeDb3JsonFields(this, dataToSave, schema.fields);
11532
12323
  try {
11533
12324
  encodeVectorFields(dataToSave, schema.fields, store.declaredVectors(), modelName, this.id);
11534
12325
  } catch (error) {
@@ -11545,8 +12336,12 @@ var init_BaseModel = __esm({
11545
12336
  throw refused;
11546
12337
  }
11547
12338
  let upsertOn;
11548
- if (upsertOnField && !asCreate) {
11549
- const matched = await ops.findIdByFields(modelName, [upsertOnField], [dataToSave[upsertOnField]]);
12339
+ if (upsertTarget && !asCreate) {
12340
+ const matched = await ops.findIdByFields(
12341
+ modelName,
12342
+ upsertTarget.fields,
12343
+ upsertTarget.fields.map((field) => dataToSave[field])
12344
+ );
11550
12345
  if (matched && matched !== this.id) {
11551
12346
  if (this._constructorProvidedId) {
11552
12347
  throw new Error(
@@ -11563,7 +12358,7 @@ var init_BaseModel = __esm({
11563
12358
  }
11564
12359
  existing = stagedOr(this.id, await ops.read(modelName, this.id));
11565
12360
  } else if (!matched && existing === null) {
11566
- upsertOn = upsertOnField;
12361
+ upsertOn = upsertTarget.token;
11567
12362
  }
11568
12363
  }
11569
12364
  const postMutation = { ...existing ?? {} };
@@ -11573,15 +12368,16 @@ var init_BaseModel = __esm({
11573
12368
  const selfJudged = store.marks().localOnly === true;
11574
12369
  for (const constraint of selfJudged ? [] : schema.resolvedUniqueConstraints) {
11575
12370
  if (!store.constraintInForce(constraint.name)) continue;
12371
+ if (heldCleared?.length && constraint.fields.some((field) => heldCleared.includes(field))) continue;
11576
12372
  const values = constraint.fields.map((field) => postMutation[field]);
11577
12373
  if (values.some((value) => value === void 0 || value === null)) continue;
11578
12374
  const holder = await ops.findIdByFields(modelName, constraint.fields, values);
11579
12375
  if (holder !== null && holder !== this.id) {
11580
12376
  throw new UniqueConstraintViolationError(
11581
- `Unique constraint "${constraint.name}" violated for model "${modelName}" on fields [${constraint.fields.join(", ")}]: a record (${holder}) already exists for this value. Attempted record id: ${this.id}.`,
12377
+ `Unique constraint "${constraint.name}" violated for model "${modelName}" on fields [${currentFieldsOf(schema, constraint.fields).join(", ")}]: a record (${holder}) already exists for this value. Attempted record id: ${this.id}.`,
11582
12378
  modelName,
11583
12379
  constraint.name,
11584
- constraint.fields,
12380
+ currentFieldsOf(schema, constraint.fields),
11585
12381
  this.id,
11586
12382
  holder
11587
12383
  );
@@ -11607,7 +12403,7 @@ var init_BaseModel = __esm({
11607
12403
  Logger.warn("[record-log] write refused locally \u2014", docId, modelName, this.id, event.error.code);
11608
12404
  ormContext.reportRecordLogWriteRefused(event);
11609
12405
  };
11610
- const entryUpsertOn = upsertOn ?? (upsertOnField !== null && guards.ifNotExists ? upsertOnField : void 0);
12406
+ const entryUpsertOn = upsertOn ?? (upsertTarget !== null && guards.ifNotExists ? upsertTarget.token : void 0);
11611
12407
  assertRecordLogEntry(docId, [mutation], report, entryUpsertOn !== void 0 ? { upsertOn: entryUpsertOn } : {});
11612
12408
  if (!transaction) assertRecordLogDeclaredTypes(docId, [mutation], declaredTypeOf(store), report);
11613
12409
  this._format2Row = store.entryFor(modelName, this.id);
@@ -11723,6 +12519,12 @@ var init_BaseModel = __esm({
11723
12519
  const schema = modelConstructor.getSchema?.();
11724
12520
  const modelName = schema?.options?.name;
11725
12521
  if (!modelName) throw new Error(`Schema not found for model ${modelConstructor.name} in increment.`);
12522
+ const incrementNames = schema.fieldNames ?? null;
12523
+ const askedFields = fields;
12524
+ if (incrementNames) {
12525
+ fields = toStoredData(modelName, incrementNames, fields);
12526
+ if (options.condition !== void 0) options = { ...options, condition: toStoredFilter(incrementNames, options.condition) };
12527
+ }
11726
12528
  if (typeof id !== "string" || id.length === 0) {
11727
12529
  throw new Error(`[${modelName}] increment needs the id of the record to increment.`);
11728
12530
  }
@@ -11793,6 +12595,14 @@ var init_BaseModel = __esm({
11793
12595
  const settled = settlement.rows.find((r) => r.model === modelName && r.id === id)?.row;
11794
12596
  if (settled) values = valuesOf(settled);
11795
12597
  }
12598
+ if (incrementNames) {
12599
+ return Object.fromEntries(
12600
+ Object.keys(askedFields).map((name) => {
12601
+ const stored = storedNameOf(incrementNames, name);
12602
+ return [currentNameOf(incrementNames, stored), values[stored]];
12603
+ })
12604
+ );
12605
+ }
11796
12606
  return values;
11797
12607
  }
11798
12608
  /**
@@ -11933,7 +12743,7 @@ var init_BaseModel = __esm({
11933
12743
  store: recordLogStore,
11934
12744
  modelName,
11935
12745
  docId,
11936
- ...options?.condition !== void 0 ? { condition: options.condition } : {}
12746
+ ...options?.condition !== void 0 ? { condition: schema?.fieldNames ? toStoredFilter(schema.fieldNames, options.condition) : options.condition } : {}
11937
12747
  })
11938
12748
  );
11939
12749
  if (options?.confirm && seq !== null) await recordLogStore.whenAcknowledged(seq);
@@ -12032,7 +12842,9 @@ var init_BaseModel = __esm({
12032
12842
  }
12033
12843
  // Keep toJSON for backward compatibility, but delegate to getCurrentJSState
12034
12844
  toJSON() {
12035
- return this.getCurrentJSState();
12845
+ const state = this.getCurrentJSState();
12846
+ const names = fieldNamesOfClass(this.constructor);
12847
+ return names ? toCurrentRow(() => names, "", state) : state;
12036
12848
  }
12037
12849
  /**
12038
12850
  * Refuse a read through a class whose ORM instance has been destroyed
@@ -12164,6 +12976,12 @@ var init_BaseModel = __esm({
12164
12976
  throw new Error("Model not properly initialized for query");
12165
12977
  }
12166
12978
  const modelName = schema.options.name;
12979
+ const namesOf = modelNamesOf(this, modelName, schema.fieldNames);
12980
+ const renames = namesAnyModel(namesOf, modelName, options?.include);
12981
+ if (renames) {
12982
+ filter = toStoredFilter(namesOf(modelName), filter);
12983
+ options = storedQueryOptions(namesOf, modelName, options);
12984
+ }
12167
12985
  Logger.verbose(`[${modelName}] Executing query:`, { filter, options });
12168
12986
  const near = parseNearRead(filter, options?.include);
12169
12987
  const hasIncludes = options?.include && options.include.length > 0;
@@ -12199,7 +13017,7 @@ var init_BaseModel = __esm({
12199
13017
  { sort: options?.sort, include: options?.include },
12200
13018
  side
12201
13019
  );
12202
- return page;
13020
+ return renames ? currentPage(page, namesOf, modelName, options?.include) : page;
12203
13021
  }
12204
13022
  if (near) throw new Db3IndexNotOnDeviceError({ operator: "$near", model: modelName, field: near.field });
12205
13023
  if (side) {
@@ -12355,7 +13173,7 @@ var init_BaseModel = __esm({
12355
13173
  }).filter(Boolean);
12356
13174
  }
12357
13175
  return {
12358
- data: transformedData,
13176
+ data: renames ? currentRows(transformedData, namesOf, modelName, options?.include) : transformedData,
12359
13177
  nextCursor: cursors.nextCursor,
12360
13178
  prevCursor: cursors.prevCursor,
12361
13179
  hasMore
@@ -12424,6 +13242,8 @@ var init_BaseModel = __esm({
12424
13242
  throw new Error("Model not properly initialized for aggregation");
12425
13243
  }
12426
13244
  const modelName = schema.options.name;
13245
+ const aggregateNames = schema.fieldNames ?? null;
13246
+ if (aggregateNames) options = toStoredAggregate(aggregateNames, options);
12427
13247
  Logger.verbose(`[${modelName}] Executing structured aggregation:`, options);
12428
13248
  const near = parseNearRead(options.filter);
12429
13249
  for (const operation of options.operations) {
@@ -12518,7 +13338,7 @@ var init_BaseModel = __esm({
12518
13338
  writable: false
12519
13339
  });
12520
13340
  }
12521
- return rows;
13341
+ return toCurrentAggregateRows(aggregateNames, options, rows);
12522
13342
  }
12523
13343
  if (near) throw new Db3IndexNotOnDeviceError({ operator: "$near", model: modelName, field: near.field });
12524
13344
  if (side) {
@@ -12573,7 +13393,7 @@ var init_BaseModel = __esm({
12573
13393
  writable: false
12574
13394
  });
12575
13395
  }
12576
- return processedResult;
13396
+ return toCurrentAggregateRows(aggregateNames, options, processedResult);
12577
13397
  }
12578
13398
  /**
12579
13399
  * Build SQL query for structured aggregation, through js-bao's one
@@ -12723,6 +13543,7 @@ var init_BaseModel = __esm({
12723
13543
  throw new Error("Model not properly initialized for count");
12724
13544
  }
12725
13545
  const modelName = schema.options.name;
13546
+ filter = toStoredFilter(schema.fieldNames, filter);
12726
13547
  Logger.verbose(`[${modelName}] Executing count:`, { filter, options });
12727
13548
  const near = parseNearRead(filter);
12728
13549
  let scope = this.documentsInScope(
@@ -12908,9 +13729,7 @@ var init_BaseModel = __esm({
12908
13729
  `[${currentModelName}] Schema or unique constraints not loaded for findByUnique.`
12909
13730
  );
12910
13731
  }
12911
- const constraint = schema.resolvedUniqueConstraints.find(
12912
- (c) => c.name === constraintName
12913
- );
13732
+ const constraint = uniqueConstraintNamed(schema, constraintName);
12914
13733
  if (!constraint) {
12915
13734
  throw new Error(
12916
13735
  `[${currentModelName}] Unique constraint named '${constraintName}' not found.`
@@ -13052,22 +13871,23 @@ var init_BaseModel = __esm({
13052
13871
  `[${currentModelName}] No documents are connected. Connect at least one document via initJsBao(...).connectDocument or call initializeForDocument(yDoc, db, docId, permissionHint) before calling upsertByUnique.`
13053
13872
  );
13054
13873
  }
13055
- const constraint = schema.resolvedUniqueConstraints.find(
13056
- (c) => c.name === constraintName
13057
- );
13874
+ const constraint = uniqueConstraintNamed(schema, constraintName);
13058
13875
  if (!constraint) {
13059
13876
  throw new Error(
13060
13877
  `[${currentModelName}] Unique constraint named '${constraintName}' not found for upsert.`
13061
13878
  );
13062
13879
  }
13063
13880
  const keyValuesForLookup = Array.isArray(uniqueLookupValue) ? uniqueLookupValue : [uniqueLookupValue];
13881
+ const upsertNames = schema.fieldNames ?? null;
13882
+ const storedUpsert = toStoredData(currentModelName, upsertNames, dataToUpsert);
13883
+ if (upsertNames) dataToUpsert = toCurrentRow(() => upsertNames, "", storedUpsert);
13064
13884
  constraint.fields.forEach((field, index) => {
13065
- if (!dataToUpsert.hasOwnProperty(field)) {
13885
+ if (!storedUpsert.hasOwnProperty(field)) {
13066
13886
  throw new Error(
13067
- `[${currentModelName}] upsertByUnique: dataToUpsert is missing required unique field '${field}' from constraint '${constraintName}'.`
13887
+ `[${currentModelName}] upsertByUnique: dataToUpsert is missing required unique field '${currentNameOf(upsertNames, field)}' from constraint '${constraintName}'.`
13068
13888
  );
13069
13889
  }
13070
- const dataValue = dataToUpsert[field];
13890
+ const dataValue = storedUpsert[field];
13071
13891
  const lookupValue = keyValuesForLookup[index];
13072
13892
  if (dataValue !== lookupValue) {
13073
13893
  throw new Error(
@@ -13575,6 +14395,7 @@ __export(browser_exports, {
13575
14395
  DatabaseFactory: () => BrowserDatabaseFactory,
13576
14396
  Db3DriftExceededError: () => Db3DriftExceededError,
13577
14397
  Db3IndexNotOnDeviceError: () => Db3IndexNotOnDeviceError,
14398
+ Db3JsonValueError: () => Db3JsonValueError,
13578
14399
  Db3ModelOnOtherClientError: () => Db3ModelOnOtherClientError,
13579
14400
  Db3NotResidentError: () => Db3NotResidentError,
13580
14401
  Db3QueryScopeError: () => Db3QueryScopeError,
@@ -13585,6 +14406,7 @@ __export(browser_exports, {
13585
14406
  DocumentWriteAccessDeniedError: () => DocumentWriteAccessDeniedError,
13586
14407
  FORMAT2_MANIFEST_VERSION: () => FORMAT2_MANIFEST_VERSION,
13587
14408
  FORMAT2_MIN_MANIFEST_VERSION: () => FORMAT2_MIN_MANIFEST_VERSION,
14409
+ FieldNamedTwiceError: () => FieldNamedTwiceError,
13588
14410
  Format2QueryScopeError: () => Db3QueryScopeError,
13589
14411
  Format2RowCache: () => Db3RowCache,
13590
14412
  Format2StorageCapabilityError: () => Db3StorageCapabilityError,
@@ -13663,8 +14485,10 @@ __export(browser_exports, {
13663
14485
  attachAndRegisterModel: () => attachAndRegisterModel,
13664
14486
  attachSchemaToClass: () => attachSchemaToClass,
13665
14487
  autoRegisterModel: () => autoRegisterModel,
14488
+ bindDb3JsonFields: () => bindDb3JsonFields,
13666
14489
  buildUniqueKey: () => buildUniqueKey,
13667
14490
  buildUniqueKeyFromValues: () => buildUniqueKeyFromValues,
14491
+ canonicalDb3Json: () => canonicalDb3Json,
13668
14492
  canonicalStringSet: () => canonicalStringSet,
13669
14493
  checkVectorModelEnvelope: () => checkVectorModelEnvelope,
13670
14494
  clearMetaSyncCache: () => clearMetaSyncCache,
@@ -13673,7 +14497,10 @@ __export(browser_exports, {
13673
14497
  conditionHolds: () => conditionHolds,
13674
14498
  conditionProblem: () => conditionProblem,
13675
14499
  countViewRows: () => countViewRows,
14500
+ currentNameOf: () => currentNameOf,
14501
+ db3JsonText: () => db3JsonText,
13676
14502
  db3ViewTranslator: () => db3ViewTranslator,
14503
+ declareFieldNameTypes: () => declareFieldNameTypes,
13677
14504
  declaredTypeProblem: () => declaredTypeProblem,
13678
14505
  declineRecordLogIndex: () => declineRecordLogIndex,
13679
14506
  decodeRecordLogChunk: () => decodeRecordLogChunk,
@@ -13691,6 +14518,9 @@ __export(browser_exports, {
13691
14518
  estimateMaterializedBytes: () => estimateMaterializedBytes,
13692
14519
  explainViewRead: () => explainViewRead,
13693
14520
  features: () => features,
14521
+ fieldNameMapOf: () => fieldNameMapOf,
14522
+ fieldNameTypesOf: () => fieldNameTypesOf,
14523
+ fieldNamesOfClass: () => fieldNamesOfClass,
13694
14524
  fieldUniqueConstraintName: () => fieldUniqueConstraintName,
13695
14525
  findNearOperator: () => findNearOperator,
13696
14526
  findReservedFieldNameInToml: () => findReservedFieldNameInToml,
@@ -13703,7 +14533,7 @@ __export(browser_exports, {
13703
14533
  isAnchorId: () => isAnchorId,
13704
14534
  isBrowser: () => isBrowser,
13705
14535
  isCanonicalStringSet: () => isCanonicalStringSet,
13706
- isNode: () => isNode,
14536
+ isNode: () => isNode2,
13707
14537
  isRecordLogResident: () => isRecordLogResident,
13708
14538
  isRecordLogStoreNotice: () => isRecordLogStoreNotice,
13709
14539
  isRecordLogStoreRequest: () => isRecordLogStoreRequest,
@@ -13713,6 +14543,7 @@ __export(browser_exports, {
13713
14543
  loadYjs: () => loadYjs,
13714
14544
  localConstraints: () => localConstraints,
13715
14545
  localIndexList: () => localIndexList,
14546
+ namesAnyModel: () => namesAnyModel,
13716
14547
  omitStringsetConstraints: () => omitStringsetConstraints,
13717
14548
  parseSnapshotChunkPath: () => parseSnapshotChunkPath,
13718
14549
  planRecordLogDelete: () => planRecordLogDelete,
@@ -13742,16 +14573,26 @@ __export(browser_exports, {
13742
14573
  requestStoragePersistence: () => requestStoragePersistence,
13743
14574
  resetJsBao: () => resetJsBao,
13744
14575
  resolveChunkOrdinal: () => resolveChunkOrdinal,
14576
+ resolveUpsertTarget: () => resolveUpsertTarget,
13745
14577
  schemaToToml: () => schemaToToml,
13746
14578
  serveRecordLogStoreHost: () => serveRecordLogStoreHost,
13747
14579
  storedConditionHolds: () => storedConditionHolds,
14580
+ storedNameOf: () => storedNameOf,
13748
14581
  syncInferredMeta: () => syncInferredMeta,
13749
14582
  syncModelMeta: () => syncModelMeta,
13750
14583
  syncRecordLogIndexes: () => syncRecordLogIndexes,
14584
+ toCurrentAggregateRows: () => toCurrentAggregateRows,
14585
+ toCurrentRow: () => toCurrentRow,
14586
+ toStoredAggregate: () => toStoredAggregate,
14587
+ toStoredData: () => toStoredData,
14588
+ toStoredFilter: () => toStoredFilter,
14589
+ toStoredIncludes: () => toStoredIncludes,
14590
+ toStoredKeys: () => toStoredKeys,
13751
14591
  traceViewRead: () => traceViewRead,
13752
14592
  uniqueIndexMapName: () => uniqueIndexMapName,
13753
14593
  uniqueStringsetMessage: () => uniqueStringsetMessage,
13754
14594
  uniqueStringsetViolations: () => uniqueStringsetViolations,
14595
+ validateDb3Json: () => validateDb3Json,
13755
14596
  validateSnapshotManifest: () => validateSnapshotManifest,
13756
14597
  vectorBytes: () => vectorBytes,
13757
14598
  wireEntryOf: () => wireEntryOf,
@@ -14203,7 +15044,7 @@ function detectEnvironment() {
14203
15044
  }
14204
15045
  return "unknown";
14205
15046
  }
14206
- function isNode() {
15047
+ function isNode2() {
14207
15048
  return detectEnvironment() === "node";
14208
15049
  }
14209
15050
  function isBrowser() {
@@ -14217,7 +15058,7 @@ function importNodeOnly(specifier) {
14217
15058
  );
14218
15059
  }
14219
15060
  async function isNodeModuleAvailable(moduleName) {
14220
- if (!isNode()) {
15061
+ if (!isNode2()) {
14221
15062
  return false;
14222
15063
  }
14223
15064
  try {
@@ -14236,7 +15077,7 @@ var features = {
14236
15077
  return isBrowser() && typeof Worker !== "undefined";
14237
15078
  },
14238
15079
  get hasFileSystem() {
14239
- return isNode();
15080
+ return isNode2();
14240
15081
  },
14241
15082
  get hasWebAssembly() {
14242
15083
  return typeof WebAssembly !== "undefined";
@@ -14255,7 +15096,7 @@ var import_meta = {};
14255
15096
  var SQL_WASM_URL = "/sql-wasm.wasm";
14256
15097
  var SQL_WASM_FILENAME = "sql-wasm.wasm";
14257
15098
  async function resolveNodeWasmPath() {
14258
- if (!isNode()) {
15099
+ if (!isNode2()) {
14259
15100
  return null;
14260
15101
  }
14261
15102
  try {
@@ -14277,7 +15118,7 @@ async function resolveNodeWasmPath() {
14277
15118
  return null;
14278
15119
  }
14279
15120
  async function preflightNodeWasm(wasmPath) {
14280
- if (!isNode()) {
15121
+ if (!isNode2()) {
14281
15122
  return;
14282
15123
  }
14283
15124
  if (/^[a-z]+:\/\//i.test(wasmPath)) {
@@ -14333,7 +15174,7 @@ async function guardedLoadSqlJs(locateFile) {
14333
15174
  reason
14334
15175
  )}`
14335
15176
  );
14336
- const nodeProcess = isNode() && typeof process !== "undefined" ? process : void 0;
15177
+ const nodeProcess = isNode2() && typeof process !== "undefined" ? process : void 0;
14337
15178
  const onUnhandled = (reason) => {
14338
15179
  if (runtimeFailed() && !runtimeFailureCaught) {
14339
15180
  runtimeFailureCaught = true;
@@ -14608,10 +15449,10 @@ var SqljsEngine = class _SqljsEngine extends SqliteQueryEngineBase {
14608
15449
  const db = this.db;
14609
15450
  let depth = 0;
14610
15451
  return {
14611
- exec(query, ...bindings) {
15452
+ exec(query, ...bindings2) {
14612
15453
  const stmt = db.prepare(query);
14613
15454
  try {
14614
- if (bindings.length > 0) stmt.bind(bindings);
15455
+ if (bindings2.length > 0) stmt.bind(bindings2);
14615
15456
  const rows = [];
14616
15457
  while (stmt.step()) rows.push(stmt.getAsObject());
14617
15458
  return rows;
@@ -14708,8 +15549,8 @@ var CHUNK_PATH_OWN = /^([A-Za-z][A-Za-z0-9_]*)\/(\d+)$/;
14708
15549
  var CHUNK_PATH_SOURCED = /^(\d+)-([A-Za-z0-9_-]{1,64})\/([A-Za-z][A-Za-z0-9_]*)\/(\d+)$/;
14709
15550
  function parseSnapshotChunkPath(path) {
14710
15551
  if (!path || typeof path !== "string") return null;
14711
- const own2 = CHUNK_PATH_OWN.exec(path);
14712
- if (own2) return { model: own2[1], index: Number(own2[2]) };
15552
+ const own3 = CHUNK_PATH_OWN.exec(path);
15553
+ if (own3) return { model: own3[1], index: Number(own3[2]) };
14713
15554
  const sourced = CHUNK_PATH_SOURCED.exec(path);
14714
15555
  if (!sourced) return null;
14715
15556
  return {
@@ -15307,6 +16148,7 @@ var RECORD_LOG_CHANGING_COMMANDS = /* @__PURE__ */ new Set([
15307
16148
  "refused",
15308
16149
  "applyCatchUpPage",
15309
16150
  "completeCatchUp",
16151
+ "applyClears",
15310
16152
  "applyLoadChunk",
15311
16153
  "completeLoad",
15312
16154
  "applySegmentChunk",
@@ -15324,6 +16166,7 @@ var RECORD_LOG_VECTOR_WANT_COMMANDS = /* @__PURE__ */ new Set([
15324
16166
  "refused",
15325
16167
  "applyCatchUpPage",
15326
16168
  "completeCatchUp",
16169
+ "applyClears",
15327
16170
  "applyLoadChunk",
15328
16171
  "completeLoad",
15329
16172
  "applySegmentChunk",
@@ -15550,6 +16393,9 @@ function dispatchRecordLogStoreCommand(store, command) {
15550
16393
  case "completeCatchUp":
15551
16394
  value = store.completeCatchUp(c);
15552
16395
  break;
16396
+ case "applyClears":
16397
+ value = store.applyClears(c);
16398
+ break;
15553
16399
  case "beginReceipt":
15554
16400
  value = store.beginReceipt({
15555
16401
  writer: c.writer,
@@ -15767,6 +16613,70 @@ var VectorJobs = class {
15767
16613
  }
15768
16614
  };
15769
16615
 
16616
+ // src/record-log-client/cleared.ts
16617
+ var held = /* @__PURE__ */ new WeakMap();
16618
+ function heldClearedOf(sql, docId) {
16619
+ let docs = held.get(sql);
16620
+ if (!docs) held.set(sql, docs = /* @__PURE__ */ new Map());
16621
+ if (docs.has(docId)) return docs.get(docId);
16622
+ let cleared = null;
16623
+ let state;
16624
+ try {
16625
+ [state] = Array.from(sql.exec(`SELECT typed, db3_type FROM record_log_state WHERE doc_id = ?`, docId));
16626
+ } catch {
16627
+ return null;
16628
+ }
16629
+ if (state?.typed === "yes" && typeof state.db3_type === "string") {
16630
+ try {
16631
+ const map = JSON.parse(state.db3_type).cleared;
16632
+ if (map && typeof map === "object") {
16633
+ const entries = Object.entries(map).filter(([, names]) => Array.isArray(names) && names.length > 0);
16634
+ if (entries.length) cleared = new Map(entries.map(([model, names]) => [model, new Set(names.map(String))]));
16635
+ }
16636
+ } catch {
16637
+ }
16638
+ }
16639
+ docs.set(docId, cleared);
16640
+ return cleared;
16641
+ }
16642
+ function forgetHeldCleared(sql, docId) {
16643
+ held.get(sql)?.delete(docId);
16644
+ }
16645
+ function clearedOverDocuments(sql, model, documents) {
16646
+ let union;
16647
+ for (const docId of documents) {
16648
+ const names = heldClearedOf(sql, docId)?.get(model);
16649
+ if (!names) continue;
16650
+ if (!union) union = new Set(names);
16651
+ else for (const name of names) union.add(name);
16652
+ }
16653
+ return union;
16654
+ }
16655
+ function clearedReadOf(sql, model, documents) {
16656
+ const unsetFields = clearedOverDocuments(sql, model, documents);
16657
+ if (!unsetFields) return void 0;
16658
+ const distinct = [...new Set(documents)];
16659
+ let unsetFieldDocuments;
16660
+ for (const name of unsetFields) {
16661
+ const hiding = distinct.filter((docId) => heldClearedOf(sql, docId)?.get(model)?.has(name));
16662
+ if (hiding.length < distinct.length) (unsetFieldDocuments ??= /* @__PURE__ */ new Map()).set(name, hiding);
16663
+ }
16664
+ return { unsetFields, ...unsetFieldDocuments ? { unsetFieldDocuments } : {} };
16665
+ }
16666
+ function withoutNames(row, names) {
16667
+ if (!names) return row;
16668
+ let out;
16669
+ for (const name of names) {
16670
+ if (!Object.prototype.hasOwnProperty.call(row, name)) continue;
16671
+ out ??= { ...row };
16672
+ delete out[name];
16673
+ }
16674
+ return out ?? row;
16675
+ }
16676
+ function withoutHeldCleared(sql, docId, model, row) {
16677
+ return withoutNames(row, heldClearedOf(sql, docId)?.get(model));
16678
+ }
16679
+
15770
16680
  // src/record-log-client/store.ts
15771
16681
  var import_ulid3 = require("ulid");
15772
16682
 
@@ -15783,14 +16693,14 @@ function checkConstraints(trial, touched, constraints) {
15783
16693
  );
15784
16694
  if (!mine.length) continue;
15785
16695
  const ids = rows.filter((x) => x.key.model === constraint.model).map((x) => x.key.id);
15786
- const held = /* @__PURE__ */ new Map();
16696
+ const held2 = /* @__PURE__ */ new Map();
15787
16697
  for (const { key, row } of mine) {
15788
16698
  const values = constraintKey(row, constraint.fields);
15789
16699
  if (values === null) continue;
15790
16700
  const text = JSON.stringify(values);
15791
- const other = held.get(text);
16701
+ const other = held2.get(text);
15792
16702
  if (other) return { constraint, key: values, record: key, conflicting: other };
15793
- held.set(text, key);
16703
+ held2.set(text, key);
15794
16704
  const holder = trial.holder(constraint.model, constraint.fields, values, ids);
15795
16705
  if (holder !== null) {
15796
16706
  return {
@@ -15836,12 +16746,12 @@ function fieldLookupPredicates(modelName, fields) {
15836
16746
  };
15837
16747
  }
15838
16748
  function fieldLookupBindings(predicates, modelName, fields, values) {
15839
- const bindings = predicates.bindType ? [modelName] : [];
16749
+ const bindings2 = predicates.bindType ? [modelName] : [];
15840
16750
  for (let i = 0; i < fields.length; i++) {
15841
- if (predicates.bindPaths && fields[i] !== "id") bindings.push(fields[i]);
15842
- bindings.push(values[i]);
16751
+ if (predicates.bindPaths && fields[i] !== "id") bindings2.push(fields[i]);
16752
+ bindings2.push(values[i]);
15843
16753
  }
15844
- return bindings;
16754
+ return bindings2;
15845
16755
  }
15846
16756
 
15847
16757
  // src/record-log/sql.ts
@@ -15945,7 +16855,7 @@ var IncludeSpecError = class _IncludeSpecError extends DocumentQueryError {
15945
16855
  Object.setPrototypeOf(this, _IncludeSpecError.prototype);
15946
16856
  }
15947
16857
  };
15948
- var isPlainObject4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
16858
+ var isPlainObject5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
15949
16859
  var identifierError = (value, label) => {
15950
16860
  try {
15951
16861
  assertValidIdentifier(value, label);
@@ -15956,7 +16866,7 @@ var identifierError = (value, label) => {
15956
16866
  };
15957
16867
  function validateIncludeSpec(spec, options = {}) {
15958
16868
  const strict = options.strict === true;
15959
- if (strict && !isPlainObject4(spec)) return "each include spec must be an object";
16869
+ if (strict && !isPlainObject5(spec)) return "each include spec must be an object";
15960
16870
  const s = spec ?? {};
15961
16871
  if (!s.model || typeof s.model !== "string") return "include: 'model' is required";
15962
16872
  if (identifierError(s.model, "include model")) return `include: invalid model name '${s.model}'`;
@@ -15988,15 +16898,15 @@ function validateIncludeSpec(spec, options = {}) {
15988
16898
  if (s.limit !== void 0 && !(Number.isInteger(s.limit) && s.limit > 0)) {
15989
16899
  return "hasMany limit must be a positive integer";
15990
16900
  }
15991
- if (s.filter !== void 0 && !isPlainObject4(s.filter)) return "filter must be an object";
16901
+ if (s.filter !== void 0 && !isPlainObject5(s.filter)) return "filter must be an object";
15992
16902
  if (s.projection !== void 0) {
15993
- if (!isPlainObject4(s.projection)) return "projection must be an object";
16903
+ if (!isPlainObject5(s.projection)) return "projection must be an object";
15994
16904
  for (const field of Object.keys(s.projection)) {
15995
16905
  if (identifierError(field, "include projection field")) return `invalid projection field '${field}'`;
15996
16906
  }
15997
16907
  }
15998
16908
  if (s.sort !== void 0) {
15999
- if (!isPlainObject4(s.sort)) return "sort must be an object";
16909
+ if (!isPlainObject5(s.sort)) return "sort must be an object";
16000
16910
  if (Object.values(s.sort).some((dir) => dir !== 1 && dir !== -1)) return "sort directions must be 1 or -1";
16001
16911
  }
16002
16912
  if (s.include !== void 0) {
@@ -16256,7 +17166,7 @@ function definitionInSql(sql) {
16256
17166
  if (!at) return null;
16257
17167
  return sql.slice(at.index + at[0].length).replace(/\s+/g, " ").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")").trim();
16258
17168
  }
16259
- var rowsOf = (sql, query, ...bindings) => Array.from(sql.exec(query, ...bindings));
17169
+ var rowsOf = (sql, query, ...bindings2) => Array.from(sql.exec(query, ...bindings2));
16260
17170
  function usable(entry) {
16261
17171
  if (!isValidIdentifier(entry.model)) return `model '${entry.model}' is not an identifier`;
16262
17172
  const bad = entry.fields.find((field) => !isValidIdentifier(field));
@@ -16272,9 +17182,9 @@ function recordLogTextTableName(docId, model) {
16272
17182
  const part = (name) => `${name.length}_${name.toLowerCase()}`;
16273
17183
  return ["idx_record_log_text", part(docId), part(model)].join("_");
16274
17184
  }
16275
- function deviceTableFor(sql, key, canonical, previous) {
16276
- const held = previous.get(key);
16277
- if (held !== void 0) return held;
17185
+ function deviceTableFor(sql, key, canonical2, previous) {
17186
+ const held2 = previous.get(key);
17187
+ if (held2 !== void 0) return held2;
16278
17188
  const taken = (name) => rowsOf(sql, `SELECT 1 FROM sqlite_master WHERE name = ? COLLATE NOCASE`, name).length > 0 || rowsOf(
16279
17189
  sql,
16280
17190
  `SELECT 1 FROM record_log_indexes WHERE members = ? COLLATE NOCASE OR text = ? COLLATE NOCASE OR vector = ? COLLATE NOCASE`,
@@ -16282,8 +17192,8 @@ function deviceTableFor(sql, key, canonical, previous) {
16282
17192
  name,
16283
17193
  name
16284
17194
  ).length > 0 || [...previous.values()].some((other) => other.toLowerCase() === name.toLowerCase());
16285
- if (!taken(canonical)) return canonical;
16286
- for (let n = 2; ; n++) if (!taken(`${canonical}_${n}`)) return `${canonical}_${n}`;
17195
+ if (!taken(canonical2)) return canonical2;
17196
+ for (let n = 2; ; n++) if (!taken(`${canonical2}_${n}`)) return `${canonical2}_${n}`;
16287
17197
  }
16288
17198
  var memberKey = (model, field) => `members\0${model}\0${field}`;
16289
17199
  var textKey = (model) => `text\0${model}`;
@@ -16301,7 +17211,7 @@ function dispositionOf(row, deviceIndexes) {
16301
17211
  if (row.verdict === "accepted") return "build";
16302
17212
  return deviceIndexesExclude(deviceIndexes, row.kind) ? "keep" : "build";
16303
17213
  }
16304
- var cachedRows = (sql, where2 = "", ...bindings) => rowsOf(
17214
+ var cachedRows = (sql, where2 = "", ...bindings2) => rowsOf(
16305
17215
  sql,
16306
17216
  `SELECT i.doc_id, i.model, i.fields, i.kind, i.is_unique, i.room_name, i.members, i.text, i.vector, i.options, p.verdict, s.local_only
16307
17217
  FROM record_log_indexes i
@@ -16309,7 +17219,7 @@ var cachedRows = (sql, where2 = "", ...bindings) => rowsOf(
16309
17219
  LEFT JOIN record_log_state s ON s.doc_id = i.doc_id
16310
17220
  ${where2}
16311
17221
  ORDER BY i.doc_id, i.model, i.fields, i.kind`,
16312
- ...bindings
17222
+ ...bindings2
16313
17223
  );
16314
17224
  var optionsOf = (row) => row.options === null || row.options === void 0 ? null : JSON.parse(String(row.options));
16315
17225
  function entryOptionsText(options) {
@@ -16474,16 +17384,16 @@ function recordLogIndexSkips(sql, docId) {
16474
17384
  );
16475
17385
  }
16476
17386
  function heldDefinitions(sql) {
16477
- const held = /* @__PURE__ */ new Map();
17387
+ const held2 = /* @__PURE__ */ new Map();
16478
17388
  for (const row of rowsOf(sql, `SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL`)) {
16479
17389
  const name = String(row.name);
16480
17390
  if (!FAMILY.some((f) => f.table === row.tbl_name && name.startsWith(f.prefix))) continue;
16481
17391
  const definition = definitionInSql(String(row.sql));
16482
- if (definition !== null && !held.has(definition)) held.set(definition, name);
17392
+ if (definition !== null && !held2.has(definition)) held2.set(definition, name);
16483
17393
  }
16484
- return held;
17394
+ return held2;
16485
17395
  }
16486
- function wantedScalars(sql, deviceIndexes, held) {
17396
+ function wantedScalars(sql, deviceIndexes, held2) {
16487
17397
  const out = /* @__PURE__ */ new Map();
16488
17398
  for (const row of cachedRows(sql, `WHERE i.kind = 'scalar'`)) {
16489
17399
  const disposition = dispositionOf(row, deviceIndexes);
@@ -16491,7 +17401,7 @@ function wantedScalars(sql, deviceIndexes, held) {
16491
17401
  const model = String(row.model);
16492
17402
  const fields = JSON.parse(String(row.fields));
16493
17403
  const view = definitionOf("record_log_view", model, fields);
16494
- if (disposition === "keep" && !held.has(view)) continue;
17404
+ if (disposition === "keep" && !held2.has(view)) continue;
16495
17405
  let wanted2 = out.get(view);
16496
17406
  if (!wanted2) {
16497
17407
  wanted2 = {
@@ -16511,9 +17421,9 @@ function wantedScalars(sql, deviceIndexes, held) {
16511
17421
  }
16512
17422
  return out;
16513
17423
  }
16514
- function wanted(sql, deviceIndexes, held) {
17424
+ function wanted(sql, deviceIndexes, held2) {
16515
17425
  const out = /* @__PURE__ */ new Map();
16516
- for (const scalar of wantedScalars(sql, deviceIndexes, held).values()) {
17426
+ for (const scalar of wantedScalars(sql, deviceIndexes, held2).values()) {
16517
17427
  out.set(scalar.view.definition, scalar.view);
16518
17428
  if (scalar.rows) out.set(scalar.rows.definition, scalar.rows);
16519
17429
  }
@@ -16564,9 +17474,9 @@ function dropUnwanted(sql, deviceIndexes, support) {
16564
17474
  const table = String(row.text);
16565
17475
  const wantedText = wantedTextOf(row);
16566
17476
  const bodies = textTriggersDDL(table, wantedText);
16567
- const held = tables.get(table) === textTableDDL(table, wantedText.fields, wantedText.options) && TEXT_TRIGGERS.every((suffix, i) => triggers.get(`${table}${suffix}`) === bodies[i]);
17477
+ const held2 = tables.get(table) === textTableDDL(table, wantedText.fields, wantedText.options) && TEXT_TRIGGERS.every((suffix, i) => triggers.get(`${table}${suffix}`) === bodies[i]);
16568
17478
  const declined = dispositionOf(row, deviceIndexes) === "decline";
16569
- if (!declined && held && !texts.has(table)) {
17479
+ if (!declined && held2 && !texts.has(table)) {
16570
17480
  texts.add(table);
16571
17481
  if (wantedText.options.unbuilt !== void 0) markUnbuilt(sql, wantedText, null);
16572
17482
  continue;
@@ -16699,10 +17609,10 @@ function reportUnbuilt(subject, reason) {
16699
17609
  var messageOf = (error) => error instanceof Error ? error.message : String(error);
16700
17610
  function buildWanted(sql, support, deviceIndexes) {
16701
17611
  let created = 0;
16702
- const held = heldDefinitions(sql);
17612
+ const held2 = heldDefinitions(sql);
16703
17613
  const taken = new Set(rowsOf(sql, `SELECT name FROM sqlite_master WHERE type = 'index'`).map((row) => String(row.name)));
16704
- for (const scalar of wantedScalars(sql, deviceIndexes, held).values()) {
16705
- const missing = [scalar.view, ...scalar.rows ? [scalar.rows] : []].filter((index) => !held.has(index.definition));
17614
+ for (const scalar of wantedScalars(sql, deviceIndexes, held2).values()) {
17615
+ const missing = [scalar.view, ...scalar.rows ? [scalar.rows] : []].filter((index) => !held2.has(index.definition));
16706
17616
  const rows = () => cachedRows(sql, `WHERE i.kind = 'scalar' AND i.model = ? AND i.fields = ?`, scalar.model, JSON.stringify(scalar.fields)).filter(
16707
17617
  (row) => dispositionOf(row, deviceIndexes) === "build"
16708
17618
  );
@@ -17019,11 +17929,11 @@ function recordLogTextIndexOf(sql, docId, model, deviceIndexes) {
17019
17929
  if (!row) return null;
17020
17930
  const options = JSON.parse(String(row.options));
17021
17931
  const table = row.text === null || row.text === void 0 ? null : String(row.text);
17022
- const held = table !== null && options.unbuilt === void 0 && rowsOf(sql, `SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`, table).length > 0;
17932
+ const held2 = table !== null && options.unbuilt === void 0 && rowsOf(sql, `SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?`, table).length > 0;
17023
17933
  const disposition = dispositionOf(row, deviceIndexes);
17024
- const declined = disposition === "decline" ? DECLINED_HERE : disposition === "keep" && !held ? excludedByOption("text") : void 0;
17934
+ const declined = disposition === "decline" ? DECLINED_HERE : disposition === "keep" && !held2 ? excludedByOption("text") : void 0;
17025
17935
  return {
17026
- table: held ? table : null,
17936
+ table: held2 ? table : null,
17027
17937
  fields: JSON.parse(String(row.fields)),
17028
17938
  options,
17029
17939
  roomName: String(row.room_name),
@@ -17082,17 +17992,17 @@ function placementOf(row) {
17082
17992
  if (Number(row.local_only ?? 0) === 1) return "device";
17083
17993
  return optionsOf(row)?.on ?? "both";
17084
17994
  }
17085
- function statusOf(row, deviceIndexes, held) {
17995
+ function statusOf(row, deviceIndexes, held2) {
17086
17996
  const fields = JSON.parse(String(row.fields));
17087
17997
  const kind = String(row.kind);
17088
17998
  const base = { name: String(row.room_name), model: String(row.model), fields, kind, on: placementOf(row) };
17089
17999
  const disposition = dispositionOf(row, deviceIndexes);
17090
18000
  if (disposition === "decline") return { ...base, status: "declined", reason: DECLINED_HERE };
17091
18001
  const options = optionsOf(row) ?? {};
17092
- const built = kind === "scalar" ? held.definitions.has(definitionOf("record_log_view", base.model, fields)) : kind === "members" ? row.members !== null && row.members !== void 0 && memberTableHeld(held.memberTables, held.memberTriggers, String(row.members)) : kind === "text" ? row.text !== null && row.text !== void 0 && options.unbuilt === void 0 && held.texts.has(String(row.text)) : row.vector !== null && row.vector !== void 0 && options.unbuilt === void 0 && held.vectors.has(String(row.vector));
18002
+ const built = kind === "scalar" ? held2.definitions.has(definitionOf("record_log_view", base.model, fields)) : kind === "members" ? row.members !== null && row.members !== void 0 && memberTableHeld(held2.memberTables, held2.memberTriggers, String(row.members)) : kind === "text" ? row.text !== null && row.text !== void 0 && options.unbuilt === void 0 && held2.texts.has(String(row.text)) : row.vector !== null && row.vector !== void 0 && options.unbuilt === void 0 && held2.vectors.has(String(row.vector));
17093
18003
  if (built && kind === "vector") {
17094
18004
  const vector = options;
17095
- const installed = !!vector.ann && held.vectors.has(annTableOf(String(row.vector)));
18005
+ const installed = !!vector.ann && held2.vectors.has(annTableOf(String(row.vector)));
17096
18006
  if (installed && vector.fill) return { ...base, status: "building", mode: "exact" };
17097
18007
  return { ...base, status: "built", mode: installed ? "ann" : "exact" };
17098
18008
  }
@@ -17120,24 +18030,24 @@ function heldObjects(sql) {
17120
18030
  };
17121
18031
  }
17122
18032
  function recordLogIndexStatuses(sql, docId, deviceIndexes) {
17123
- const held = heldObjects(sql);
17124
- return cachedRows(sql, `WHERE i.doc_id = ?`, docId).filter((row) => placementOf(row) !== "server").map((row) => statusOf(row, deviceIndexes, held)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
18033
+ const held2 = heldObjects(sql);
18034
+ return cachedRows(sql, `WHERE i.doc_id = ?`, docId).filter((row) => placementOf(row) !== "server").map((row) => statusOf(row, deviceIndexes, held2)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
17125
18035
  }
17126
18036
  function recordLogNamedIndex(sql, docId, name, deviceIndexes) {
17127
18037
  const [row] = cachedRows(sql, `WHERE i.doc_id = ? AND i.room_name = ?`, docId, name);
17128
18038
  if (!row) return null;
17129
- const held = heldObjects(sql);
17130
- const status = statusOf(row, deviceIndexes, held);
17131
- const object = status.status !== "built" ? null : row.kind === "scalar" ? held.definitions.get(definitionOf("record_log_view", status.model, status.fields)) ?? null : row.kind === "members" ? String(row.members) : null;
18039
+ const held2 = heldObjects(sql);
18040
+ const status = statusOf(row, deviceIndexes, held2);
18041
+ const object = status.status !== "built" ? null : row.kind === "scalar" ? held2.definitions.get(definitionOf("record_log_view", status.model, status.fields)) ?? null : row.kind === "members" ? String(row.members) : null;
17132
18042
  return { status, object };
17133
18043
  }
17134
18044
  function recordLogRegistryNames(sql, docId) {
17135
- const held = heldDefinitions(sql);
18045
+ const held2 = heldDefinitions(sql);
17136
18046
  const names = /* @__PURE__ */ new Map();
17137
18047
  for (const row of cachedRows(sql, `WHERE i.doc_id = ?`, docId)) {
17138
18048
  const name = String(row.room_name);
17139
18049
  if (row.kind === "scalar") {
17140
- const object = held.get(definitionOf("record_log_view", String(row.model), JSON.parse(String(row.fields))));
18050
+ const object = held2.get(definitionOf("record_log_view", String(row.model), JSON.parse(String(row.fields))));
17141
18051
  if (object !== void 0) names.set(object, name);
17142
18052
  }
17143
18053
  for (const column of ["members", "text", "vector"]) {
@@ -17221,8 +18131,8 @@ var RECORD_LOG_GROWTH_STATISTICS_MIN_ROWS = 1e3;
17221
18131
  var RECORD_LOG_GROWTH_STATISTICS_FACTOR = 10;
17222
18132
  var highestViewRowid = (sql) => Number(rowsOf(sql, `SELECT MAX(rowid) AS n FROM record_log_view`)[0]?.n ?? 0);
17223
18133
  function heldMemberTables(sql) {
17224
- const held = new Set(familyNames(sql, "table"));
17225
- return rowsOf(sql, `SELECT DISTINCT members FROM record_log_indexes WHERE members IS NOT NULL ORDER BY members`).map((row) => String(row.members)).filter((table) => held.has(table));
18134
+ const held2 = new Set(familyNames(sql, "table"));
18135
+ return rowsOf(sql, `SELECT DISTINCT members FROM record_log_indexes WHERE members IS NOT NULL ORDER BY members`).map((row) => String(row.members)).filter((table) => held2.has(table));
17226
18136
  }
17227
18137
  function gatherRecordLogStatistics(sql) {
17228
18138
  try {
@@ -17325,7 +18235,9 @@ function db3ViewTranslator(model, options = {}) {
17325
18235
  ...options.facetTiesByMember ? { facetTiesByMember: true } : {},
17326
18236
  ...options.textIndex ? { textIndex: options.textIndex } : {},
17327
18237
  ...options.vectorIndex ? { vectorIndex: options.vectorIndex } : {},
17328
- ...options.indexHint ? { indexHint: options.indexHint } : {}
18238
+ ...options.indexHint ? { indexHint: options.indexHint } : {},
18239
+ ...options.unsetFields?.size ? { unsetFields: options.unsetFields } : {},
18240
+ ...options.unsetFields?.size && options.unsetFieldDocuments?.size ? { unsetFieldDocuments: options.unsetFieldDocuments } : {}
17329
18241
  });
17330
18242
  }
17331
18243
  function searchIndexOf(sql, model, documents, support, deviceIndexes) {
@@ -17416,11 +18328,11 @@ function declaredFieldOf(sql, docId, model, field) {
17416
18328
  const [state] = Array.from(sql.exec(`SELECT typed, db3_type FROM record_log_state WHERE doc_id = ?`, docId));
17417
18329
  if (state?.typed !== "yes" || typeof state.db3_type !== "string") return null;
17418
18330
  try {
17419
- const held = JSON.parse(state.db3_type);
17420
- const fields = held.models?.[model];
18331
+ const held2 = JSON.parse(state.db3_type);
18332
+ const fields = held2.models?.[model];
17421
18333
  if (!fields) return null;
17422
18334
  const kind = Object.prototype.hasOwnProperty.call(fields, field) ? fields[field] : null;
17423
- const dims = held.vectors?.[model]?.[field]?.dims;
18335
+ const dims = held2.vectors?.[model]?.[field]?.dims;
17424
18336
  return { kind, ...typeof dims === "number" ? { dims } : {} };
17425
18337
  } catch {
17426
18338
  return null;
@@ -17468,7 +18380,8 @@ function readViewPage(sql, model, filter, options, limits = {}, support, deviceI
17468
18380
  const excluding = selected !== void 0 && Object.values(selected).every((value) => value === 0);
17469
18381
  const direction = options.direction === -1 ? -1 : 1;
17470
18382
  const textIndex = searchedIndex(sql, model, filter, options.documents, support, deviceIndexes);
17471
- const find = (local2) => db3ViewTranslator(model, { tieBreak: true, ...local2, ...forcedOptions(sql, model) }).translateFind(filter, {
18383
+ let unset;
18384
+ const find = (local2) => db3ViewTranslator(model, { tieBreak: true, ...local2, ...forcedOptions(sql, model), ...unset }).translateFind(filter, {
17472
18385
  ...options.sort ? { sort: options.sort } : {},
17473
18386
  ...selected ? { projection: selected } : {},
17474
18387
  ...options.uniqueStartKey ? { uniqueStartKey: options.uniqueStartKey } : {},
@@ -17477,7 +18390,9 @@ function readViewPage(sql, model, filter, options, limits = {}, support, deviceI
17477
18390
  direction,
17478
18391
  documents: [...options.documents]
17479
18392
  });
17480
- const judged = find({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18393
+ let judged = find({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18394
+ unset = clearedReadOf(sql, model, options.documents);
18395
+ if (unset) judged = find({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
17481
18396
  const local = deviceIndexReadOptions(sql, model, options.documents, textIndex, vectorIndex);
17482
18397
  const query = local.memberIndexTable ? find(local) : judged;
17483
18398
  const aliased = query.cursorSortValueFields ?? [];
@@ -17516,6 +18431,11 @@ function readViewPage(sql, model, filter, options, limits = {}, support, deviceI
17516
18431
  mint = { ...mint, _distance: distance };
17517
18432
  }
17518
18433
  row = canonicalSets(row, setFields);
18434
+ if (unset) {
18435
+ const cleared = heldClearedOf(sql, String(docId))?.get(model);
18436
+ row = withoutNames(row, cleared);
18437
+ mint = withoutNames(mint, cleared);
18438
+ }
17519
18439
  const bytes = jsonBytes(row);
17520
18440
  if (rows.length > 0 && used + bytes > policy.budgetBytes) {
17521
18441
  hasMore = true;
@@ -17564,13 +18484,16 @@ function resolvePageIncludes(sql, model, rows, documents, includes, policy, used
17564
18484
  const budget = { limit: policy.budgetBytes, used };
17565
18485
  for (const [docId, parents] of groups) {
17566
18486
  const source = {
17567
- translator: (related, path) => db3ViewTranslator(related, { document: docId, ...forcedOptions(sql, related, path) }),
18487
+ translator: (related, path) => {
18488
+ const unsetFields = heldClearedOf(sql, docId)?.get(related);
18489
+ return db3ViewTranslator(related, { document: docId, ...forcedOptions(sql, related, path), ...unsetFields ? { unsetFields } : {} });
18490
+ },
17568
18491
  exec: (text, params) => sql.exec(text, ...params),
17569
- // A related row answers as a parent row does: its fields, no `type`.
17570
- decodeRow: (_related, row) => {
18492
+ // A related row answers as a parent row does: its fields, no `type`, none the db3's type clears.
18493
+ decodeRow: (related, row) => {
17571
18494
  const { type: _type, ...fields } = parseRecordRow(row);
17572
18495
  void _type;
17573
- return fields;
18496
+ return withoutNames(fields, heldClearedOf(sql, docId)?.get(related));
17574
18497
  }
17575
18498
  };
17576
18499
  resolveIncludes(
@@ -17605,8 +18528,8 @@ function includedJsonBytes(records) {
17605
18528
  const recordBytes = (record) => {
17606
18529
  const known = sizes.get(record);
17607
18530
  if (known !== void 0) return known;
17608
- const { _related: related, ...own2 } = record;
17609
- let bytes2 = jsonBytes(own2);
18531
+ const { _related: related, ...own3 } = record;
18532
+ let bytes2 = jsonBytes(own3);
17610
18533
  if (related !== void 0 && related !== null && typeof related === "object" && !Array.isArray(related)) {
17611
18534
  let inner = 2;
17612
18535
  let entries = 0;
@@ -17654,8 +18577,13 @@ function readDocumentSync(sql, documents) {
17654
18577
  function countViewRows(sql, model, filter, documents, support, deviceIndexes) {
17655
18578
  const vectorIndex = nearIndexOf(sql, model, filter, void 0, documents, support, deviceIndexes);
17656
18579
  const textIndex = searchedIndex(sql, model, filter, documents, support, deviceIndexes);
17657
- const count = (local2) => db3ViewTranslator(model, { ...local2, ...forcedOptions(sql, model) }).translateCount(filter, { documents: [...documents] });
17658
- const judged = count({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18580
+ let unset;
18581
+ const count = (local2) => db3ViewTranslator(model, { ...local2, ...forcedOptions(sql, model), ...unset }).translateCount(filter, {
18582
+ documents: [...documents]
18583
+ });
18584
+ let judged = count({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18585
+ unset = clearedReadOf(sql, model, documents);
18586
+ if (unset) judged = count({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
17659
18587
  const local = deviceIndexReadOptions(sql, model, documents, textIndex, vectorIndex);
17660
18588
  const { sql: text, params } = local.memberIndexTable ? count(local) : judged;
17661
18589
  const [row] = Array.from(sql.exec(text, ...params));
@@ -17667,11 +18595,16 @@ function aggregateViewRows(sql, model, options, documents, setFields = [], limit
17667
18595
  const sets = new Set(setFields);
17668
18596
  const vectorIndex = nearIndexOf(sql, model, options.filter, void 0, documents, support, deviceIndexes);
17669
18597
  const textIndex = searchedIndex(sql, model, options.filter, documents, support, deviceIndexes);
17670
- const aggregate = (local2) => buildAggregate(db3ViewTranslator(model, { ...local2, ...forcedOptions(sql, model) }).aggregateSource({ isSetField: (field) => sets.has(field) }), {
17671
- ...options,
17672
- documents: [...documents]
17673
- });
17674
- const judged = aggregate({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18598
+ let unset;
18599
+ const aggregate = (local2) => buildAggregate(
18600
+ db3ViewTranslator(model, { ...local2, ...forcedOptions(sql, model), ...unset }).aggregateSource({
18601
+ isSetField: (field) => sets.has(field)
18602
+ }),
18603
+ { ...options, documents: [...documents] }
18604
+ );
18605
+ let judged = aggregate({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
18606
+ unset = clearedReadOf(sql, model, documents);
18607
+ if (unset) judged = aggregate({ ...textIndex ? { textIndex } : {}, ...vectorIndex ? { vectorIndex } : {} });
17675
18608
  const local = deviceIndexReadOptions(sql, model, documents, textIndex, vectorIndex);
17676
18609
  const plan = local.memberIndexTable ? aggregate(local) : judged;
17677
18610
  const sqlRows = Array.from(sql.exec(plan.sql, ...plan.params));
@@ -17700,16 +18633,16 @@ var RecordLogExplainRefusal = class _RecordLogExplainRefusal extends DocumentQue
17700
18633
  };
17701
18634
  var RECORD_LOG_VIEW_PRIMARY_KEY_INDEX = "sqlite_autoindex_record_log_view_1";
17702
18635
  var OPS = ["query", "count", "aggregate"];
17703
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
18636
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
17704
18637
  var invalid = (message, details = {}) => new RecordLogExplainRefusal("INVALID_ARGUMENT", 400, message, details);
17705
18638
  function checkedRequest(model, request) {
17706
- if (!isObject(request)) throw invalid("explain takes a request object: { op, filter?, options?, aggregate?, index?, setFields? }");
18639
+ if (!isObject2(request)) throw invalid("explain takes a request object: { op, filter?, options?, aggregate?, index?, setFields? }");
17707
18640
  const { op, filter, options, aggregate, index, setFields } = request;
17708
18641
  if (typeof model !== "string" || model.length === 0) throw invalid("explain takes a model name");
17709
18642
  if (!OPS.includes(op)) throw invalid("op must be query, count or aggregate", { op });
17710
- if (filter !== void 0 && !isObject(filter)) throw invalid("filter must be an object");
17711
- if (options !== void 0 && !isObject(options)) throw invalid("options must be an object");
17712
- if (aggregate !== void 0 && !isObject(aggregate)) throw invalid("aggregate must be an object");
18643
+ if (filter !== void 0 && !isObject2(filter)) throw invalid("filter must be an object");
18644
+ if (options !== void 0 && !isObject2(options)) throw invalid("options must be an object");
18645
+ if (aggregate !== void 0 && !isObject2(aggregate)) throw invalid("aggregate must be an object");
17713
18646
  if (index !== void 0 && index !== null && (typeof index !== "string" || index.length === 0)) {
17714
18647
  throw invalid("index must be an index name or none", { index });
17715
18648
  }
@@ -17724,7 +18657,7 @@ function filterFields(filter, into) {
17724
18657
  for (const branch of filter) filterFields(branch, into);
17725
18658
  return;
17726
18659
  }
17727
- if (!isObject(filter)) return;
18660
+ if (!isObject2(filter)) return;
17728
18661
  for (const [key, value] of Object.entries(filter)) {
17729
18662
  if (key === "$search") continue;
17730
18663
  if (key.startsWith("$")) filterFields(value, into);
@@ -17734,12 +18667,12 @@ function filterFields(filter, into) {
17734
18667
  function aggregateOutputKeys(aggregate) {
17735
18668
  const keys = /* @__PURE__ */ new Set(["count"]);
17736
18669
  for (const operation of aggregate.operations ?? []) {
17737
- if (isObject(operation) && typeof operation.type === "string") {
18670
+ if (isObject2(operation) && typeof operation.type === "string") {
17738
18671
  keys.add(operation.type === "count" ? "count" : `${operation.type}_${String(operation.field)}`);
17739
18672
  }
17740
18673
  }
17741
18674
  (aggregate.groupBy ?? []).forEach((level, index) => {
17742
- if (!isObject(level) || typeof level.field !== "string") return;
18675
+ if (!isObject2(level) || typeof level.field !== "string") return;
17743
18676
  if (typeof level.period === "string") keys.add(`${level.field}_${level.period}`);
17744
18677
  if (typeof level.contains === "string") {
17745
18678
  keys.add(`ss_${level.field}_${index}`);
@@ -17756,14 +18689,14 @@ function fieldsOfRead(request) {
17756
18689
  filterFields(aggregate.filter, fields);
17757
18690
  for (const level of aggregate.groupBy ?? []) {
17758
18691
  if (typeof level === "string") fields.add(level);
17759
- else if (isObject(level) && typeof level.field === "string") fields.add(level.field);
18692
+ else if (isObject2(level) && typeof level.field === "string") fields.add(level.field);
17760
18693
  }
17761
- const sort = isObject(aggregate.sort) ? aggregate.sort.field : void 0;
18694
+ const sort = isObject2(aggregate.sort) ? aggregate.sort.field : void 0;
17762
18695
  if (typeof sort === "string" && !aggregateOutputKeys(aggregate).has(sort)) fields.add(sort);
17763
18696
  return fields;
17764
18697
  }
17765
18698
  filterFields(request.filter, fields);
17766
- if (request.op === "query" && isObject(request.options?.sort)) {
18699
+ if (request.op === "query" && isObject2(request.options?.sort)) {
17767
18700
  for (const field of Object.keys(request.options.sort)) fields.add(field);
17768
18701
  }
17769
18702
  return fields;
@@ -17889,9 +18822,9 @@ function recordingHandle(sql, force, root) {
17889
18822
  let building = { model: root };
17890
18823
  const handle = forceViewReads(
17891
18824
  {
17892
- exec: (query, ...bindings) => {
17893
- if (reportedStatement(query)) runs.push({ ...building, sql: query, bindings });
17894
- return sql.exec(query, ...bindings);
18825
+ exec: (query, ...bindings2) => {
18826
+ if (reportedStatement(query)) runs.push({ ...building, sql: query, bindings: bindings2 });
18827
+ return sql.exec(query, ...bindings2);
17895
18828
  },
17896
18829
  transaction: (fn) => sql.transaction(fn)
17897
18830
  },
@@ -17942,8 +18875,8 @@ function explainViewRead(sql, docId, model, request, setFields, context = {}) {
17942
18875
  }
17943
18876
  throw error;
17944
18877
  }
17945
- const quoted3 = (name) => `"${name.replace(/"/g, '""')}"`;
17946
- if (planned?.memberTable !== void 0 && !runs.some((run) => run.sql.includes(quoted3(planned.memberTable)))) {
18878
+ const quoted4 = (name) => `"${name.replace(/"/g, '""')}"`;
18879
+ if (planned?.memberTable !== void 0 && !runs.some((run) => run.sql.includes(quoted4(planned.memberTable)))) {
17947
18880
  throw cannotServe(
17948
18881
  checked.index,
17949
18882
  model,
@@ -17951,7 +18884,7 @@ function explainViewRead(sql, docId, model, request, setFields, context = {}) {
17951
18884
  `The member index ${checked.index} serves $contains, any-of, a membership level or an unfiltered facet on its field; this read has none`
17952
18885
  );
17953
18886
  }
17954
- if (planned?.scalarIndex !== void 0 && !runs.some((run) => run.sql.includes(`INDEXED BY ${quoted3(planned.scalarIndex)}`))) {
18887
+ if (planned?.scalarIndex !== void 0 && !runs.some((run) => run.sql.includes(`INDEXED BY ${quoted4(planned.scalarIndex)}`))) {
17955
18888
  throw cannotServe(checked.index, model, "shape", `The index ${checked.index} is a field index, and no statement of this read reads ${model}'s records to take it`);
17956
18889
  }
17957
18890
  const registry = recordLogRegistryNames(sql, docId);
@@ -18039,7 +18972,7 @@ function traceViewRead(sql, documents, model, read) {
18039
18972
  init_logger();
18040
18973
  init_schema();
18041
18974
  init_vectorIndex();
18042
- var rowsOf2 = (sql, query, ...bindings) => Array.from(sql.exec(query, ...bindings));
18975
+ var rowsOf2 = (sql, query, ...bindings2) => Array.from(sql.exec(query, ...bindings2));
18043
18976
  var optionsOf2 = (row) => row.options === null || row.options === void 0 ? { on: "device" } : JSON.parse(String(row.options));
18044
18977
  var STORAGE_FAILURE_CODES = /* @__PURE__ */ new Set([5, 6, 8, 9, 10, 13, 14]);
18045
18978
  var STORAGE_FAILURE_NAMES = /^SQLITE_(BUSY|LOCKED|READONLY|INTERRUPT|IOERR|FULL|CANTOPEN)(_|$)/;
@@ -18084,11 +19017,11 @@ function vectorModelWants(sql, docId, deviceIndexes, now = Date.now()) {
18084
19017
  if (row.vector === null || row.vector === void 0 || !builtByPolicy(row, deviceIndexes)) continue;
18085
19018
  const options = optionsOf2(row);
18086
19019
  if (!options.vector || !isAnnIndex(options.vector.index) || options.unbuilt !== void 0 || options.fill) continue;
18087
- const held = trainingHeld(options, now);
19020
+ const held2 = trainingHeld(options, now);
18088
19021
  const name = String(row.room_name);
18089
19022
  const localOnly = Number(row.local_only ?? 0) === 1;
18090
19023
  if (localOnly) {
18091
- if (held || options.ann || options.refused) continue;
19024
+ if (held2 || options.ann || options.refused) continue;
18092
19025
  } else {
18093
19026
  const generation = options.generation;
18094
19027
  if (generation === void 0 || options.revision === void 0) continue;
@@ -18099,7 +19032,7 @@ function vectorModelWants(sql, docId, deviceIndexes, now = Date.now()) {
18099
19032
  wants.push({ name, want: "fetch", generation, revision });
18100
19033
  continue;
18101
19034
  }
18102
- if (held || options.ann) continue;
19035
+ if (held2 || options.ann) continue;
18103
19036
  if (options.refused && options.refused.generation === generation && options.refused.revision === options.revision) continue;
18104
19037
  }
18105
19038
  const rows = liveRows(sql, row);
@@ -18447,6 +19380,58 @@ var RecordLogClient = class {
18447
19380
  if (entry?.void) this.tables.deletePending(this.writer, seq);
18448
19381
  return { touched: [] };
18449
19382
  }
19383
+ /**
19384
+ * Apply model clears a catch-up carries, oldest first, before the rows,
19385
+ * chunks or page they ride with. The cursor does not move: the catch-up's
19386
+ * completion moves it. A clear at or below the cursor, or at or below the
19387
+ * highest clear applied (a resumed download is sent the clears again),
19388
+ * changes nothing.
19389
+ */
19390
+ applyClears(clears) {
19391
+ const out = { touched: [] };
19392
+ const ordered = [...clears].sort((a, b) => a.l - b.l);
19393
+ for (const clear of ordered) {
19394
+ if (clear.l <= this.tables.cursor()) continue;
19395
+ if (this.applyClear(clear.model, clear.l, out)) this.sawEpoch(clear.e);
19396
+ }
19397
+ return out;
19398
+ }
19399
+ /**
19400
+ * Empty `model` for the clear at log number `l`, unless a clear at or past
19401
+ * `l` was applied already; the mark moves with the removal. Answers
19402
+ * whether it removed.
19403
+ */
19404
+ applyClear(model, l, out) {
19405
+ if (l <= this.tables.clearedThrough()) return false;
19406
+ this.changedUnderReplacement({});
19407
+ out.touched.push(...this.tables.clearModel(model));
19408
+ this.tables.setClearedThrough(l, model);
19409
+ if (!(out.cleared ??= []).includes(model)) out.cleared.push(model);
19410
+ return true;
19411
+ }
19412
+ /**
19413
+ * Whether a clear of `model` above log number `l` was applied already: a
19414
+ * catch-up applies the clears it carries before the cursor reaches them,
19415
+ * so a session sharing this store can still be handed results below one.
19416
+ * Such a result's rows of the model were removed by the clear on the room,
19417
+ * and stay removed here.
19418
+ */
19419
+ clearedPast(model, l) {
19420
+ return this.tables.clearedAt(model) > l;
19421
+ }
19422
+ /**
19423
+ * Whether rows of `model` the room read at log number `readAt` (a page's
19424
+ * `lsn`, a load's last log number, a segment's `C`) predate a clear of it
19425
+ * applied already. Another session sharing this store applied that clear
19426
+ * from its own catch-up; the room removed those rows with it and keeps no
19427
+ * tombstone, so putting them back here would keep them for good; and a row
19428
+ * of the model the store holds now was written after the clear, so a
19429
+ * removal read before it does not apply either. Without `readAt` (a caller
19430
+ * that did not say) everything applies.
19431
+ */
19432
+ readBeforeClear(model, readAt) {
19433
+ return readAt !== void 0 && this.clearedPast(model, readAt);
19434
+ }
18450
19435
  /**
18451
19436
  * Something the room relayed. A result is applied to the confirmed rows in
18452
19437
  * log-number order (one ahead of the cursor waits; one at or below it was
@@ -18457,7 +19442,8 @@ var RecordLogClient = class {
18457
19442
  *
18458
19443
  * A compact acknowledgement (no `changes`) is applied, in its turn, by its
18459
19444
  * pending entry's mutations as plain row operations, the rule by which the
18460
- * room vouched for it. With no unwithdrawn pending entry for its `seq` it
19445
+ * room vouched for it. A model clear empties its model in its turn, once
19446
+ * ({@link applyClears}). With no unwithdrawn pending entry for its `seq` it
18461
19447
  * stays buffered, the cursor stops below it, and the outcome names it
18462
19448
  * (`underivable`).
18463
19449
  */
@@ -18496,9 +19482,11 @@ var RecordLogClient = class {
18496
19482
  for (let next = this.tables.buffered(this.tables.cursor() + 1); next; next = this.tables.buffered(this.tables.cursor() + 1)) {
18497
19483
  if (!applied) this.changedUnderReplacement({});
18498
19484
  applied = true;
18499
- if (next.changes) {
19485
+ if (next.clear) {
19486
+ this.applyClear(next.clear.model, next.l, out);
19487
+ } else if (next.changes) {
18500
19488
  for (const change of next.changes) {
18501
- applyChange(confirmed, change);
19489
+ if (!this.clearedPast(change.model, next.l)) applyChange(confirmed, change);
18502
19490
  out.touched.push({ model: change.model, id: change.id });
18503
19491
  }
18504
19492
  } else if (!this.applyOwnEntry(confirmed, next, out)) {
@@ -18529,6 +19517,10 @@ var RecordLogClient = class {
18529
19517
  if (!entry || entry.void) return false;
18530
19518
  for (const m of mutationsOf(entry)) {
18531
19519
  const key = { model: m.model, id: m.id };
19520
+ if (this.clearedPast(m.model, item.l)) {
19521
+ out.touched.push(key);
19522
+ continue;
19523
+ }
18532
19524
  const row = plainRowAfter(confirmed.row(key), m);
18533
19525
  if (row) confirmed.set(key, row);
18534
19526
  else if (m.kind === "delete") confirmed.delete(key);
@@ -18688,6 +19680,10 @@ var RecordLogClient = class {
18688
19680
  * cursor. A page of receipt `receipt`'s remainder is refused with
18689
19681
  * {@link RecordLogStaleReceiptError} before anything changes once another
18690
19682
  * attempt took that receipt over; it does not count as the attempt's change.
19683
+ * A row or gone record of a model whose clear above `readAt` (the log number
19684
+ * the room read the page at) was applied already changes nothing
19685
+ * ({@link readBeforeClear}): a row of it the store holds now was written
19686
+ * after the clear.
18691
19687
  */
18692
19688
  applyCatchUpPage(page) {
18693
19689
  this.assertNotDisplaced(page.receipt);
@@ -18696,10 +19692,12 @@ var RecordLogClient = class {
18696
19692
  const confirmed = this.tables.confirmed();
18697
19693
  const touched = [];
18698
19694
  for (const { model, id, row } of page.rows) {
19695
+ if (this.readBeforeClear(model, page.readAt)) continue;
18699
19696
  confirmed.set({ model, id }, { ...row });
18700
19697
  touched.push({ model, id });
18701
19698
  }
18702
19699
  for (const key of page.gone ?? []) {
19700
+ if (this.readBeforeClear(key.model, page.readAt)) continue;
18703
19701
  confirmed.delete(key);
18704
19702
  touched.push({ model: key.model, id: key.id });
18705
19703
  }
@@ -18727,6 +19725,7 @@ var RecordLogClient = class {
18727
19725
  if (next) {
18728
19726
  const replay = this.receive(next);
18729
19727
  out.touched.push(...replay.touched);
19728
+ if (replay.cleared?.length) out.cleared = [.../* @__PURE__ */ new Set([...out.cleared ?? [], ...replay.cleared])];
18730
19729
  out.acknowledged.push(...replay.acknowledged);
18731
19730
  out.settled.push(...replay.settled);
18732
19731
  if (replay.settlements) (out.settlements ??= []).push(...replay.settlements);
@@ -18750,13 +19749,13 @@ var RecordLogClient = class {
18750
19749
  * replacement every one whose last change came before it began. The
18751
19750
  * records a dropped attempt's load named are forgotten with it.
18752
19751
  */
18753
- settleReceipts(full, own2) {
19752
+ settleReceipts(full, own3) {
18754
19753
  const tables = this.tables;
18755
19754
  const state = tables.receipts?.() ?? null;
18756
19755
  if (!state || !tables.setReceipts) return;
18757
19756
  const since = full ? state.since : null;
18758
- const mine = own2 === void 0 ? void 0 : state.attempts.find((a) => a.attempt === own2);
18759
- const ended = (a) => a.attempt === own2 || mine !== void 0 && a.kind === mine.kind && a.id === mine.id && a.last <= mine.last || since !== null && a.last <= since;
19757
+ const mine = own3 === void 0 ? void 0 : state.attempts.find((a) => a.attempt === own3);
19758
+ const ended = (a) => a.attempt === own3 || mine !== void 0 && a.kind === mine.kind && a.id === mine.id && a.last <= mine.last || since !== null && a.last <= since;
18760
19759
  const attempts = state.attempts.filter((a) => !ended(a));
18761
19760
  const nextSince = full ? null : state.since;
18762
19761
  if (attempts.length === state.attempts.length && nextSince === state.since) return;
@@ -18916,20 +19915,24 @@ var RecordLogClient = class {
18916
19915
  * with each member once, as the room stores it (#5274). Each key is
18917
19916
  * remembered for a refresh, unless the load's `mode` is `merge`, whose
18918
19917
  * completion removes nothing. An attempt no longer in progress is refused
18919
- * with {@link RecordLogStaleReceiptError} before anything changes.
19918
+ * with {@link RecordLogStaleReceiptError} before anything changes. A chunk
19919
+ * of a model whose clear above `readAt` (the load's last log number) was
19920
+ * applied already changes no row ({@link readBeforeClear}); it still counts
19921
+ * as the attempt's chunk and names its keys.
18920
19922
  *
18921
19923
  * @returns The records whose confirmed row changed.
18922
19924
  */
18923
19925
  applyLoadLines(chunk) {
18924
19926
  const tables = this.receiptTables();
18925
19927
  this.touchReceipt(chunk.attempt, { chunk: true });
19928
+ const lines = this.readBeforeClear(chunk.model, chunk.readAt) ? [] : chunk.lines;
18926
19929
  const batch = this.batchRows(
18927
- chunk.lines.map(({ id }) => ({ model: chunk.model, id })),
19930
+ lines.map(({ id }) => ({ model: chunk.model, id })),
18928
19931
  true
18929
19932
  );
18930
19933
  const confirmed = batch ?? this.tables.confirmed();
18931
19934
  const touched = [];
18932
- for (const { id, patch } of chunk.lines) {
19935
+ for (const { id, patch } of lines) {
18933
19936
  const key = { model: chunk.model, id };
18934
19937
  const existing = confirmed.row(key);
18935
19938
  if (patch._deleted === true) {
@@ -18985,14 +19988,20 @@ var RecordLogClient = class {
18985
19988
  tables.forgetLoad(load2.attempt);
18986
19989
  return { touched };
18987
19990
  }
18988
- /** Put a segment's rows under the replacement `generation`, as receipt `attempt` when it names one. */
19991
+ /**
19992
+ * Put a segment's rows under the replacement `generation`, as receipt
19993
+ * `attempt` when it names one; a row of a model whose clear above `readAt`
19994
+ * (the segment's `C`) was applied already is not put back
19995
+ * ({@link readBeforeClear}).
19996
+ */
18989
19997
  applySegmentRows(segment) {
18990
19998
  this.assertGeneration(segment.generation);
18991
19999
  if (segment.attempt !== void 0) this.touchReceipt(segment.attempt, { chunk: true });
18992
- const batch = this.batchRows(segment.rows, false);
20000
+ const rows = segment.rows.filter(({ model }) => !this.readBeforeClear(model, segment.readAt));
20001
+ const batch = this.batchRows(rows, false);
18993
20002
  const confirmed = batch ?? this.tables.confirmed();
18994
20003
  const touched = [];
18995
- for (const { model, id, row } of segment.rows) {
20004
+ for (const { model, id, row } of rows) {
18996
20005
  confirmed.set({ model, id }, { ...row, id });
18997
20006
  touched.push({ model, id });
18998
20007
  }
@@ -19016,6 +20025,7 @@ var RecordLogClient = class {
19016
20025
  this.assertGeneration(chunk.generation);
19017
20026
  const state = this.receiptTables().receipts();
19018
20027
  if (!state || !state.attempts.some((a) => a.attempt === chunk.attempt)) throw new RecordLogStaleReceiptError(chunk.attempt);
20028
+ if (this.readBeforeClear(chunk.model, chunk.readAt)) return { mismatch: true };
19019
20029
  const entry = this.tables.heldSegment?.()?.chunks.find((c) => c.object === chunk.object);
19020
20030
  const same = entry !== void 0 && entry.model === chunk.model && entry.sha256 === chunk.sha256 && entry.rows === chunk.rows && entry.firstId === chunk.firstId && entry.lastId === chunk.lastId;
19021
20031
  const alone = state.attempts.every((a) => a.attempt === chunk.attempt);
@@ -19027,7 +20037,9 @@ var RecordLogClient = class {
19027
20037
  /**
19028
20038
  * Apply a segment's corrections under the replacement `generation`: a row
19029
20039
  * replaces the record's, a `null` deletes it (one the chunks did not carry
19030
- * changes nothing).
20040
+ * changes nothing). A line of a model whose clear above `readAt` (the
20041
+ * segment's `C`) was applied already changes nothing
20042
+ * ({@link readBeforeClear}).
19031
20043
  */
19032
20044
  applySegmentCorrections(segment) {
19033
20045
  this.assertGeneration(segment.generation);
@@ -19036,6 +20048,7 @@ var RecordLogClient = class {
19036
20048
  const touched = [];
19037
20049
  for (const { model, id, row } of segment.lines) {
19038
20050
  const key = { model, id };
20051
+ if (this.readBeforeClear(model, segment.readAt)) continue;
19039
20052
  if (row === null) {
19040
20053
  if (!confirmed.row(key)) continue;
19041
20054
  confirmed.delete(key);
@@ -19106,6 +20119,8 @@ var MemoryRecordLogTables = class {
19106
20119
  writers = /* @__PURE__ */ new Map();
19107
20120
  counts = /* @__PURE__ */ new Map();
19108
20121
  headValue = null;
20122
+ clearedValue = 0;
20123
+ clearedModels = /* @__PURE__ */ new Map();
19109
20124
  /**
19110
20125
  * @param init - The rows, cursor and epochs to start from.
19111
20126
  */
@@ -19204,6 +20219,23 @@ var MemoryRecordLogTables = class {
19204
20219
  if (!named) this.loadKeys.set(attempt, named = /* @__PURE__ */ new Set());
19205
20220
  for (const key of keys) named.add(keyText(key));
19206
20221
  }
20222
+ clearModel(model) {
20223
+ for (const text of [...this.rows.rows.keys()]) {
20224
+ const at = text.indexOf("\0");
20225
+ if (text.slice(0, at) === model) this.rows.delete({ model, id: text.slice(at + 1) });
20226
+ }
20227
+ return [];
20228
+ }
20229
+ clearedThrough() {
20230
+ return this.clearedValue;
20231
+ }
20232
+ clearedAt(model) {
20233
+ return this.clearedModels.get(model) ?? 0;
20234
+ }
20235
+ setClearedThrough(l, model) {
20236
+ this.clearedValue = Math.max(this.clearedValue, l);
20237
+ this.clearedModels.set(model, Math.max(this.clearedModels.get(model) ?? 0, l));
20238
+ }
19207
20239
  removeUnnamed(attempt, models) {
19208
20240
  const named = this.loadKeys.get(attempt) ?? /* @__PURE__ */ new Set();
19209
20241
  const covered = new Set(models);
@@ -19446,7 +20478,9 @@ function recordLogClientDDL() {
19446
20478
  local_only INTEGER NOT NULL DEFAULT 0,
19447
20479
  local_indexes TEXT,
19448
20480
  known_head INTEGER,
19449
- known_head_at INTEGER
20481
+ known_head_at INTEGER,
20482
+ cleared_lsn INTEGER,
20483
+ cleared_models TEXT
19450
20484
  )`,
19451
20485
  `CREATE TABLE IF NOT EXISTS record_log_writers (
19452
20486
  doc_id TEXT NOT NULL,
@@ -19544,6 +20578,10 @@ var RECORD_LOG_KNOWN_HEAD_COLUMNS = Object.freeze([
19544
20578
  var RECORD_LOG_VECTOR_INDEX_COLUMNS = Object.freeze([
19545
20579
  { table: "record_log_indexes", column: "vector", add: `ALTER TABLE record_log_indexes ADD COLUMN vector TEXT` }
19546
20580
  ]);
20581
+ var RECORD_LOG_CLEAR_MARK_COLUMNS = Object.freeze([
20582
+ { table: "record_log_state", column: "cleared_lsn", add: `ALTER TABLE record_log_state ADD COLUMN cleared_lsn INTEGER` },
20583
+ { table: "record_log_state", column: "cleared_models", add: `ALTER TABLE record_log_state ADD COLUMN cleared_models TEXT` }
20584
+ ]);
19547
20585
  var RECORD_LOG_CLIENT_ADDED_COLUMNS = Object.freeze([
19548
20586
  { table: "record_log_state", column: "receipt", add: `ALTER TABLE record_log_state ADD COLUMN receipt TEXT` },
19549
20587
  { table: "record_log_state", column: "segment", add: `ALTER TABLE record_log_state ADD COLUMN segment TEXT` },
@@ -19553,7 +20591,8 @@ var RECORD_LOG_CLIENT_ADDED_COLUMNS = Object.freeze([
19553
20591
  ...RECORD_LOG_LOCAL_ONLY_COLUMNS,
19554
20592
  ...RECORD_LOG_MEMBER_INDEX_COLUMNS,
19555
20593
  ...RECORD_LOG_KNOWN_HEAD_COLUMNS,
19556
- ...RECORD_LOG_VECTOR_INDEX_COLUMNS
20594
+ ...RECORD_LOG_VECTOR_INDEX_COLUMNS,
20595
+ ...RECORD_LOG_CLEAR_MARK_COLUMNS
19557
20596
  ]);
19558
20597
  function recordLogFieldIndexName(kind, model, name, table = "view") {
19559
20598
  const tag = kind === "field" ? "f" : "u";
@@ -19602,7 +20641,7 @@ function purgeDocumentQueryRows(sql, docId) {
19602
20641
  sql.exec(`DELETE FROM ${quote2(parent)} WHERE "_meta_doc_id" = ?`, docId);
19603
20642
  }
19604
20643
  }
19605
- var RECORD_LOG_STORAGE_VERSION = 11;
20644
+ var RECORD_LOG_STORAGE_VERSION = 12;
19606
20645
  var DATA_TABLES = ["record_log_rows", "record_log_view", "record_log_staged_base"];
19607
20646
  function migrateRecordLogStore(sql, options) {
19608
20647
  let current = 1;
@@ -19718,6 +20757,7 @@ function convertToOneCopy(sql) {
19718
20757
  }
19719
20758
  function addIndexSkips(sql) {
19720
20759
  if (storedDocuments(sql).length > 0) sql.exec(RECORD_LOG_INDEX_SKIPS_DDL);
20760
+ addMissingColumns(sql, RECORD_LOG_CLEAR_MARK_COLUMNS);
19721
20761
  writeStorageVersion(sql, RECORD_LOG_STORAGE_VERSION);
19722
20762
  }
19723
20763
  function regroupLoadKeys(sql) {
@@ -19926,8 +20966,8 @@ function storedData(row) {
19926
20966
  function storedRow(id, data) {
19927
20967
  return rowWithId(String(id), JSON.parse(String(data)));
19928
20968
  }
19929
- function rowsOf3(sql, query, ...bindings) {
19930
- return Array.from(sql.exec(query, ...bindings));
20969
+ function rowsOf3(sql, query, ...bindings2) {
20970
+ return Array.from(sql.exec(query, ...bindings2));
19931
20971
  }
19932
20972
  var BOUND_IDS = 400;
19933
20973
  function idLists(ids) {
@@ -20040,21 +21080,24 @@ var SqlRecordLogTables = class {
20040
21080
  typeState() {
20041
21081
  const state = this.state();
20042
21082
  const typed = state?.typed === "yes" ? "yes" : state?.typed === "no" ? "no" : "unknown";
20043
- const none = { declarations: null, vectors: null, vectorsKnown: true, enums: null, enumsKnown: true };
21083
+ const none = { declarations: null, vectors: null, vectorsKnown: true, enums: null, enumsKnown: true, cleared: null, clearedKnown: true };
20044
21084
  if (typed !== "yes" || !state?.db3_type) return { typed, db3Type: null, ...none };
20045
21085
  try {
20046
- const held = JSON.parse(String(state.db3_type));
20047
- const declarations = held.models ?? null;
21086
+ const held2 = JSON.parse(String(state.db3_type));
21087
+ const declarations = held2.models ?? null;
20048
21088
  return {
20049
21089
  typed,
20050
- db3Type: { name: held.name, hash: held.hash ?? null },
21090
+ db3Type: { name: held2.name, hash: held2.hash ?? null },
20051
21091
  declarations,
20052
- vectors: held.vectors ?? null,
21092
+ vectors: held2.vectors ?? null,
20053
21093
  // An entry with declarations and no `vectors` key was written before vector fields (#5225).
20054
- vectorsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held, "vectors"),
20055
- enums: held.enums ?? null,
21094
+ vectorsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held2, "vectors"),
21095
+ enums: held2.enums ?? null,
20056
21096
  // An entry with declarations and no `enums` key was written before enforced enums (#5897).
20057
- enumsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held, "enums")
21097
+ enumsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held2, "enums"),
21098
+ cleared: held2.cleared ?? null,
21099
+ // An entry with declarations and no `cleared` key was written before cleared fields (#6021).
21100
+ clearedKnown: declarations === null || Object.prototype.hasOwnProperty.call(held2, "cleared")
20058
21101
  };
20059
21102
  } catch {
20060
21103
  return { typed, db3Type: null, ...none };
@@ -20066,16 +21109,18 @@ var SqlRecordLogTables = class {
20066
21109
  */
20067
21110
  setType(update) {
20068
21111
  this.ensureState();
21112
+ forgetHeldCleared(this.sql, this.docId);
20069
21113
  if (update.typed === "no") {
20070
21114
  this.sql.exec(`UPDATE record_log_state SET typed = 'no', db3_type = NULL WHERE doc_id = ?`, this.docId);
20071
21115
  return;
20072
21116
  }
20073
- const held = this.typeState();
21117
+ const held2 = this.typeState();
20074
21118
  const { name, hash, models } = update.db3Type;
20075
- const keepsHeld = models === void 0 && hash !== null && held.db3Type?.hash === hash;
20076
- const kept = models ?? (keepsHeld ? held.declarations : null);
20077
- const vectors = models !== void 0 ? update.db3Type.vectors ?? null : keepsHeld && held.vectorsKnown ? held.vectors : void 0;
20078
- const enums = models !== void 0 ? update.db3Type.enums ?? null : keepsHeld && held.enumsKnown ? held.enums : void 0;
21119
+ const keepsHeld = models === void 0 && hash !== null && held2.db3Type?.hash === hash;
21120
+ const kept = models ?? (keepsHeld ? held2.declarations : null);
21121
+ const vectors = models !== void 0 ? update.db3Type.vectors ?? null : keepsHeld && held2.vectorsKnown ? held2.vectors : void 0;
21122
+ const enums = models !== void 0 ? update.db3Type.enums ?? null : keepsHeld && held2.enumsKnown ? held2.enums : void 0;
21123
+ const cleared = models !== void 0 ? update.db3Type.cleared ?? null : keepsHeld && held2.clearedKnown ? held2.cleared : void 0;
20079
21124
  this.sql.exec(
20080
21125
  `UPDATE record_log_state SET typed = 'yes', db3_type = ? WHERE doc_id = ?`,
20081
21126
  JSON.stringify({
@@ -20083,7 +21128,8 @@ var SqlRecordLogTables = class {
20083
21128
  hash: kept ? hash : null,
20084
21129
  models: kept,
20085
21130
  ...kept && vectors !== void 0 ? { vectors } : {},
20086
- ...kept && enums !== void 0 ? { enums } : {}
21131
+ ...kept && enums !== void 0 ? { enums } : {},
21132
+ ...kept && cleared !== void 0 ? { cleared } : {}
20087
21133
  }),
20088
21134
  this.docId
20089
21135
  );
@@ -20187,7 +21233,9 @@ var SqlRecordLogTables = class {
20187
21233
  }
20188
21234
  /** Records whose view row a confirmed write changed since the last call, each with the row it showed before. */
20189
21235
  takeViewChanged() {
20190
- const out = [...this.viewChanged.values()];
21236
+ const out = [...this.viewChanged.values()].map(
21237
+ (change) => change.before ? { ...change, before: withoutHeldCleared(this.sql, this.docId, change.key.model, change.before) } : change
21238
+ );
20191
21239
  this.viewChanged.clear();
20192
21240
  return out;
20193
21241
  }
@@ -20216,18 +21264,18 @@ var SqlRecordLogTables = class {
20216
21264
  if (state?.replacing === null || state?.replacing === void 0) return false;
20217
21265
  const completed = Number(state.rows_gen ?? 0);
20218
21266
  const within = `doc_id = ? AND _type = ? AND _id >= ? AND _id <= ? AND _gen = ?`;
20219
- const bindings = [this.docId, range.model, range.firstId, range.lastId, completed];
21267
+ const bindings2 = [this.docId, range.model, range.firstId, range.lastId, completed];
20220
21268
  const shown = `${within} AND NOT EXISTS (${OVERLAY_ROW_OF("record_log_view")})`;
20221
- const held = `${within} AND _data IS NOT NULL`;
21269
+ const held2 = `${within} AND _data IS NOT NULL`;
20222
21270
  const [count] = rowsOf3(
20223
21271
  this.sql,
20224
- `SELECT (SELECT COUNT(*) FROM record_log_view WHERE ${shown}) + (SELECT COUNT(*) FROM record_log_rows WHERE ${held}) AS n`,
20225
- ...bindings,
20226
- ...bindings
21272
+ `SELECT (SELECT COUNT(*) FROM record_log_view WHERE ${shown}) + (SELECT COUNT(*) FROM record_log_rows WHERE ${held2}) AS n`,
21273
+ ...bindings2,
21274
+ ...bindings2
20227
21275
  );
20228
21276
  if (Number(count?.n ?? 0) !== range.rows) return false;
20229
- this.sql.exec(`UPDATE record_log_view SET _gen = ? WHERE ${shown}`, Number(state.replacing), ...bindings);
20230
- this.sql.exec(`UPDATE record_log_rows SET _gen = ? WHERE ${held}`, Number(state.replacing), ...bindings);
21277
+ this.sql.exec(`UPDATE record_log_view SET _gen = ? WHERE ${shown}`, Number(state.replacing), ...bindings2);
21278
+ this.sql.exec(`UPDATE record_log_rows SET _gen = ? WHERE ${held2}`, Number(state.replacing), ...bindings2);
20231
21279
  return true;
20232
21280
  }
20233
21281
  noteLoadKeys(attempt, keys) {
@@ -20257,6 +21305,80 @@ var SqlRecordLogTables = class {
20257
21305
  }
20258
21306
  }
20259
21307
  }
21308
+ clearModel(model) {
21309
+ const ctx = this.writeContext();
21310
+ if (ctx.staged) return this.clearStaged(model, ctx);
21311
+ const plain = `record_log_view.doc_id = ? AND record_log_view._type = ?
21312
+ AND NOT EXISTS (${OVERLAY_ROW_OF("record_log_view")}) AND NOT EXISTS (${PENDING_KEY_OF("record_log_view")})`;
21313
+ this.sql.exec(`DELETE FROM record_log_view WHERE ${plain}`, this.docId, model);
21314
+ const guessed = rowsOf3(
21315
+ this.sql,
21316
+ `SELECT _id FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _data IS NOT NULL
21317
+ UNION ALL
21318
+ SELECT _id FROM record_log_view WHERE doc_id = ? AND _type = ? AND NOT EXISTS (${OVERLAY_ROW_OF("record_log_view")})`,
21319
+ this.docId,
21320
+ model,
21321
+ this.docId,
21322
+ model
21323
+ ).map((row) => ({ model, id: String(row._id) }));
21324
+ for (const key of guessed) this.putConfirmed(key, null, ctx);
21325
+ return guessed;
21326
+ }
21327
+ /**
21328
+ * {@link clearModel} under a staged replacement: the view still shows the
21329
+ * completed generation, guessed over the staged base. Each record of the
21330
+ * model, in the view, the overlay or the base, has its confirmed row put
21331
+ * as none under the replacement and its base kept as none, so the view
21332
+ * shows no row of it now and the replacement's completion keeps none.
21333
+ */
21334
+ clearStaged(model, ctx) {
21335
+ const keys = rowsOf3(
21336
+ this.sql,
21337
+ `SELECT _id FROM record_log_view WHERE doc_id = ? AND _type = ?
21338
+ UNION SELECT _id FROM record_log_rows WHERE doc_id = ? AND _type = ?
21339
+ UNION SELECT _id FROM record_log_staged_base WHERE doc_id = ? AND _type = ?`,
21340
+ this.docId,
21341
+ model,
21342
+ this.docId,
21343
+ model,
21344
+ this.docId,
21345
+ model
21346
+ ).map((row) => ({ model, id: String(row._id) }));
21347
+ this.stageBase(keys);
21348
+ this.sql.exec(`UPDATE record_log_staged_base SET _data = NULL WHERE doc_id = ? AND _type = ?`, this.docId, model);
21349
+ for (const key of keys) this.putConfirmed(key, null, ctx);
21350
+ return keys;
21351
+ }
21352
+ clearedThrough() {
21353
+ return Number(this.state()?.cleared_lsn ?? 0);
21354
+ }
21355
+ clearedAt(model) {
21356
+ return this.clearedModels().get(model) ?? 0;
21357
+ }
21358
+ setClearedThrough(l, model) {
21359
+ this.ensureState();
21360
+ const models = this.clearedModels();
21361
+ models.set(model, Math.max(models.get(model) ?? 0, l));
21362
+ this.sql.exec(
21363
+ `UPDATE record_log_state SET cleared_lsn = ?, cleared_models = ? WHERE doc_id = ?`,
21364
+ Math.max(this.clearedThrough(), l),
21365
+ JSON.stringify([...models]),
21366
+ this.docId
21367
+ );
21368
+ }
21369
+ /** Each cleared model's highest clear applied: a JSON list of `[model, l]`, so any model name reads back as it is. */
21370
+ clearedModels() {
21371
+ const text = this.state()?.cleared_models;
21372
+ const out = /* @__PURE__ */ new Map();
21373
+ if (typeof text !== "string") return out;
21374
+ try {
21375
+ for (const pair of JSON.parse(text)) {
21376
+ if (Array.isArray(pair) && typeof pair[0] === "string" && typeof pair[1] === "number") out.set(pair[0], pair[1]);
21377
+ }
21378
+ } catch {
21379
+ }
21380
+ return out;
21381
+ }
20260
21382
  removeUnnamed(attempt, models) {
20261
21383
  const removed = [];
20262
21384
  const ctx = this.writeContext();
@@ -20355,16 +21477,16 @@ var SqlRecordLogTables = class {
20355
21477
  continue;
20356
21478
  }
20357
21479
  const guessed = /* @__PURE__ */ new Set();
20358
- for (const { list, bindings } of idLists(ids)) {
21480
+ for (const { list, bindings: bindings2 } of idLists(ids)) {
20359
21481
  for (const row of this.sql.exec(
20360
21482
  `SELECT _id FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id IN ${list}
20361
21483
  UNION SELECT _id FROM record_log_pending_keys WHERE doc_id = ? AND _type = ? AND _id IN ${list}`,
20362
21484
  this.docId,
20363
21485
  model,
20364
- ...bindings,
21486
+ ...bindings2,
20365
21487
  this.docId,
20366
21488
  model,
20367
- ...bindings
21489
+ ...bindings2
20368
21490
  )) {
20369
21491
  guessed.add(String(row._id));
20370
21492
  }
@@ -20389,8 +21511,8 @@ var SqlRecordLogTables = class {
20389
21511
  /** Confirmed rows of `model` no guess covers, written into the view at once: `removed` first, then `puts`. */
20390
21512
  viewBatch(model, removed, puts, ctx) {
20391
21513
  const deleted = ctx.replacing ? [...removed, ...puts.map(([id]) => id)] : removed;
20392
- for (const { list, bindings } of idLists(deleted)) {
20393
- this.sql.exec(`DELETE FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id IN ${list}`, this.docId, model, ...bindings);
21514
+ for (const { list, bindings: bindings2 } of idLists(deleted)) {
21515
+ this.sql.exec(`DELETE FROM record_log_view WHERE doc_id = ? AND _type = ? AND _id IN ${list}`, this.docId, model, ...bindings2);
20394
21516
  }
20395
21517
  if (!puts.length) return;
20396
21518
  const [next] = rowsOf3(this.sql, `SELECT ${NEXT_VIEW_ROWID} AS rowid`);
@@ -20425,16 +21547,16 @@ var SqlRecordLogTables = class {
20425
21547
  }
20426
21548
  this.defer(key);
20427
21549
  }
20428
- for (const { list, bindings } of idLists(written.map(({ key }) => key.id))) {
20429
- this.sql.exec(`DELETE FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id IN ${list}`, this.docId, model, ...bindings);
21550
+ for (const { list, bindings: bindings2 } of idLists(written.map(({ key }) => key.id))) {
21551
+ this.sql.exec(`DELETE FROM record_log_rows WHERE doc_id = ? AND _type = ? AND _id IN ${list}`, this.docId, model, ...bindings2);
20430
21552
  }
20431
- for (const { list, bindings } of idLists(gone)) {
21553
+ for (const { list, bindings: bindings2 } of idLists(gone)) {
20432
21554
  this.sql.exec(
20433
21555
  `INSERT INTO record_log_rows (doc_id, _type, _id, _data, _gen) SELECT ?, ?, value, NULL, ? FROM ${list}`,
20434
21556
  this.docId,
20435
21557
  model,
20436
21558
  generation,
20437
- ...bindings
21559
+ ...bindings2
20438
21560
  );
20439
21561
  }
20440
21562
  if (puts.size) {
@@ -21015,7 +22137,7 @@ function findHolder(sql, table, docId, model, fields, values, excluding) {
21015
22137
  function findConfirmedHolder(sql, docId, model, fields, values, excluding) {
21016
22138
  if (fields.length === 0 || values.some((v) => v === null || v === void 0)) return null;
21017
22139
  const lookup = fieldLookupPredicates(model, fields);
21018
- const bindings = fieldLookupBindings(lookup, model, fields, values.map(lookupBinding));
22140
+ const bindings2 = fieldLookupBindings(lookup, model, fields, values.map(lookupBinding));
21019
22141
  const skip = new Set(excluding);
21020
22142
  for (const row of sql.exec(
21021
22143
  `SELECT _id FROM (
@@ -21024,9 +22146,9 @@ function findConfirmedHolder(sql, docId, model, fields, values, excluding) {
21024
22146
  SELECT _id FROM record_log_rows WHERE doc_id = ? AND ${lookup.where} AND _data IS NOT NULL)
21025
22147
  ORDER BY _id LIMIT ?`,
21026
22148
  docId,
21027
- ...bindings,
22149
+ ...bindings2,
21028
22150
  docId,
21029
- ...bindings,
22151
+ ...bindings2,
21030
22152
  skip.size + 1
21031
22153
  )) {
21032
22154
  const id = String(row._id);
@@ -21262,7 +22384,7 @@ var RecordLogStore = class {
21262
22384
  if (!command.force && live.length > 0) {
21263
22385
  return { purged: false, reason: "pending", pendingOps: live.length, handedBack: [] };
21264
22386
  }
21265
- const [held] = rowsOf3(this.sql, `SELECT COUNT(*) AS n FROM record_log_state WHERE doc_id = ?`, this.docId);
22387
+ const [held2] = rowsOf3(this.sql, `SELECT COUNT(*) AS n FROM record_log_state WHERE doc_id = ?`, this.docId);
21266
22388
  const present = new Set(
21267
22389
  rowsOf3(this.sql, `SELECT name FROM sqlite_master WHERE type = 'table'`).map((row) => String(row.name))
21268
22390
  );
@@ -21275,7 +22397,7 @@ var RecordLogStore = class {
21275
22397
  }
21276
22398
  return {
21277
22399
  purged: true,
21278
- ...Number(held?.n ?? 0) === 0 && live.length === 0 ? { nothingStored: true } : {},
22400
+ ...Number(held2?.n ?? 0) === 0 && live.length === 0 ? { nothingStored: true } : {},
21279
22401
  pendingOps: live.length,
21280
22402
  handedBack: live
21281
22403
  };
@@ -21332,9 +22454,9 @@ var RecordLogStore = class {
21332
22454
  SELECT MIN(_type) FROM ${table} WHERE doc_id = ?
21333
22455
  UNION ALL SELECT (SELECT MIN(_type) FROM ${table} WHERE doc_id = ? AND _type > t.m) FROM t WHERE t.m IS NOT NULL)
21334
22456
  SELECT m AS _type FROM t WHERE m IS NOT NULL`;
21335
- const held = /* @__PURE__ */ new Set();
22457
+ const held2 = /* @__PURE__ */ new Set();
21336
22458
  for (const table of ["record_log_view", "record_log_rows"]) {
21337
- for (const row of rowsOf3(this.sql, skipScan(table), docId, docId)) held.add(String(row._type));
22459
+ for (const row of rowsOf3(this.sql, skipScan(table), docId, docId)) held2.add(String(row._type));
21338
22460
  }
21339
22461
  for (const row of rowsOf3(
21340
22462
  this.sql,
@@ -21343,9 +22465,9 @@ var RecordLogStore = class {
21343
22465
  WHERE p.doc_id = ? AND p.void = 0 AND p.acked IS NULL`,
21344
22466
  docId
21345
22467
  )) {
21346
- held.add(String(row._type));
22468
+ held2.add(String(row._type));
21347
22469
  }
21348
- return [...held].sort();
22470
+ return [...held2].sort();
21349
22471
  }
21350
22472
  /** A writer's unacknowledged, unwithdrawn entries and the records each touches. */
21351
22473
  unackedOf(writer) {
@@ -21380,7 +22502,7 @@ var RecordLogStore = class {
21380
22502
  model,
21381
22503
  id
21382
22504
  );
21383
- return row ? storedRow(id, row._data) : null;
22505
+ return row ? withoutHeldCleared(this.sql, this.docId, model, storedRow(id, row._data)) : null;
21384
22506
  }
21385
22507
  /** Several records' view rows, in the order asked for; a missing one is `null`. */
21386
22508
  readMany(model, ids) {
@@ -21395,7 +22517,7 @@ var RecordLogStore = class {
21395
22517
  model,
21396
22518
  ...slice
21397
22519
  )) {
21398
- found.set(String(row._id), storedRow(row._id, row._data));
22520
+ found.set(String(row._id), withoutHeldCleared(this.sql, this.docId, model, storedRow(row._id, row._data)));
21399
22521
  }
21400
22522
  }
21401
22523
  return ids.map((id) => found.get(id) ?? null);
@@ -21406,7 +22528,7 @@ var RecordLogStore = class {
21406
22528
  this.sql,
21407
22529
  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 ?`,
21408
22530
  ...after === null ? [this.docId, model, limit] : [this.docId, model, after, limit]
21409
- ).map((row) => storedRow(row._id, row._data));
22531
+ ).map((row) => withoutHeldCleared(this.sql, this.docId, model, storedRow(row._id, row._data)));
21410
22532
  }
21411
22533
  /** One page of a model's record ids in id order, after `after`. */
21412
22534
  recordIdsAfter(model, after, limit) {
@@ -21789,9 +22911,9 @@ var RecordLogStore = class {
21789
22911
  if (!row) continue;
21790
22912
  const key = parseKey(text);
21791
22913
  if (key.model !== model || excluding.includes(key.id)) continue;
21792
- const held = fields.map((f) => row[f]);
21793
- if (held.some((v) => v === void 0 || v === null)) continue;
21794
- if (JSON.stringify(held) === wanted2) found.push(text);
22914
+ const held2 = fields.map((f) => row[f]);
22915
+ if (held2.some((v) => v === void 0 || v === null)) continue;
22916
+ if (JSON.stringify(held2) === wanted2) found.push(text);
21795
22917
  }
21796
22918
  const skip = [...excluding, ...[...working.keys()].map(parseKey).filter((k) => k.model === model).map((k) => k.id)];
21797
22919
  for (const id of findHolders(this.sql, "record_log_view", docId, model, fields, values, skip)) {
@@ -21851,9 +22973,9 @@ var RecordLogStore = class {
21851
22973
  const before = view ? storedRow(key.id, view.data) : null;
21852
22974
  const confirmed = overlay ? overlay.data === null ? null : storedRow(key.id, overlay.data) : before;
21853
22975
  const shows = JSON.stringify(row);
21854
- const held = ctx.staged && overlay !== null && overlay.gen === ctx.replacement;
21855
- const settles = !held && JSON.stringify(confirmed) === shows;
21856
- if (!held && !settles && overlay === null) {
22976
+ const held2 = ctx.staged && overlay !== null && overlay.gen === ctx.replacement;
22977
+ const settles = !held2 && JSON.stringify(confirmed) === shows;
22978
+ if (!held2 && !settles && overlay === null) {
21857
22979
  if (view) {
21858
22980
  this.sql.exec(
21859
22981
  `INSERT INTO record_log_rows (doc_id, _type, _id, _data, _gen, _ord)
@@ -22140,10 +23262,12 @@ var RecordLogStore = class {
22140
23262
  const acknowledged = [];
22141
23263
  const settled = [];
22142
23264
  const settlements = [];
23265
+ const cleared = /* @__PURE__ */ new Set();
22143
23266
  let underivable;
22144
23267
  for (const item of command.items) {
22145
23268
  const out = client.receive(item);
22146
23269
  touched.push(...out.touched);
23270
+ for (const model of out.cleared ?? []) cleared.add(model);
22147
23271
  acknowledged.push(...out.acknowledged);
22148
23272
  settled.push(...out.settled);
22149
23273
  settlements.push(...out.settlements ?? []);
@@ -22156,11 +23280,31 @@ var RecordLogStore = class {
22156
23280
  settled,
22157
23281
  ...settlements.length ? { settlements } : {},
22158
23282
  changed,
23283
+ ...cleared.size ? { models: [...cleared] } : {},
22159
23284
  cursor: this.tables.cursor(),
22160
23285
  ...underivable ? { underivable } : {}
22161
23286
  };
22162
23287
  });
22163
23288
  }
23289
+ /**
23290
+ * Apply the model clears a catch-up carries, in one transaction, before
23291
+ * the rows, chunks or page they ride with: every confirmed row of each
23292
+ * model goes, its member, text and vector index entries with it, a record
23293
+ * an unjudged entry touches is guessed again, and the highest clear
23294
+ * applied is recorded with the removal. The cursor does not move. A clear
23295
+ * at or below the cursor or the mark changes nothing, so one sent again
23296
+ * (a resumed download) leaves the rows read since it alone. The reply
23297
+ * names the models emptied in `models`, and in `changed` only the records
23298
+ * an unjudged entry touches.
23299
+ */
23300
+ applyClears(command) {
23301
+ return this.sql.transaction(() => {
23302
+ this.beginWrites();
23303
+ const out = this.client(command.writer).applyClears(command.clears);
23304
+ const changed = this.settleView(out.touched);
23305
+ return { changed, ...out.cleared?.length ? { models: out.cleared } : {}, cursor: this.tables.cursor() };
23306
+ });
23307
+ }
22164
23308
  /** Act on a refusal: hand back what it reaches and answer the frames that move the room past it. */
22165
23309
  refused(command) {
22166
23310
  return this.sql.transaction(() => {
@@ -22237,7 +23381,9 @@ var RecordLogStore = class {
22237
23381
  rows: command.rows,
22238
23382
  gone: command.gone,
22239
23383
  ...command.generation !== void 0 ? { generation: command.generation } : {},
22240
- ...command.receipt !== void 0 ? { receipt: command.receipt } : {}
23384
+ ...command.receipt !== void 0 ? { receipt: command.receipt } : {},
23385
+ // Rows of a model another session's catch-up cleared past `lsn` stay gone (#5994).
23386
+ ...command.lsn !== void 0 ? { readAt: command.lsn } : {}
22241
23387
  });
22242
23388
  client.noteHead(command);
22243
23389
  if (staged) this.beginWrites();
@@ -22275,7 +23421,7 @@ var RecordLogStore = class {
22275
23421
  });
22276
23422
  this.tables.setLastCatchUpAt(command.at ?? Date.now());
22277
23423
  client.noteHead(command);
22278
- const settled = staged ? this.settleReplacement(out.touched, models) : { changed: this.settleView(out.touched), models: [] };
23424
+ const settled = staged ? this.settleReplacement(out.touched, [.../* @__PURE__ */ new Set([...models, ...out.cleared ?? []])]) : { changed: this.settleView(out.touched), models: out.cleared ?? [] };
22279
23425
  return {
22280
23426
  acknowledged: out.acknowledged,
22281
23427
  settled: out.settled,
@@ -22350,7 +23496,8 @@ var RecordLogStore = class {
22350
23496
  attempt: command.attempt,
22351
23497
  model: command.model,
22352
23498
  lines: command.lines,
22353
- ...command.mode !== void 0 ? { mode: command.mode } : {}
23499
+ ...command.mode !== void 0 ? { mode: command.mode } : {},
23500
+ ...command.readAt !== void 0 ? { readAt: command.readAt } : {}
22354
23501
  });
22355
23502
  const touched = new Set(out.touched.map(keyText2));
22356
23503
  const removed = command.lines.filter(
@@ -22412,7 +23559,8 @@ var RecordLogStore = class {
22412
23559
  const out = this.client(command.writer).applySegmentRows({
22413
23560
  generation: command.generation,
22414
23561
  rows: command.rows,
22415
- ...command.attempt !== void 0 ? { attempt: command.attempt } : {}
23562
+ ...command.attempt !== void 0 ? { attempt: command.attempt } : {},
23563
+ ...command.readAt !== void 0 ? { readAt: command.readAt } : {}
22416
23564
  });
22417
23565
  if (staged) {
22418
23566
  this.beginWrites();
@@ -22463,7 +23611,8 @@ var RecordLogStore = class {
22463
23611
  const out = this.client(command.writer).applySegmentCorrections({
22464
23612
  generation: command.generation,
22465
23613
  lines: command.lines,
22466
- ...command.attempt !== void 0 ? { attempt: command.attempt } : {}
23614
+ ...command.attempt !== void 0 ? { attempt: command.attempt } : {},
23615
+ ...command.readAt !== void 0 ? { readAt: command.readAt } : {}
22467
23616
  });
22468
23617
  const touched = new Set(out.touched.map(keyText2));
22469
23618
  const removed = command.lines.filter((l) => l.row === null && touched.has(keyText2(l))).length;
@@ -22488,12 +23637,12 @@ var RecordLogStore = class {
22488
23637
  this.tables.takeViewChanged();
22489
23638
  for (const [model, ids] of idsByModel(keys)) {
22490
23639
  const guessed = /* @__PURE__ */ new Set();
22491
- for (const { list, bindings } of idLists(ids)) {
23640
+ for (const { list, bindings: bindings2 } of idLists(ids)) {
22492
23641
  for (const row of this.sql.exec(
22493
23642
  `SELECT DISTINCT _id FROM record_log_pending_keys WHERE doc_id = ? AND _type = ? AND _id IN ${list}`,
22494
23643
  docId,
22495
23644
  model,
22496
- ...bindings
23645
+ ...bindings2
22497
23646
  )) {
22498
23647
  guessed.add(String(row._id));
22499
23648
  }
@@ -24503,8 +25652,8 @@ var OpfsEngine = class {
24503
25652
  const routing = this.docs.get(docId);
24504
25653
  if (routing && routing.entry === entry) routing.sessions++;
24505
25654
  else this.docs.set(docId, { entry, sessions: 1 });
24506
- const held = this.holdPresence(db3ClientLockName(namespace, docId, options.clientId));
24507
- if (held) this.presence.add(held);
25655
+ const held2 = this.holdPresence(db3ClientLockName(namespace, docId, options.clientId));
25656
+ if (held2) this.presence.add(held2);
24508
25657
  const engine = this;
24509
25658
  let closing = null;
24510
25659
  const closeOnce = async () => {
@@ -24513,7 +25662,7 @@ var OpfsEngine = class {
24513
25662
  entry.docIds.delete(docId);
24514
25663
  engine.docs.delete(docId);
24515
25664
  }
24516
- if (held && engine.presence.delete(held)) held();
25665
+ if (held2 && engine.presence.delete(held2)) held2();
24517
25666
  releaseDocument();
24518
25667
  await host.close();
24519
25668
  };
@@ -24729,10 +25878,10 @@ var OpfsEngine = class {
24729
25878
  report.skipped.push({ pool: directory, reason: "unreachable" });
24730
25879
  return;
24731
25880
  }
24732
- const keep = new Set(options.keep ?? []);
25881
+ const keep3 = new Set(options.keep ?? []);
24733
25882
  const wanted2 = [];
24734
25883
  for (const docId of stored) {
24735
- if (keep.has(docId)) report.skipped.push({ pool: docId, reason: "keep" });
25884
+ if (keep3.has(docId)) report.skipped.push({ pool: docId, reason: "keep" });
24736
25885
  else wanted2.push(docId);
24737
25886
  }
24738
25887
  await this.withExclusiveAll(
@@ -25244,9 +26393,9 @@ var OpfsEngine = class {
25244
26393
  `[format2] The worker serving '${docId}' is gone; its '${modelName}' rows cannot be read until the document is reconnected.`
25245
26394
  );
25246
26395
  }
25247
- const held = candidates.get(entry.engine) ?? [];
25248
- held.push(docId);
25249
- candidates.set(entry.engine, held);
26396
+ const held2 = candidates.get(entry.engine) ?? [];
26397
+ held2.push(docId);
26398
+ candidates.set(entry.engine, held2);
25250
26399
  }
25251
26400
  return routeQueryEngine({ mirror: this.mirror, candidates, ordinary, modelName });
25252
26401
  }
@@ -25828,8 +26977,8 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
25828
26977
  }
25829
26978
  this.mirror = { ...this.mirror, nextSeq, pending, lowestPending: lowest };
25830
26979
  if (confirmed) {
25831
- const own2 = this.mirror.writer;
25832
- this.acknowledged((reply.acknowledged ?? []).filter((a) => a.writer === own2).map((a) => a.seq));
26980
+ const own3 = this.mirror.writer;
26981
+ this.acknowledged((reply.acknowledged ?? []).filter((a) => a.writer === own3).map((a) => a.seq));
25833
26982
  this.noteSettled(reply);
25834
26983
  }
25835
26984
  if (committed.length) {
@@ -25934,10 +27083,10 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
25934
27083
  }
25935
27084
  /** This writer's entries a reply settled: what waits on them resolves with their rows. */
25936
27085
  noteSettled(reply) {
25937
- const own2 = this.mirror.writer;
25938
- const rowsOf4 = new Map((reply.settlements ?? []).filter((s) => s.writer === own2).map((s) => [s.seq, s.rows]));
27086
+ const own3 = this.mirror.writer;
27087
+ const rowsOf4 = new Map((reply.settlements ?? []).filter((s) => s.writer === own3).map((s) => [s.seq, s.rows]));
25939
27088
  for (const { writer, seq } of reply.settled ?? []) {
25940
- if (writer !== own2) continue;
27089
+ if (writer !== own3) continue;
25941
27090
  this.unsettled.delete(seq);
25942
27091
  const settlement = { rows: rowsOf4.get(seq) ?? [] };
25943
27092
  this.settlements.set(seq, settlement);
@@ -26360,7 +27509,8 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
26360
27509
  return this.run("receive", async () => {
26361
27510
  const cursor = this.mirror.cursor;
26362
27511
  const reply = await this.host.dispatch({ kind: "receive", writer, items, ...heard });
26363
- this.afterChange(reply, "remote");
27512
+ if (reply.models?.length) await this.afterBulk(reply, "remote");
27513
+ else this.afterChange(reply, "remote");
26364
27514
  this.noteSettled(reply);
26365
27515
  if (!reply.changed.length && (heard.head !== void 0 || reply.cursor !== cursor)) this.pendingChanged();
26366
27516
  return reply;
@@ -26418,6 +27568,20 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
26418
27568
  return reply;
26419
27569
  });
26420
27570
  }
27571
+ /**
27572
+ * Apply the model clears a catch-up carries, before its rows, chunks or
27573
+ * page (#5994), as one scheduled operation: each model's rows go at once,
27574
+ * and the listeners hear each model emptied once. One at or below the
27575
+ * store's cursor or its highest clear applied changes nothing.
27576
+ */
27577
+ applyClears(clears, writer = this.writer()) {
27578
+ return this.run("applyClears", async () => {
27579
+ const reply = await this.host.dispatch({ kind: "applyClears", writer, clears });
27580
+ if (reply.models?.length) await this.afterBulk(reply, "remote");
27581
+ else this.afterChange(reply, "remote");
27582
+ return reply;
27583
+ });
27584
+ }
26421
27585
  /**
26422
27586
  * Complete a catch-up at the room's log number; answered `stale` when the store is past it.
26423
27587
  * @param _project - Ignored: a db3's rows live only in the view.
@@ -26561,6 +27725,14 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
26561
27725
  declaredEnums() {
26562
27726
  return this.mirror.typed === "yes" ? this.mirror.enums ?? null : null;
26563
27727
  }
27728
+ /**
27729
+ * The cleared and tombstoned fields of the db3's type the room sent beside
27730
+ * its declarations, per model the sorted names; `null` while the db3 is not
27731
+ * known to be typed, its type clears none, or none were received yet.
27732
+ */
27733
+ declaredCleared() {
27734
+ return this.mirror.typed === "yes" ? this.mirror.cleared ?? null : null;
27735
+ }
26564
27736
  /**
26565
27737
  * Whether the local pre-check should hold a save to a unique constraint:
26566
27738
  * every constraint is checked unless the room has said it keeps it out of
@@ -27206,13 +28378,14 @@ var ACCESS_REFUSED_CODES = /* @__PURE__ */ new Set(["ACCESS_DENIED", "DOC_ACCESS
27206
28378
  function typeOfOpened(frame, docId) {
27207
28379
  if (!("db3Type" in frame) || frame.db3Type === void 0) return { type: { typed: "no" } };
27208
28380
  const type = frame.db3Type;
27209
- const isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
27210
- const models = isObject2(type) ? type.models : void 0;
27211
- const vectors = isObject2(type) ? type.vectors : void 0;
27212
- const enums = isObject2(type) ? type.enums : void 0;
28381
+ const isObject3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
28382
+ const models = isObject3(type) ? type.models : void 0;
28383
+ const vectors = isObject3(type) ? type.vectors : void 0;
28384
+ const enums = isObject3(type) ? type.enums : void 0;
28385
+ const cleared = isObject3(type) ? type.cleared : void 0;
27213
28386
  const isValues = (value) => Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string");
27214
- const isEncoding = (value) => isObject2(value) && typeof value.dims === "number" && Number.isInteger(value.dims) && value.dims >= 1 && isVectorElement(value.element);
27215
- const wellFormed = isObject2(type) && typeof type.name === "string" && type.name !== "" && typeof type.hash === "string" && type.hash !== "" && (models === void 0 || isObject2(models) && Object.values(models).every((fields) => isObject2(fields) && Object.values(fields).every((kind) => typeof kind === "string"))) && (vectors === void 0 || models !== void 0 && isObject2(vectors) && Object.values(vectors).every((fields) => isObject2(fields) && Object.values(fields).every(isEncoding))) && (enums === void 0 || models !== void 0 && isObject2(enums) && Object.values(enums).every((fields) => isObject2(fields) && Object.values(fields).every(isValues)));
28387
+ const isEncoding = (value) => isObject3(value) && typeof value.dims === "number" && Number.isInteger(value.dims) && value.dims >= 1 && isVectorElement(value.element);
28388
+ const wellFormed = isObject3(type) && typeof type.name === "string" && type.name !== "" && typeof type.hash === "string" && type.hash !== "" && (models === void 0 || isObject3(models) && Object.values(models).every((fields) => isObject3(fields) && Object.values(fields).every((kind) => typeof kind === "string"))) && (vectors === void 0 || models !== void 0 && isObject3(vectors) && Object.values(vectors).every((fields) => isObject3(fields) && Object.values(fields).every(isEncoding))) && (enums === void 0 || models !== void 0 && isObject3(enums) && Object.values(enums).every((fields) => isObject3(fields) && Object.values(fields).every(isValues))) && (cleared === void 0 || models !== void 0 && isObject3(cleared) && Object.values(cleared).every(isValues));
27216
28389
  if (!wellFormed) {
27217
28390
  Logger.warn(`[record-log] ${docId}: record.opened carried a db3Type this client cannot read; the type it holds is kept`);
27218
28391
  return {};
@@ -27225,7 +28398,8 @@ function typeOfOpened(frame, docId) {
27225
28398
  hash: type.hash,
27226
28399
  ...models !== void 0 ? { models } : {},
27227
28400
  ...vectors !== void 0 ? { vectors } : {},
27228
- ...enums !== void 0 ? { enums } : {}
28401
+ ...enums !== void 0 ? { enums } : {},
28402
+ ...cleared !== void 0 ? { cleared } : {}
27229
28403
  }
27230
28404
  }
27231
28405
  };
@@ -27277,6 +28451,12 @@ function isChunkIntegrityError(error) {
27277
28451
  return name === "IngestChunkError" || name === "SnapshotChunkIntegrityError";
27278
28452
  }
27279
28453
  var errorText = (error) => error instanceof Error ? error.message : String(error);
28454
+ function clearsOf(value) {
28455
+ if (!Array.isArray(value)) return [];
28456
+ return value.filter(
28457
+ (c) => typeof c === "object" && c !== null && typeof c.model === "string" && Number.isInteger(c.l) && Number.isInteger(c.e)
28458
+ ).map((c) => ({ model: c.model, l: c.l, e: c.e }));
28459
+ }
27280
28460
  function answeredSeqs(items, writer) {
27281
28461
  const seqs = [];
27282
28462
  for (const item of items) {
@@ -27568,10 +28748,10 @@ var RecordLogDocumentSession = class {
27568
28748
  this.store.resumeAcknowledgements?.();
27569
28749
  this.phase = "opening";
27570
28750
  const generation = this.generation;
27571
- const own2 = this.store.writer();
28751
+ const own3 = this.store.writer();
27572
28752
  const state = await this.store.storedState();
27573
28753
  if (generation !== this.generation) return;
27574
- this.orphans = state.writers.filter((w) => w.writer !== own2 && w.pending > 0).map((w) => ({ writer: w.writer, lowestPending: w.lowestPending }));
28754
+ this.orphans = state.writers.filter((w) => w.writer !== own3 && w.pending > 0).map((w) => ({ writer: w.writer, lowestPending: w.lowestPending }));
27575
28755
  if (this.orphans.length) {
27576
28756
  Logger.info(`[record-log] ${this.docId}: draining ${this.orphans.length} earlier session writer(s) before opening`);
27577
28757
  }
@@ -27631,9 +28811,10 @@ var RecordLogDocumentSession = class {
27631
28811
  ...unfinished ? { unfinished } : {},
27632
28812
  // The type revision whose declarations this device holds: the room
27633
28813
  // sends them again only for another one (#5020). Declarations held
27634
- // without their vector fields (written before #5225) or their enforced
27635
- // enums (before #5897) are asked for again.
27636
- ...typed === "yes" && marks.db3Type?.hash && marks.vectorsKnown !== false && marks.enumsKnown !== false ? { db3TypeHash: marks.db3Type.hash } : {}
28814
+ // without their vector fields (written before #5225), their enforced
28815
+ // enums (before #5897) or their cleared fields (before #6021) are asked
28816
+ // for again.
28817
+ ...typed === "yes" && marks.db3Type?.hash && marks.vectorsKnown !== false && marks.enumsKnown !== false && marks.clearedKnown !== false ? { db3TypeHash: marks.db3Type.hash } : {}
27637
28818
  });
27638
28819
  if (!sendAhead) return;
27639
28820
  const ahead = { declarations: null, refused: false, seqs: [] };
@@ -27659,9 +28840,9 @@ var RecordLogDocumentSession = class {
27659
28840
  * made since do not name its models). The models it names are this open's.
27660
28841
  */
27661
28842
  declarationsFor(pending) {
27662
- const held = new Set(this.store.marks().models ?? []);
27663
- for (const entry of pending) for (const model of modelsOf2(entry)) held.add(model);
27664
- const models = this.host.declarations(this.docId, [...held].sort());
28843
+ const held2 = new Set(this.store.marks().models ?? []);
28844
+ for (const entry of pending) for (const model of modelsOf2(entry)) held2.add(model);
28845
+ const models = this.host.declarations(this.docId, [...held2].sort());
27665
28846
  this.declaredThisOpen = new Set(Object.keys(models));
27666
28847
  return models;
27667
28848
  }
@@ -27954,6 +29135,11 @@ var RecordLogDocumentSession = class {
27954
29135
  const catchUp = frame.catchUp ?? { mode: "inline", rows: [], gone: [], lsn: frame.lsn };
27955
29136
  if (catchUp.mode === "building") return this.waitForSegment(catchUp);
27956
29137
  this.buildingSince = null;
29138
+ const clears = clearsOf(catchUp.clears);
29139
+ if (clears.length) {
29140
+ await this.store.applyClears(clears, this.current.writer);
29141
+ if (generation !== this.generation || !this.current) return;
29142
+ }
27957
29143
  this.phase = "catchingUp";
27958
29144
  if (catchUp.mode === "load") {
27959
29145
  return this.startLoadReceipt(catchUp.load, {
@@ -28152,6 +29338,11 @@ var RecordLogDocumentSession = class {
28152
29338
  const gone = frame.gone ?? [];
28153
29339
  const mine = receipt?.attempt !== void 0 ? { receipt: receipt.attempt } : {};
28154
29340
  const heard = heardOf(frame, receivedAt);
29341
+ const clears = clearsOf(frame.clears);
29342
+ if (clears.length) {
29343
+ await this.store.applyClears(clears, this.current.writer);
29344
+ if (generation !== this.generation || !this.paging || !this.current) return;
29345
+ }
28155
29346
  const page = await this.store.applyCatchUpPage({ rows, gone, lsn, ...fence, ...mine, ...heard }, [], this.current.writer);
28156
29347
  if (generation !== this.generation || !this.paging || !this.current) return;
28157
29348
  if (page.stale) {
@@ -28325,6 +29516,9 @@ var RecordLogDocumentSession = class {
28325
29516
  attempt,
28326
29517
  model: chunk.model,
28327
29518
  mode: pointer.mode,
29519
+ // The rows are the load's as of its last number: a model
29520
+ // another session cleared past it keeps none of them (#5994).
29521
+ readAt: pointer.lastLsn ?? void 0,
28328
29522
  bytes,
28329
29523
  descriptor: {
28330
29524
  model: chunk.model,
@@ -28410,12 +29604,12 @@ var RecordLogDocumentSession = class {
28410
29604
  );
28411
29605
  const { attempt } = start;
28412
29606
  receipt.attempt = attempt;
28413
- const { generation, held } = start.generation !== void 0 ? { generation: start.generation, held: start.held ?? null } : await this.store.beginSegmentReplacement(attempt, receipt.writer);
29607
+ const { generation, held: held2 } = start.generation !== void 0 ? { generation: start.generation, held: start.held ?? null } : await this.store.beginSegmentReplacement(attempt, receipt.writer);
28414
29608
  if (generation === null) throw new ReceiptFailure("the store handed out no replacement generation");
28415
29609
  const overtaken = () => this.serially(
28416
29610
  () => this.receiptStale(receipt, () => this.abandonReceipt(receipt, "another client of the store began replacing it", generation), generation)
28417
29611
  );
28418
- const holds = new Map((held?.chunks ?? []).map((c) => [c.object, c]));
29612
+ const holds = new Map((held2?.chunks ?? []).map((c) => [c.object, c]));
28419
29613
  receipt.kept = 0;
28420
29614
  receipt.fetched = 0;
28421
29615
  this.resuming(receipt, start, segment.chunks.length);
@@ -28440,7 +29634,7 @@ var RecordLogDocumentSession = class {
28440
29634
  const { index: _index, ...range } = mine;
28441
29635
  void _index;
28442
29636
  const kept = await this.store.keepSegmentChunk(
28443
- { generation, attempt, segmentId: segment.segmentId, ...range },
29637
+ { generation, attempt, segmentId: segment.segmentId, ...range, readAt: segment.completedLsn },
28444
29638
  receipt.writer
28445
29639
  );
28446
29640
  if (!this.receiving(receipt)) return;
@@ -28458,7 +29652,7 @@ var RecordLogDocumentSession = class {
28458
29652
  receipt,
28459
29653
  `${base}/${chunk.path}`,
28460
29654
  (bytes) => this.store.applySegmentChunk(
28461
- { generation, attempt, segmentId: segment.segmentId, bytes, descriptor: chunk },
29655
+ { generation, attempt, segmentId: segment.segmentId, readAt: segment.completedLsn, bytes, descriptor: chunk },
28462
29656
  [],
28463
29657
  receipt.writer
28464
29658
  )
@@ -28474,7 +29668,11 @@ var RecordLogDocumentSession = class {
28474
29668
  const corrections = await this.applyChunk(
28475
29669
  receipt,
28476
29670
  `${base}/${segment.corrections.path}`,
28477
- (bytes) => this.store.applySegmentCorrections({ generation, attempt, bytes, descriptor: segment.corrections }, [], receipt.writer)
29671
+ (bytes) => this.store.applySegmentCorrections(
29672
+ { generation, attempt, readAt: segment.completedLsn, bytes, descriptor: segment.corrections },
29673
+ [],
29674
+ receipt.writer
29675
+ )
28478
29676
  );
28479
29677
  if (!corrections || !this.receiving(receipt)) return;
28480
29678
  if (corrections.stale) return overtaken();
@@ -28702,10 +29900,10 @@ var RecordLogDocumentSession = class {
28702
29900
  this.catchUpRetryMs = CATCH_UP_RETRY_MS;
28703
29901
  this.clearGap();
28704
29902
  this.settleAcknowledged(acknowledged);
28705
- const held = this.held;
29903
+ const held2 = this.held;
28706
29904
  this.held = [];
28707
29905
  this.phase = current.orphan ? "draining" : "open";
28708
- for (const answer of held) {
29906
+ for (const answer of held2) {
28709
29907
  if (answer.kind === "results") underivable = await this.applyResults(answer.items, answer.heard) ?? underivable;
28710
29908
  else await this.applyRefusal(answer.refusal);
28711
29909
  }
@@ -28862,8 +30060,8 @@ var RecordLogDocumentSession = class {
28862
30060
  }
28863
30061
  /** This client's writer's entries the room acknowledged: confirmed, and their waiters resolve. */
28864
30062
  settleAcknowledged(acknowledged) {
28865
- const own2 = this.store.writer();
28866
- const seqs = acknowledged.filter((a) => a.writer === own2).map((a) => a.seq);
30063
+ const own3 = this.store.writer();
30064
+ const seqs = acknowledged.filter((a) => a.writer === own3).map((a) => a.seq);
28867
30065
  if (!seqs.length) return;
28868
30066
  const touched = this.store.acknowledged(seqs);
28869
30067
  if (touched.length) this.host.notify(touched);
@@ -29049,9 +30247,9 @@ var RecordLogDocumentSession = class {
29049
30247
  `[record-log] ${this.docId}: the db3 is typed by ${frame.db3Type ?? "its type"}; the room keeps the type's declarations, and this client's models are judged against them.`
29050
30248
  );
29051
30249
  if (typeof frame.db3Type === "string" && frame.db3Type) {
29052
- const held = this.store.marks().db3Type;
30250
+ const held2 = this.store.marks().db3Type;
29053
30251
  await this.store.setState({
29054
- type: { typed: "yes", db3Type: { name: frame.db3Type, hash: held?.name === frame.db3Type ? held.hash : null } }
30252
+ type: { typed: "yes", db3Type: { name: frame.db3Type, hash: held2?.name === frame.db3Type ? held2.hash : null } }
29055
30253
  });
29056
30254
  }
29057
30255
  this.host.declared?.(this.docId);
@@ -29275,7 +30473,7 @@ var RecordLogSessions = class {
29275
30473
  connection: () => this.connection,
29276
30474
  awaitTypeBeforeDeclaring: this.host.awaitTypeBeforeDeclaring === true,
29277
30475
  scopesDeclarations: this.host.scopesDeclarations === true,
29278
- declarations: (id, held) => this.host.declarations(id, held),
30476
+ declarations: (id, held2) => this.host.declarations(id, held2),
29279
30477
  notify: (records) => this.host.notify(records),
29280
30478
  reportRefused: (event) => this.host.reportRefused(event),
29281
30479
  synced: (id) => {
@@ -29381,10 +30579,10 @@ function namedIndexName(model, name) {
29381
30579
  return `idx_named_${model.toLowerCase()}_${name.toLowerCase()}`;
29382
30580
  }
29383
30581
  function memberIndexName(model, field, taken) {
29384
- const held = new Set([...taken].map((name) => name.toLowerCase()));
30582
+ const held2 = new Set([...taken].map((name) => name.toLowerCase()));
29385
30583
  const base = `idx_members_${model}_${field}`.toLowerCase();
29386
- if (!held.has(base)) return base;
29387
- for (let n = 2; ; n++) if (!held.has(`${base}_${n}`)) return `${base}_${n}`;
30584
+ if (!held2.has(base)) return base;
30585
+ for (let n = 2; ; n++) if (!held2.has(`${base}_${n}`)) return `${base}_${n}`;
29388
30586
  }
29389
30587
  function constraintIndexName(model, constraint) {
29390
30588
  const name = constraint.replace(/[^A-Za-z0-9_]/g, "_");
@@ -29474,7 +30672,7 @@ function localIndexList(declarations, registrations) {
29474
30672
  continue;
29475
30673
  }
29476
30674
  const key = fieldsKey([registration.model, ...registration.fields]);
29477
- const held = byDefinition.get(key);
30675
+ const held2 = byDefinition.get(key);
29478
30676
  const origin = { kind: "named", unique: registration.unique };
29479
30677
  if (registration.members) {
29480
30678
  byDefinition.set(key, {
@@ -29489,9 +30687,9 @@ function localIndexList(declarations, registrations) {
29489
30687
  });
29490
30688
  continue;
29491
30689
  }
29492
- if (held) {
29493
- held.origins = [...held.origins.filter((o) => o.kind !== "named"), origin];
29494
- held.unique = held.origins.some((o) => o.unique);
30690
+ if (held2) {
30691
+ held2.origins = [...held2.origins.filter((o) => o.kind !== "named"), origin];
30692
+ held2.unique = held2.origins.some((o) => o.unique);
29495
30693
  continue;
29496
30694
  }
29497
30695
  byDefinition.set(key, {
@@ -29539,7 +30737,7 @@ var VECTOR_QUANTIZERS = ["pq", "opq", "bq"];
29539
30737
  var isPositiveInteger = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1;
29540
30738
  function vectorOptionsProblem(options) {
29541
30739
  if (options === void 0) return null;
29542
- if (!isPlainObject5(options)) return "vector options must be an object of { distance?, index? }";
30740
+ if (!isPlainObject6(options)) return "vector options must be an object of { distance?, index? }";
29543
30741
  const vector = options;
29544
30742
  const unknown = Object.keys(vector).find((key) => key !== "distance" && key !== "index");
29545
30743
  if (unknown !== void 0) return `vector options take distance and index, not ${JSON.stringify(unknown)}`;
@@ -29549,7 +30747,7 @@ function vectorOptionsProblem(options) {
29549
30747
  const index = vector.index;
29550
30748
  if (index === void 0 || index === "exact") return null;
29551
30749
  const shape = `vector.index must be "exact" or { mode: "ann", nbucket?, codesize?, quantizer? }`;
29552
- if (!isPlainObject5(index)) return shape;
30750
+ if (!isPlainObject6(index)) return shape;
29553
30751
  const ann = index;
29554
30752
  if (ann.mode !== "ann") return shape;
29555
30753
  const extra = Object.keys(ann).find((key) => !["mode", "nbucket", "codesize", "quantizer"].includes(key));
@@ -29562,7 +30760,7 @@ function vectorOptionsProblem(options) {
29562
30760
  }
29563
30761
  return null;
29564
30762
  }
29565
- var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30763
+ var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
29566
30764
  function parseLocalRegistration(body, support) {
29567
30765
  if (!body || typeof body !== "object" || Array.isArray(body)) {
29568
30766
  throw invalid2("An index registration is an object: { model, field | fields, kind?, on?, unique?, name? }");
@@ -29583,7 +30781,7 @@ function parseLocalRegistration(body, support) {
29583
30781
  for (const options of ["text", "vector"]) {
29584
30782
  if (raw[options] === void 0) continue;
29585
30783
  if (kind !== options) throw invalid2(`${options} options apply to kind: "${options}" only`);
29586
- if (!isPlainObject5(raw[options])) throw invalid2(`${options} options must be an object`);
30784
+ if (!isPlainObject6(raw[options])) throw invalid2(`${options} options must be an object`);
29587
30785
  }
29588
30786
  if (kind === "members" && raw.fields !== void 0) {
29589
30787
  throw invalid2(`A member index is { model, field, kind: "members" }: it covers one field and takes no fields`);
@@ -29722,15 +30920,15 @@ function registerLocalIndex(declarations, registrations, body, duplicates, suppo
29722
30920
  function registerTextIndex(declarations, registrations, request) {
29723
30921
  const { model, fields } = request;
29724
30922
  const list = localIndexList(declarations, registrations);
29725
- const held = list.find((index2) => index2.kind === "text" && index2.model === model);
29726
- if (held && fieldsKey(held.fields) !== fieldsKey(fields)) {
30923
+ const held2 = list.find((index2) => index2.kind === "text" && index2.model === model);
30924
+ if (held2 && fieldsKey(held2.fields) !== fieldsKey(fields)) {
29727
30925
  throw new RecordLogLocalIndexError(
29728
30926
  "DB3_INDEX_EXISTS",
29729
- `${model} already has a text index, ${held.name}, on ${held.fields.join(", ")}: a model has one text index, so drop it before registering another`,
29730
- { index: held.name }
30927
+ `${model} already has a text index, ${held2.name}, on ${held2.fields.join(", ")}: a model has one text index, so drop it before registering another`,
30928
+ { index: held2.name }
29731
30929
  );
29732
30930
  }
29733
- if (held) return { registrations: [...registrations], index: held };
30931
+ if (held2) return { registrations: [...registrations], index: held2 };
29734
30932
  const taken = new Set([...list.map((index2) => index2.name), ...registrations.map((r) => r.name)].map((name2) => name2.toLowerCase()));
29735
30933
  const base = textIndexName(model);
29736
30934
  let name = base;
@@ -29744,8 +30942,8 @@ function registerVectorIndex(declarations, registrations, request) {
29744
30942
  const { model } = request;
29745
30943
  const field = request.fields[0];
29746
30944
  const list = localIndexList(declarations, registrations);
29747
- const held = list.find((index2) => index2.kind === "vector" && index2.model === model && index2.fields[0] === field);
29748
- if (held) return { registrations: [...registrations], index: held };
30945
+ const held2 = list.find((index2) => index2.kind === "vector" && index2.model === model && index2.fields[0] === field);
30946
+ if (held2) return { registrations: [...registrations], index: held2 };
29749
30947
  const declared = entriesOf(declarations.find((d) => d.model === model)?.fields ?? {}).find(([name2]) => name2 === field)?.[1];
29750
30948
  const vector = vectorOptionsOf({ ...request.vector ?? {}, dims: declared?.dims, element: declared?.element });
29751
30949
  if (declared?.type !== "vector" || !vector) {
@@ -29839,7 +31037,7 @@ var RecordLogDocumentBinding = class {
29839
31037
  awaitTypeBeforeDeclaring: true,
29840
31038
  // Each db3 is declared the models it uses (#5115).
29841
31039
  scopesDeclarations: true,
29842
- declarations: (docId, held) => this.declarations(docId, held),
31040
+ declarations: (docId, held2) => this.declarations(docId, held2),
29843
31041
  notify: (records) => this.notify(records),
29844
31042
  reportRefused: (event) => this.ormContext.reportRecordLogWriteRefused(event)
29845
31043
  });
@@ -30154,9 +31352,9 @@ var RecordLogDocumentBinding = class {
30154
31352
  * there. Each is its fields with their JSON options and its compound
30155
31353
  * unique constraints. With no `docId`, every active model's.
30156
31354
  */
30157
- declarations(docId, held = []) {
31355
+ declarations(docId, held2 = []) {
30158
31356
  const out = {};
30159
- const wanted2 = new Set(held);
31357
+ const wanted2 = new Set(held2);
30160
31358
  const globalDefault = docId !== void 0 && this.ormContext.getGlobalDefaultDocumentId() === docId;
30161
31359
  for (const [, modelClass] of this.modelRegistry.getActiveModels()) {
30162
31360
  const schema = modelClass.getSchema?.();
@@ -31275,6 +32473,7 @@ init_BaseModel();
31275
32473
  init_ModelRegistry();
31276
32474
  init_uniqueIndex();
31277
32475
  init_vector();
32476
+ init_fieldNames();
31278
32477
  function defineModelSchema(input) {
31279
32478
  for (const [field, options] of Object.entries(input.fields)) {
31280
32479
  const problem = vectorFieldProblem(options);
@@ -31298,7 +32497,8 @@ function buildDefinedModelSchema(input) {
31298
32497
  name,
31299
32498
  className: input.options?.className,
31300
32499
  uniqueConstraints: input.options?.uniqueConstraints ? [...input.options.uniqueConstraints] : void 0,
31301
- relationships: input.options?.relationships
32500
+ relationships: input.options?.relationships,
32501
+ ...input.options?.removedFields ? { removedFields: [...input.options.removedFields] } : {}
31302
32502
  };
31303
32503
  const schema = {
31304
32504
  name,
@@ -31309,20 +32509,35 @@ function buildDefinedModelSchema(input) {
31309
32509
  if (schema.runtimeShape && schema.runtimeShape.class === modelClass) {
31310
32510
  return schema.runtimeShape;
31311
32511
  }
32512
+ const fieldNames = fieldNameMapOf(fields);
31312
32513
  const fieldsMap = /* @__PURE__ */ new Map();
31313
32514
  for (const [fieldName, fieldOptions] of Object.entries(fields)) {
31314
- fieldsMap.set(fieldName, { ...fieldOptions });
32515
+ if (fieldNames && fieldOptions.storedAs !== void 0) {
32516
+ const { storedAs: _storedAs, ...rest } = fieldOptions;
32517
+ void _storedAs;
32518
+ fieldsMap.set(storedNameOf(fieldNames, fieldName), rest);
32519
+ } else {
32520
+ fieldsMap.set(fieldName, { ...fieldOptions });
32521
+ }
31315
32522
  }
32523
+ const shapeOptions = fieldNames && options.uniqueConstraints ? {
32524
+ ...options,
32525
+ uniqueConstraints: options.uniqueConstraints.map((constraint) => ({
32526
+ ...constraint,
32527
+ fields: constraint.fields.map((field) => storedNameOf(fieldNames, field))
32528
+ }))
32529
+ } : options;
31316
32530
  const resolvedUniqueConstraints = resolveUniqueConstraints(
31317
32531
  name,
31318
32532
  fieldsMap,
31319
- options.uniqueConstraints
32533
+ shapeOptions.uniqueConstraints
31320
32534
  );
31321
32535
  schema.runtimeShape = {
31322
32536
  class: modelClass,
31323
- options,
32537
+ options: shapeOptions,
31324
32538
  fields: fieldsMap,
31325
- resolvedUniqueConstraints
32539
+ resolvedUniqueConstraints,
32540
+ fieldNames
31326
32541
  };
31327
32542
  return schema.runtimeShape;
31328
32543
  }
@@ -31573,6 +32788,7 @@ function schemaToToml(schema) {
31573
32788
  }
31574
32789
 
31575
32790
  // src/models/tomlLoader.ts
32791
+ init_fieldNames();
31576
32792
  var import_smol_toml2 = require("smol-toml");
31577
32793
  init_reservedFields();
31578
32794
  init_uniqueIndex();
@@ -31584,7 +32800,7 @@ var FIELD_CONTEXTS = {
31584
32800
  model: {
31585
32801
  values: "as-written",
31586
32802
  types: FIELD_TYPES,
31587
- keys: ["type", "indexed", "unique", "required", "auto_assign", "auto_stamp", "max_length", "max_count", "default", "enum", "enforce_enum", "dims", "element"]
32803
+ keys: ["type", "indexed", "unique", "required", "auto_assign", "auto_stamp", "max_length", "max_count", "default", "enum", "enforce_enum", "dims", "element", "deprecated", "cleared", "storedAs"]
31588
32804
  },
31589
32805
  property: {
31590
32806
  values: "checked",
@@ -31718,6 +32934,19 @@ var FIELD_KEYS = [
31718
32934
  contexts: { model: "allowed", property: { refused: "a property is never a vector (element)" }, io: { refused: notStored("element") } },
31719
32935
  types: ["vector"]
31720
32936
  },
32937
+ { key: "deprecated", prop: "deprecated", kind: "flag", storage: false, contexts: { model: "allowed", property: "unknown", io: "unknown" }, flagTier: "always" },
32938
+ {
32939
+ key: "cleared",
32940
+ prop: "cleared",
32941
+ kind: "flag",
32942
+ storage: false,
32943
+ contexts: { model: "allowed", property: "unknown", io: "unknown" },
32944
+ flagTier: "always",
32945
+ needs: "deprecated",
32946
+ refusedWith: "required"
32947
+ },
32948
+ // The name records hold for a renamed db3 field; the loader judges the name itself.
32949
+ { key: "storedAs", prop: "storedAs", kind: "string", storage: false, contexts: { model: "allowed", property: "unknown", io: "unknown" } },
31721
32950
  {
31722
32951
  key: "client",
31723
32952
  prop: "client",
@@ -31743,7 +32972,7 @@ var FIELD_KEYS = [
31743
32972
  { key: "description", prop: "description", kind: "string", storage: false, contexts: ioOnly },
31744
32973
  { key: "schema", prop: "schema", kind: "table", storage: false, contexts: ioOnly }
31745
32974
  ];
31746
- var own = (record, key) => Object.prototype.hasOwnProperty.call(record, key);
32975
+ var own2 = (record, key) => Object.prototype.hasOwnProperty.call(record, key);
31747
32976
  var isTable = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
31748
32977
  var positiveInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
31749
32978
  function rowFor(key) {
@@ -31804,9 +33033,15 @@ function judge(row, value, decl, spec, table) {
31804
33033
  switch (row.kind) {
31805
33034
  case "flag":
31806
33035
  if (row.flagTier === "always" && typeof value !== "boolean") return { problem: { code: "bad-boolean", key: row.key } };
31807
- if (row.needs === "enum" && value === true && !(own(table, "enum") && table.enum !== void 0)) {
33036
+ if (row.needs === "enum" && value === true && !(own2(table, "enum") && table.enum !== void 0)) {
31808
33037
  return { problem: { code: "enforce-without-enum", key: "enforce_enum" } };
31809
33038
  }
33039
+ if (row.needs === "deprecated" && value === true && table.deprecated !== true) {
33040
+ return { problem: { code: "cleared-without-deprecated", key: "cleared" } };
33041
+ }
33042
+ if (row.refusedWith === "required" && value === true && table.required === true) {
33043
+ return { problem: { code: "cleared-with-required", key: "cleared" } };
33044
+ }
31810
33045
  if (row.flagTier === "always" || !checked) return { value: value === true ? true : void 0 };
31811
33046
  return typeof value === "boolean" ? { value } : { problem: { code: "bad-boolean", key: row.key } };
31812
33047
  case "literal": {
@@ -31851,7 +33086,7 @@ function readFieldTable(raw, context) {
31851
33086
  else if (entry !== "allowed") problems.push({ code: "unknown-key", key, allowed: [...spec.keys] });
31852
33087
  }
31853
33088
  const type = table.type;
31854
- if (typeof type === "string" && spec.refusedTypes && own(spec.refusedTypes, type)) {
33089
+ if (typeof type === "string" && spec.refusedTypes && own2(spec.refusedTypes, type)) {
31855
33090
  problems.push({ code: "refused-type", type, reason: spec.refusedTypes[type] });
31856
33091
  return { decl: null, problems };
31857
33092
  }
@@ -31860,7 +33095,7 @@ function readFieldTable(raw, context) {
31860
33095
  return { decl: null, problems };
31861
33096
  }
31862
33097
  const decl = { type };
31863
- const rows = FIELD_KEYS.filter((row) => row.kind !== "type" && row.contexts[context] === "allowed" && own(table, row.key) && table[row.key] !== void 0);
33098
+ const rows = FIELD_KEYS.filter((row) => row.kind !== "type" && row.contexts[context] === "allowed" && own2(table, row.key) && table[row.key] !== void 0);
31864
33099
  const ordered = [...rows.filter((row) => row.kind !== "typed-default"), ...rows.filter((row) => row.kind === "typed-default")];
31865
33100
  for (const row of ordered) {
31866
33101
  const judged = judge(row, table[row.key], decl, spec, table);
@@ -31902,6 +33137,10 @@ function fieldProblemMessage(problem) {
31902
33137
  return "enum repeats a value";
31903
33138
  case "enforce-without-enum":
31904
33139
  return "enforce_enum needs an enum to enforce";
33140
+ case "cleared-without-deprecated":
33141
+ return "cleared needs deprecated = true beside it: deprecate a field before clearing it";
33142
+ case "cleared-with-required":
33143
+ return "cleared cannot be set on a required field: make the field optional, ship builds generated from that, then clear it";
31905
33144
  }
31906
33145
  }
31907
33146
 
@@ -31909,13 +33148,39 @@ function fieldProblemMessage(problem) {
31909
33148
  var import_smol_toml = require("smol-toml");
31910
33149
  var isTable2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
31911
33150
  var fail = (message) => ({ ok: false, message });
33151
+ var BESIDE_OBJECT_REF = {
33152
+ type: "the field is stored as JSON text in a string field",
33153
+ enum: "the def declares the value's shape",
33154
+ indexed: "an index on JSON text neither orders nor matches the values inside it",
33155
+ unique: "uniqueness of JSON text is not uniqueness of the values inside it",
33156
+ default: "a JSON field has no default",
33157
+ max_length: "bound the value in the def (maxLength, maxItems) instead",
33158
+ max_count: "it bounds a stringset field",
33159
+ auto_assign: "the client writes a JSON field's value",
33160
+ auto_stamp: "the client writes a JSON field's value",
33161
+ dims: "it shapes a vector field",
33162
+ element: "it shapes a vector field"
33163
+ };
33164
+ function besideObjectRef(raw) {
33165
+ const key = Object.keys(raw).find((k) => k !== "ref" && k !== "required");
33166
+ if (key === void 0) return null;
33167
+ const why = Object.prototype.hasOwnProperty.call(BESIDE_OBJECT_REF, key) ? BESIDE_OBJECT_REF[key] : "only required may";
33168
+ return `${key} cannot sit beside a ref to an object def: ${why}, so remove it.`;
33169
+ }
31912
33170
  function expandSharedEnumField(raw, resolve) {
31913
33171
  const has2 = (key) => isTable2(raw) && Object.prototype.hasOwnProperty.call(raw, key);
31914
33172
  if (!has2("ref")) return { ok: true, field: raw };
31915
33173
  const beside = ["type", "enum"].filter(has2);
31916
33174
  const [it, them] = beside.length > 1 ? ["both", "them"] : ["it", "it"];
31917
- if (beside.length > 0) return fail(`${beside.join(" and ")} cannot sit beside ref; the shared enum supplies ${it}, so remove ${them}.`);
33175
+ const enumBeside = () => fail(`${beside.join(" and ")} cannot sit beside ref; the shared enum supplies ${it}, so remove ${them}.`);
31918
33176
  const found = resolve(raw.ref);
33177
+ if (found.ok && "object" in found) {
33178
+ const refused = besideObjectRef(raw);
33179
+ if (refused) return fail(refused);
33180
+ const entries2 = Object.entries(raw).map(([k, v]) => k === "ref" ? ["type", "string"] : [k, v]);
33181
+ return { ok: true, field: Object.fromEntries(entries2), json: { ...found.object } };
33182
+ }
33183
+ if (beside.length > 0) return enumBeside();
31919
33184
  if (!found.ok) return found;
31920
33185
  const entries = Object.entries(raw).flatMap(([k, v]) => k === "ref" ? [["type", "string"], ["enum", found.values]] : [[k, v]]);
31921
33186
  return { ok: true, field: Object.fromEntries(entries), sharedEnum: { file: found.file, name: found.name, values: [...found.values] } };
@@ -31926,7 +33191,8 @@ var KNOWN_MODEL_KEYS = /* @__PURE__ */ new Set([
31926
33191
  "fields",
31927
33192
  "relationships",
31928
33193
  "unique_constraints",
31929
- "class_name"
33194
+ "class_name",
33195
+ "removedFields"
31930
33196
  ]);
31931
33197
  var KNOWN_RELATIONSHIP_KEYS = /* @__PURE__ */ new Set([
31932
33198
  "type",
@@ -31998,6 +33264,8 @@ function parseFieldOptions(raw, context, strict, vectors, fieldName, sharedEnums
31998
33264
  throw new Error(`${context}: \`enum\` values must all be strings.`);
31999
33265
  }
32000
33266
  enforceEnumProblem(raw, decl, problems, context, fieldName, vectors);
33267
+ lifecycleProblem(raw, decl, problems, context, fieldName);
33268
+ const storedAs = storedAsOf(raw, problems, context, fieldName);
32001
33269
  const opts = { type: decl.type };
32002
33270
  if (decl.type === "vector") {
32003
33271
  opts.dims = decl.dims;
@@ -32013,8 +33281,66 @@ function parseFieldOptions(raw, context, strict, vectors, fieldName, sharedEnums
32013
33281
  if (decl.default !== void 0) opts.default = decl.default;
32014
33282
  if (decl.enum !== void 0) opts.enum = [...decl.enum];
32015
33283
  if (decl.enforceEnum === true) opts.enforceEnum = true;
33284
+ if (decl.deprecated === true) opts.deprecated = true;
33285
+ if (decl.cleared === true) opts.cleared = true;
33286
+ if (storedAs !== void 0 && storedAs !== fieldName) opts.storedAs = storedAs;
32016
33287
  return opts;
32017
33288
  }
33289
+ var STORED_NAME_RE = /^[A-Za-z][A-Za-z0-9_]*$/;
33290
+ function storedAsOf(raw, problems, context, fieldName) {
33291
+ if (!Object.prototype.hasOwnProperty.call(raw, "storedAs")) return void 0;
33292
+ const value = raw.storedAs;
33293
+ if (typeof value !== "string" || value === "" || problems.some((p) => "key" in p && p.key === "storedAs" && p.code === "bad-string")) {
33294
+ throw new Error(`${context}: storedAs must be a non-empty string naming the field's stored name`);
33295
+ }
33296
+ if (fieldName === "id") throw new Error(`${context}: storedAs cannot be set on the id field`);
33297
+ if (value === "id") throw new Error(`${context}: storedAs "id" names the record's id; a field's stored name is never id`);
33298
+ const reserved = checkReservedFieldName(value);
33299
+ if (reserved) throw new Error(`${context}: storedAs ${JSON.stringify(value)} is reserved: ${reserved}`);
33300
+ if (!STORED_NAME_RE.test(value)) {
33301
+ throw new Error(`${context}: storedAs ${JSON.stringify(value)} is not an identifier (a letter, then letters, digits or _)`);
33302
+ }
33303
+ return value;
33304
+ }
33305
+ function storedNamesProblem(modelName, declared) {
33306
+ const storedBy = /* @__PURE__ */ new Map();
33307
+ for (const [field, options] of declared) {
33308
+ if (options.storedAs === void 0) continue;
33309
+ const context = `[models.${modelName}.fields.${field}]`;
33310
+ if (declared.has(options.storedAs)) {
33311
+ return `${context}: storedAs ${JSON.stringify(options.storedAs)} is the key of another declared field; a stored name belongs to one field`;
33312
+ }
33313
+ const other = storedBy.get(options.storedAs);
33314
+ if (other !== void 0) {
33315
+ return `${context}: storedAs ${JSON.stringify(options.storedAs)} is also the stored name of ${other}; a stored name belongs to one field`;
33316
+ }
33317
+ storedBy.set(options.storedAs, field);
33318
+ }
33319
+ return null;
33320
+ }
33321
+ function lifecycleProblem(raw, decl, problems, context, fieldName) {
33322
+ for (const key of ["cleared", "deprecated"]) {
33323
+ if (!Object.prototype.hasOwnProperty.call(raw, key)) continue;
33324
+ const problem = problems.find((p) => "key" in p && p.key === key && p.code !== "unknown-key");
33325
+ if (problem) throw new Error(`${context}: ${fieldProblemMessage(problem)}`);
33326
+ if (decl[key] === true && fieldName === "id") throw new Error(`${context}: ${key} cannot be set on the id field`);
33327
+ }
33328
+ }
33329
+ function parseRemovedFields(raw, modelName, declared) {
33330
+ const context = `[models.${modelName}]`;
33331
+ if (!Array.isArray(raw) || !raw.every((name) => typeof name === "string" && name.length > 0)) {
33332
+ throw new Error(`${context}: removedFields must be an array of field names`);
33333
+ }
33334
+ const seen = /* @__PURE__ */ new Set();
33335
+ for (const name of raw) {
33336
+ if (seen.has(name)) throw new Error(`${context}: removedFields names "${name}" twice`);
33337
+ seen.add(name);
33338
+ if (declared.has(name)) {
33339
+ throw new Error(`${context}: removedFields names "${name}", which the model still declares; a field is either declared or removed`);
33340
+ }
33341
+ }
33342
+ return [...raw];
33343
+ }
32018
33344
  function enforceEnumProblem(raw, decl, problems, context, fieldName, vectors) {
32019
33345
  if (!Object.prototype.hasOwnProperty.call(raw, "enforce_enum")) return;
32020
33346
  for (const problem of problems) {
@@ -32154,6 +33480,9 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
32154
33480
  }
32155
33481
  }
32156
33482
  const className = typeof modelDef.class_name === "string" ? modelDef.class_name : void 0;
33483
+ const removedFields = modelDef.removedFields === void 0 ? void 0 : parseRemovedFields(modelDef.removedFields, modelName, /* @__PURE__ */ new Set([...Object.keys(fields), ...declaredFields.keys()]));
33484
+ const storedNames = storedNamesProblem(modelName, declaredFields);
33485
+ if (storedNames) throw new Error(storedNames);
32157
33486
  const vectorConstraint = vectorConstraintProblem(declaredFields, uniqueConstraints);
32158
33487
  if (vectorConstraint) {
32159
33488
  throw new Error(`[[models.${modelName}.unique_constraints]]: ${vectorConstraint}`);
@@ -32177,11 +33506,18 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
32177
33506
  options: {
32178
33507
  className,
32179
33508
  uniqueConstraints,
32180
- relationships
33509
+ relationships,
33510
+ ...removedFields ? { removedFields } : {}
32181
33511
  }
32182
33512
  })
32183
33513
  );
32184
33514
  }
33515
+ const typeName = isTypeFile && typeof parsed.type.name === "string" && parsed.type.name !== "" ? parsed.type.name : null;
33516
+ if (typeName !== null) {
33517
+ for (const schema of schemas) {
33518
+ if (fieldNameMapOf(schema.fields)) declareFieldNameTypes([schema], { [schema.name]: [typeName] });
33519
+ }
33520
+ }
32185
33521
  return schemas;
32186
33522
  }
32187
33523
  function findReservedFieldNameInToml(tomlString) {
@@ -32678,7 +34014,7 @@ var SWIFT_CODEGEN_RESERVED_NAMES = [
32678
34014
  ];
32679
34015
  var QUERY_TABLE_COLUMNS = ["id", "type"];
32680
34016
  var TYPE_PRECEDENCE = ["string", "number", "boolean", "stringset"];
32681
- var hasOwn2 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
34017
+ var hasOwn3 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
32682
34018
  var byCodePoint = (a, b) => a < b ? -1 : a > b ? 1 : 0;
32683
34019
  function pascalCase(name) {
32684
34020
  return name.split("_").filter((segment) => segment.length > 0).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)).join("");
@@ -32711,7 +34047,7 @@ function literalDefault(value) {
32711
34047
  return { problem: `${JSON.stringify(value) ?? String(value)} is not a string, a number, a boolean or an array of strings` };
32712
34048
  }
32713
34049
  function option(options, camel, snake) {
32714
- return hasOwn2(options, camel) ? options[camel] : hasOwn2(options, snake) ? options[snake] : void 0;
34050
+ return hasOwn3(options, camel) ? options[camel] : hasOwn3(options, snake) ? options[snake] : void 0;
32715
34051
  }
32716
34052
  function recordLogSchemaToToml(answer, options = {}) {
32717
34053
  const warn = options.warn ?? ((message) => Logger.warn(message));
@@ -32732,12 +34068,18 @@ function recordLogSchemaToToml(answer, options = {}) {
32732
34068
  );
32733
34069
  warn(`[schema-toml] omitted model "${other}": it differs from "${modelName}" only in case; read its records through documents.records()`);
32734
34070
  }
32735
- const names = [.../* @__PURE__ */ new Set([...Object.keys(declared), ...Object.keys(observed)])].filter((field) => field !== "id");
34071
+ const hidden = new Set(Array.isArray(entry.cleared) ? entry.cleared.map(String) : []);
34072
+ for (const field of [...hidden].sort(byCodePoint)) {
34073
+ if (field === "id" || !(hasOwn3(declared, field) || hasOwn3(observed, field))) continue;
34074
+ comments.push(`omitted: field "${field}" (the db3's type clears or tombstones it, so no record answers it)`);
34075
+ warn(`[schema-toml] ${modelName}: omitted field "${field}": the db3's type clears or tombstones it`);
34076
+ }
34077
+ const names = [.../* @__PURE__ */ new Set([...Object.keys(declared), ...Object.keys(observed)])].filter((field) => field !== "id" && !hidden.has(field));
32736
34078
  const fields = {};
32737
- const declaredId = hasOwn2(declared, "id") ? declared.id : null;
34079
+ const declaredId = hasOwn3(declared, "id") ? declared.id : null;
32738
34080
  fields.id = declaredId ? { ...declaredOptions(modelName, "id", declaredId, noteField, warn), type: "id" } : { type: "id", autoAssign: true };
32739
34081
  const kept = [];
32740
- for (const { kept: field, omitted } of caseGroups(names, (name) => hasOwn2(declared, name))) {
34082
+ for (const { kept: field, omitted } of caseGroups(names, (name) => hasOwn3(declared, name))) {
32741
34083
  for (const other of omitted) {
32742
34084
  comments.push(
32743
34085
  `omitted: field "${other}" (it differs from "${field}" only in case, and a query table keeps one column per field name ignoring case); its values stay readable through documents.records()`
@@ -32770,7 +34112,7 @@ function recordLogSchemaToToml(answer, options = {}) {
32770
34112
  return byCodePoint(a, b);
32771
34113
  });
32772
34114
  for (const field of kept) {
32773
- if (hasOwn2(declared, field)) {
34115
+ if (hasOwn3(declared, field)) {
32774
34116
  fields[field] = declaredOptions(modelName, field, declared[field], noteField, warn);
32775
34117
  continue;
32776
34118
  }
@@ -32860,5 +34202,7 @@ function declaredOptions(model, field, declared, noteField, warn) {
32860
34202
 
32861
34203
  // src/browser.ts
32862
34204
  init_documentTypes();
34205
+ init_jsonFields();
32863
34206
  init_vector();
32864
34207
  init_yjsRuntime();
34208
+ init_fieldNames();