js-bao 0.12.0-alpha.18 → 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
@@ -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
  }
@@ -3240,6 +3240,322 @@ 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
+
3243
3559
  // src/models/jsonFields.ts
3244
3560
  function quoted(text, path) {
3245
3561
  for (let i = 0; i < text.length; i++) {
@@ -3446,7 +3762,8 @@ function bindDb3JsonFields(modelClass, fields) {
3446
3762
  const schema = modelClass.getSchema?.();
3447
3763
  const modelName = schema?.options?.name ?? modelClass.name ?? "model";
3448
3764
  const bound = bindings.get(modelClass) ?? /* @__PURE__ */ new Map();
3449
- for (const [field, def] of Object.entries(fields)) {
3765
+ for (const [named, def] of Object.entries(fields)) {
3766
+ const field = storedNameOf(schema?.fieldNames, named);
3450
3767
  if (!def || typeof def.id !== "string" || !isNode(def.schema)) {
3451
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\`.`);
3452
3769
  }
@@ -3529,6 +3846,7 @@ var Db3JsonValueError, Refusal, MAX_EXACT, isNode, hasOwn, isScalarTag, ONE_OF_S
3529
3846
  var init_jsonFields = __esm({
3530
3847
  "src/models/jsonFields.ts"() {
3531
3848
  "use strict";
3849
+ init_fieldNames();
3532
3850
  Db3JsonValueError = class _Db3JsonValueError extends Error {
3533
3851
  code = "DB3_JSON_INVALID";
3534
3852
  model;
@@ -3936,7 +4254,7 @@ var init_vectorIndex = __esm({
3936
4254
 
3937
4255
  // src/query/nearSearch.ts
3938
4256
  function hasNear(filter) {
3939
- return isPlainObject2(filter) && Object.prototype.hasOwnProperty.call(filter, "$near");
4257
+ return isPlainObject3(filter) && Object.prototype.hasOwnProperty.call(filter, "$near");
3940
4258
  }
3941
4259
  function parseNearRead(filter, include) {
3942
4260
  if (findNearInRead("", void 0, include)) throw nested();
@@ -3949,7 +4267,7 @@ function parseNearRead(filter, include) {
3949
4267
  throw new DocumentQueryError("$near is the only key of its filter: put the other conditions under $near.filter");
3950
4268
  }
3951
4269
  const near = outer.$near;
3952
- 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? }");
3953
4271
  const extra = Object.keys(near).find((key) => !NEAR_KEYS.has(key));
3954
4272
  if (extra !== void 0) throw new DocumentQueryError(`$near takes field, vector, k and filter, not ${JSON.stringify(extra)}`);
3955
4273
  if (typeof near.field !== "string" || !IDENTIFIER.test(near.field)) throw new DocumentQueryError("$near.field must name the vector field");
@@ -3962,7 +4280,7 @@ function parseNearRead(filter, include) {
3962
4280
  throw new DocumentQueryError(`$near.k must be an integer from 1 to ${DB3_NEAR_MAX_K}`);
3963
4281
  }
3964
4282
  const inner = near.filter === void 0 ? {} : near.filter;
3965
- 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");
3966
4284
  if (findNearInRead("", inner) || containsSearch(inner)) throw new DocumentQueryError("$near's filter takes neither $near nor $search");
3967
4285
  return { field: near.field, vector, k, filter: inner };
3968
4286
  }
@@ -4023,7 +4341,7 @@ function nearSubquery(read, viewTable, filterSql, filterParams = []) {
4023
4341
  params: [read.vector, read.vector, options, ...filterParams]
4024
4342
  };
4025
4343
  }
4026
- var DISTANCE_KEY, IDENTIFIER, NEAR_KEYS, isPlainObject2, nested, NearVectorInvalidError, quote, nearTieWindow;
4344
+ var DISTANCE_KEY, IDENTIFIER, NEAR_KEYS, isPlainObject3, nested, NearVectorInvalidError, quote, nearTieWindow;
4027
4345
  var init_nearSearch = __esm({
4028
4346
  "src/query/nearSearch.ts"() {
4029
4347
  "use strict";
@@ -4033,7 +4351,7 @@ var init_nearSearch = __esm({
4033
4351
  DISTANCE_KEY = "_distance";
4034
4352
  IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
4035
4353
  NEAR_KEYS = /* @__PURE__ */ new Set(["field", "vector", "k", "filter"]);
4036
- 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);
4037
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");
4038
4356
  NearVectorInvalidError = class _NearVectorInvalidError extends DocumentQueryError {
4039
4357
  /** Always `DB3_VECTOR_INVALID`. */
@@ -4881,7 +5199,7 @@ var init_reservedFields = __esm({
4881
5199
  // src/record-log/textIndex.ts
4882
5200
  function parseTextIndexOptions(fields, raw) {
4883
5201
  if (raw === void 0) raw = {};
4884
- 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");
4885
5203
  const unknown = Object.keys(raw).find((key) => !OPTION_KEYS.includes(key));
4886
5204
  if (unknown !== void 0) {
4887
5205
  throw new TextIndexOptionsError(`text.${unknown} is not a text index option: give tokenizer, prefix or weights`, unknown);
@@ -4898,7 +5216,7 @@ function parseTextIndexOptions(fields, raw) {
4898
5216
  );
4899
5217
  }
4900
5218
  const given = raw.weights ?? {};
4901
- 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");
4902
5220
  for (const [field, weight] of Object.entries(given)) {
4903
5221
  if (!fields.includes(field)) {
4904
5222
  throw new TextIndexOptionsError(`text.weights.${field} names a field the index does not cover: ${fields.join(", ")}`, "weights");
@@ -4937,7 +5255,7 @@ function textInsertSql(table, fields) {
4937
5255
  function textDeleteSql(table, fields) {
4938
5256
  return `INSERT INTO ${quoted2(table)} (${[quoted2(table), "rowid", ...fields.map((_, i) => textColumnAlias(i))].join(", ")})`;
4939
5257
  }
4940
- var TEXT_INDEX_TOKENIZERS, TEXT_INDEX_MAX_PREFIXES, TEXT_INDEX_MAX_PREFIX_LENGTH, OPTION_KEYS, TextIndexOptionsError, isPlainObject3, quoted2, literal2;
5258
+ var TEXT_INDEX_TOKENIZERS, TEXT_INDEX_MAX_PREFIXES, TEXT_INDEX_MAX_PREFIX_LENGTH, OPTION_KEYS, TextIndexOptionsError, isPlainObject4, quoted2, literal2;
4941
5259
  var init_textIndex = __esm({
4942
5260
  "src/record-log/textIndex.ts"() {
4943
5261
  "use strict";
@@ -4952,7 +5270,7 @@ var init_textIndex = __esm({
4952
5270
  this.name = "TextIndexOptionsError";
4953
5271
  }
4954
5272
  };
4955
- isPlainObject3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5273
+ isPlainObject4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4956
5274
  quoted2 = (name) => `"${name.replace(/"/g, '""')}"`;
4957
5275
  literal2 = (text) => `'${text.replace(/'/g, "''")}'`;
4958
5276
  }
@@ -8977,6 +9295,69 @@ function heldRevisionClears(instance, fieldKey) {
8977
9295
  const modelName = modelConstructor.getSchema()?.options?.name;
8978
9296
  return store.declaredCleared()?.[modelName]?.includes(fieldKey) === true;
8979
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
+ }
8980
9361
  var import_ulid2, FORMAT2_ROW_PAGE, UniqueConstraintViolationError, VectorFieldFormatError, RecordNotFoundError, SCHEMA_ACCESSORS_KEY, RecordLogTransactionGroup, activeRecordLogTransactions, unboundRecordLogTransaction, recordLogTransactionsOpen, JS_BAO_FRAME, BaseModel2;
8981
9362
  var init_BaseModel = __esm({
8982
9363
  "src/models/BaseModel.ts"() {
@@ -9005,6 +9386,7 @@ var init_BaseModel = __esm({
9005
9386
  init_indexPlacement();
9006
9387
  init_nearSearch();
9007
9388
  init_OrmContext();
9389
+ init_fieldNames();
9008
9390
  init_write();
9009
9391
  init_declared_types();
9010
9392
  init_types();
@@ -9541,7 +9923,7 @@ var init_BaseModel = __esm({
9541
9923
  * `_related`, for every included row of a registered model, at every
9542
9924
  * depth. `own` false shapes only the related rows.
9543
9925
  */
9544
- static shapeDb3Row(row, modelName, includes, own2 = true, vectors = null) {
9926
+ static shapeDb3Row(row, modelName, includes, own3 = true, vectors = null) {
9545
9927
  const registry = resolveOrmContext(this).modelRegistry;
9546
9928
  const shape = (record, model, specs, self2) => {
9547
9929
  if (self2) {
@@ -9566,7 +9948,7 @@ var init_BaseModel = __esm({
9566
9948
  }
9567
9949
  return record;
9568
9950
  };
9569
- return shape(row, modelName, includes, own2);
9951
+ return shape(row, modelName, includes, own3);
9570
9952
  }
9571
9953
  /**
9572
9954
  * The documents an unscoped statement spans: every connected format-1
@@ -9723,8 +10105,10 @@ var init_BaseModel = __esm({
9723
10105
  static attachFieldAccessors(modelClass, fields) {
9724
10106
  const attached = _BaseModel.attachFieldAccessorsSet(modelClass);
9725
10107
  const prototype = modelClass.prototype;
9726
- for (const fieldName of fields.keys()) {
9727
- 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);
9728
10112
  if (attached.has(fieldName)) continue;
9729
10113
  const existingDescriptor = Object.getOwnPropertyDescriptor(
9730
10114
  prototype,
@@ -9737,10 +10121,10 @@ var init_BaseModel = __esm({
9737
10121
  configurable: true,
9738
10122
  enumerable: true,
9739
10123
  get() {
9740
- return this.getValue(fieldName);
10124
+ return this.getValue(storedName);
9741
10125
  },
9742
10126
  set(value) {
9743
- this.setValue(fieldName, value);
10127
+ this.setValue(storedName, value);
9744
10128
  }
9745
10129
  });
9746
10130
  attached.add(fieldName);
@@ -9768,6 +10152,7 @@ var init_BaseModel = __esm({
9768
10152
  schema.fields
9769
10153
  );
9770
10154
  }
10155
+ data = toStoredData(schema.options?.name ?? modelConstructor.name, schema.fieldNames, data);
9771
10156
  const idFieldOptions = schema.fields.get("id");
9772
10157
  if (data.id) {
9773
10158
  this.id = data.id;
@@ -10094,7 +10479,7 @@ var init_BaseModel = __esm({
10094
10479
  const fieldOptions = schema?.fields?.get(fieldKey);
10095
10480
  if (fieldOptions?.type === "stringset") {
10096
10481
  throw new Error(
10097
- `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.`
10098
10483
  );
10099
10484
  }
10100
10485
  if (!this._isLoadingFromYjs) {
@@ -10157,7 +10542,7 @@ var init_BaseModel = __esm({
10157
10542
  for (const [fieldKey, fieldOptions] of schema.fields.entries()) {
10158
10543
  const currentValue = fieldKey === "id" ? this.id : fieldOptions.type === "string" && db3JsonDefOf(this.constructor, fieldKey) ? db3JsonText(this, fieldKey) : this.getValue(fieldKey);
10159
10544
  if (fieldOptions.required && (currentValue === null || currentValue === void 0) && !cleared?.includes(fieldKey)) {
10160
- throw new Error(`Field ${fieldKey} is required before save`);
10545
+ throw new Error(`Field ${currentNameOf(schema.fieldNames, fieldKey)} is required before save`);
10161
10546
  }
10162
10547
  if (fieldOptions.type === "stringset" && currentValue instanceof StringSet) {
10163
10548
  if (fieldOptions.maxCount && currentValue.size > fieldOptions.maxCount) {
@@ -10179,16 +10564,18 @@ var init_BaseModel = __esm({
10179
10564
  }
10180
10565
  // State inspection helpers
10181
10566
  getChangedFields() {
10182
- 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));
10183
10570
  }
10184
10571
  getOriginalValue(fieldKey) {
10185
- return this.getFromYjs(fieldKey);
10572
+ return this.getFromYjs(storedNameOf(fieldNamesOfClass(this.constructor), fieldKey));
10186
10573
  }
10187
10574
  getCurrentValue(fieldKey) {
10188
- return this.getValue(fieldKey);
10575
+ return this.getValue(storedNameOf(fieldNamesOfClass(this.constructor), fieldKey));
10189
10576
  }
10190
10577
  hasFieldChanged(fieldKey) {
10191
- return this.hasLocalChange(fieldKey);
10578
+ return this.hasLocalChange(storedNameOf(fieldNamesOfClass(this.constructor), fieldKey));
10192
10579
  }
10193
10580
  // StringSet support methods
10194
10581
  markStringSetChange(fieldName, operation, value) {
@@ -11355,36 +11742,56 @@ var init_BaseModel = __esm({
11355
11742
  }
11356
11743
  let upsertOnConstraint = null;
11357
11744
  let upsertOnKey = null;
11745
+ let upsertTarget = null;
11358
11746
  if (options?.upsertOn) {
11359
- const upsertField = options.upsertOn;
11360
- assertValidIdentifier(upsertField, "upsertOn field");
11361
- const upsertValue = this[upsertField];
11362
- if (upsertValue === null || upsertValue === void 0 || upsertValue === "") {
11363
- throw new Error(
11364
- `[${modelName}] upsertOn field '${upsertField}' must be present in data and not null/empty`
11365
- );
11366
- }
11367
- const constraint = schema.resolvedUniqueConstraints.find(
11368
- (c) => c.fields.length === 1 && c.fields[0] === upsertField
11369
- );
11370
- if (!constraint) {
11371
- throw new Error(
11372
- `[${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
11373
11774
  );
11374
- }
11375
- const uniqueKey = modelConstructor._buildKeyFromValues(
11376
- constraint.fields,
11377
- [upsertValue],
11378
- modelName,
11379
- constraint.name
11380
- );
11381
- if (uniqueKey === null) {
11382
- throw new Error(
11383
- `[${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
11384
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] };
11385
11794
  }
11386
- upsertOnConstraint = constraint;
11387
- upsertOnKey = uniqueKey;
11388
11795
  }
11389
11796
  if (!this.id) {
11390
11797
  Logger.error(
@@ -11418,8 +11825,11 @@ var init_BaseModel = __esm({
11418
11825
  modelName,
11419
11826
  docId: targetDocId,
11420
11827
  permissionHint,
11421
- upsertOnField: options?.upsertOn ?? null,
11422
- 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
+ }
11423
11833
  })
11424
11834
  );
11425
11835
  this.clearLocalChanges();
@@ -11615,7 +12025,7 @@ var init_BaseModel = __esm({
11615
12025
  );
11616
12026
  if (existingRecordIdWithNewKey && existingRecordIdWithNewKey !== this.id) {
11617
12027
  throw new UniqueConstraintViolationError(
11618
- `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(
11619
12029
  ", "
11620
12030
  )}]. Attempted ID: ${this.id}. Value(s) starting with '${newUniqueKey.substring(
11621
12031
  0,
@@ -11623,7 +12033,7 @@ var init_BaseModel = __esm({
11623
12033
  )}...' already exist for record ID ${existingRecordIdWithNewKey}.`,
11624
12034
  modelName,
11625
12035
  constraint.name,
11626
- constraint.fields,
12036
+ currentFieldsOf(schema, constraint.fields),
11627
12037
  this.id,
11628
12038
  existingRecordIdWithNewKey
11629
12039
  );
@@ -11634,7 +12044,7 @@ var init_BaseModel = __esm({
11634
12044
  `[${modelName}] Save Check (Item '${this.id}'): index miss for '${constraint.name}', but engine fallback found conflicting index-less record ${conflictingRecordId}.`
11635
12045
  );
11636
12046
  throw new UniqueConstraintViolationError(
11637
- `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(
11638
12048
  ", "
11639
12049
  )}]. Attempted ID: ${this.id}. Value(s) starting with '${newUniqueKey.substring(
11640
12050
  0,
@@ -11642,7 +12052,7 @@ var init_BaseModel = __esm({
11642
12052
  )}...' already exist for index-less record ID ${conflictingRecordId}.`,
11643
12053
  modelName,
11644
12054
  constraint.name,
11645
- constraint.fields,
12055
+ currentFieldsOf(schema, constraint.fields),
11646
12056
  this.id,
11647
12057
  conflictingRecordId
11648
12058
  );
@@ -11843,7 +12253,8 @@ var init_BaseModel = __esm({
11843
12253
  const persisted = fieldKey === "id" ? this.id : this.getValue(fieldKey);
11844
12254
  if (persisted !== null && persisted !== void 0) continue;
11845
12255
  }
11846
- this[fieldKey] = Date.now();
12256
+ if (schema.fieldNames) this.setValue(fieldKey, Date.now());
12257
+ else this[fieldKey] = Date.now();
11847
12258
  if (stamp === "create") {
11848
12259
  preTransactCreateStamps.add(fieldKey);
11849
12260
  }
@@ -11860,7 +12271,7 @@ var init_BaseModel = __esm({
11860
12271
  * locally.
11861
12272
  */
11862
12273
  async saveRecordLog(ctx) {
11863
- const { store, schema, modelName, docId, permissionHint, upsertOnField, guards } = ctx;
12274
+ const { store, schema, modelName, docId, permissionHint, upsertTarget, guards } = ctx;
11864
12275
  let committedSeq = null;
11865
12276
  const modelConstructor = this.constructor;
11866
12277
  const ormContext = resolveOrmContext(modelConstructor);
@@ -11925,8 +12336,12 @@ var init_BaseModel = __esm({
11925
12336
  throw refused;
11926
12337
  }
11927
12338
  let upsertOn;
11928
- if (upsertOnField && !asCreate) {
11929
- 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
+ );
11930
12345
  if (matched && matched !== this.id) {
11931
12346
  if (this._constructorProvidedId) {
11932
12347
  throw new Error(
@@ -11943,7 +12358,7 @@ var init_BaseModel = __esm({
11943
12358
  }
11944
12359
  existing = stagedOr(this.id, await ops.read(modelName, this.id));
11945
12360
  } else if (!matched && existing === null) {
11946
- upsertOn = upsertOnField;
12361
+ upsertOn = upsertTarget.token;
11947
12362
  }
11948
12363
  }
11949
12364
  const postMutation = { ...existing ?? {} };
@@ -11959,10 +12374,10 @@ var init_BaseModel = __esm({
11959
12374
  const holder = await ops.findIdByFields(modelName, constraint.fields, values);
11960
12375
  if (holder !== null && holder !== this.id) {
11961
12376
  throw new UniqueConstraintViolationError(
11962
- `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}.`,
11963
12378
  modelName,
11964
12379
  constraint.name,
11965
- constraint.fields,
12380
+ currentFieldsOf(schema, constraint.fields),
11966
12381
  this.id,
11967
12382
  holder
11968
12383
  );
@@ -11988,7 +12403,7 @@ var init_BaseModel = __esm({
11988
12403
  Logger.warn("[record-log] write refused locally \u2014", docId, modelName, this.id, event.error.code);
11989
12404
  ormContext.reportRecordLogWriteRefused(event);
11990
12405
  };
11991
- const entryUpsertOn = upsertOn ?? (upsertOnField !== null && guards.ifNotExists ? upsertOnField : void 0);
12406
+ const entryUpsertOn = upsertOn ?? (upsertTarget !== null && guards.ifNotExists ? upsertTarget.token : void 0);
11992
12407
  assertRecordLogEntry(docId, [mutation], report, entryUpsertOn !== void 0 ? { upsertOn: entryUpsertOn } : {});
11993
12408
  if (!transaction) assertRecordLogDeclaredTypes(docId, [mutation], declaredTypeOf(store), report);
11994
12409
  this._format2Row = store.entryFor(modelName, this.id);
@@ -12104,6 +12519,12 @@ var init_BaseModel = __esm({
12104
12519
  const schema = modelConstructor.getSchema?.();
12105
12520
  const modelName = schema?.options?.name;
12106
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
+ }
12107
12528
  if (typeof id !== "string" || id.length === 0) {
12108
12529
  throw new Error(`[${modelName}] increment needs the id of the record to increment.`);
12109
12530
  }
@@ -12174,6 +12595,14 @@ var init_BaseModel = __esm({
12174
12595
  const settled = settlement.rows.find((r) => r.model === modelName && r.id === id)?.row;
12175
12596
  if (settled) values = valuesOf(settled);
12176
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
+ }
12177
12606
  return values;
12178
12607
  }
12179
12608
  /**
@@ -12314,7 +12743,7 @@ var init_BaseModel = __esm({
12314
12743
  store: recordLogStore,
12315
12744
  modelName,
12316
12745
  docId,
12317
- ...options?.condition !== void 0 ? { condition: options.condition } : {}
12746
+ ...options?.condition !== void 0 ? { condition: schema?.fieldNames ? toStoredFilter(schema.fieldNames, options.condition) : options.condition } : {}
12318
12747
  })
12319
12748
  );
12320
12749
  if (options?.confirm && seq !== null) await recordLogStore.whenAcknowledged(seq);
@@ -12413,7 +12842,9 @@ var init_BaseModel = __esm({
12413
12842
  }
12414
12843
  // Keep toJSON for backward compatibility, but delegate to getCurrentJSState
12415
12844
  toJSON() {
12416
- return this.getCurrentJSState();
12845
+ const state = this.getCurrentJSState();
12846
+ const names = fieldNamesOfClass(this.constructor);
12847
+ return names ? toCurrentRow(() => names, "", state) : state;
12417
12848
  }
12418
12849
  /**
12419
12850
  * Refuse a read through a class whose ORM instance has been destroyed
@@ -12545,6 +12976,12 @@ var init_BaseModel = __esm({
12545
12976
  throw new Error("Model not properly initialized for query");
12546
12977
  }
12547
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
+ }
12548
12985
  Logger.verbose(`[${modelName}] Executing query:`, { filter, options });
12549
12986
  const near = parseNearRead(filter, options?.include);
12550
12987
  const hasIncludes = options?.include && options.include.length > 0;
@@ -12580,7 +13017,7 @@ var init_BaseModel = __esm({
12580
13017
  { sort: options?.sort, include: options?.include },
12581
13018
  side
12582
13019
  );
12583
- return page;
13020
+ return renames ? currentPage(page, namesOf, modelName, options?.include) : page;
12584
13021
  }
12585
13022
  if (near) throw new Db3IndexNotOnDeviceError({ operator: "$near", model: modelName, field: near.field });
12586
13023
  if (side) {
@@ -12736,7 +13173,7 @@ var init_BaseModel = __esm({
12736
13173
  }).filter(Boolean);
12737
13174
  }
12738
13175
  return {
12739
- data: transformedData,
13176
+ data: renames ? currentRows(transformedData, namesOf, modelName, options?.include) : transformedData,
12740
13177
  nextCursor: cursors.nextCursor,
12741
13178
  prevCursor: cursors.prevCursor,
12742
13179
  hasMore
@@ -12805,6 +13242,8 @@ var init_BaseModel = __esm({
12805
13242
  throw new Error("Model not properly initialized for aggregation");
12806
13243
  }
12807
13244
  const modelName = schema.options.name;
13245
+ const aggregateNames = schema.fieldNames ?? null;
13246
+ if (aggregateNames) options = toStoredAggregate(aggregateNames, options);
12808
13247
  Logger.verbose(`[${modelName}] Executing structured aggregation:`, options);
12809
13248
  const near = parseNearRead(options.filter);
12810
13249
  for (const operation of options.operations) {
@@ -12899,7 +13338,7 @@ var init_BaseModel = __esm({
12899
13338
  writable: false
12900
13339
  });
12901
13340
  }
12902
- return rows;
13341
+ return toCurrentAggregateRows(aggregateNames, options, rows);
12903
13342
  }
12904
13343
  if (near) throw new Db3IndexNotOnDeviceError({ operator: "$near", model: modelName, field: near.field });
12905
13344
  if (side) {
@@ -12954,7 +13393,7 @@ var init_BaseModel = __esm({
12954
13393
  writable: false
12955
13394
  });
12956
13395
  }
12957
- return processedResult;
13396
+ return toCurrentAggregateRows(aggregateNames, options, processedResult);
12958
13397
  }
12959
13398
  /**
12960
13399
  * Build SQL query for structured aggregation, through js-bao's one
@@ -13104,6 +13543,7 @@ var init_BaseModel = __esm({
13104
13543
  throw new Error("Model not properly initialized for count");
13105
13544
  }
13106
13545
  const modelName = schema.options.name;
13546
+ filter = toStoredFilter(schema.fieldNames, filter);
13107
13547
  Logger.verbose(`[${modelName}] Executing count:`, { filter, options });
13108
13548
  const near = parseNearRead(filter);
13109
13549
  let scope = this.documentsInScope(
@@ -13289,9 +13729,7 @@ var init_BaseModel = __esm({
13289
13729
  `[${currentModelName}] Schema or unique constraints not loaded for findByUnique.`
13290
13730
  );
13291
13731
  }
13292
- const constraint = schema.resolvedUniqueConstraints.find(
13293
- (c) => c.name === constraintName
13294
- );
13732
+ const constraint = uniqueConstraintNamed(schema, constraintName);
13295
13733
  if (!constraint) {
13296
13734
  throw new Error(
13297
13735
  `[${currentModelName}] Unique constraint named '${constraintName}' not found.`
@@ -13433,22 +13871,23 @@ var init_BaseModel = __esm({
13433
13871
  `[${currentModelName}] No documents are connected. Connect at least one document via initJsBao(...).connectDocument or call initializeForDocument(yDoc, db, docId, permissionHint) before calling upsertByUnique.`
13434
13872
  );
13435
13873
  }
13436
- const constraint = schema.resolvedUniqueConstraints.find(
13437
- (c) => c.name === constraintName
13438
- );
13874
+ const constraint = uniqueConstraintNamed(schema, constraintName);
13439
13875
  if (!constraint) {
13440
13876
  throw new Error(
13441
13877
  `[${currentModelName}] Unique constraint named '${constraintName}' not found for upsert.`
13442
13878
  );
13443
13879
  }
13444
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);
13445
13884
  constraint.fields.forEach((field, index) => {
13446
- if (!dataToUpsert.hasOwnProperty(field)) {
13885
+ if (!storedUpsert.hasOwnProperty(field)) {
13447
13886
  throw new Error(
13448
- `[${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}'.`
13449
13888
  );
13450
13889
  }
13451
- const dataValue = dataToUpsert[field];
13890
+ const dataValue = storedUpsert[field];
13452
13891
  const lookupValue = keyValuesForLookup[index];
13453
13892
  if (dataValue !== lookupValue) {
13454
13893
  throw new Error(
@@ -13967,6 +14406,7 @@ __export(browser_exports, {
13967
14406
  DocumentWriteAccessDeniedError: () => DocumentWriteAccessDeniedError,
13968
14407
  FORMAT2_MANIFEST_VERSION: () => FORMAT2_MANIFEST_VERSION,
13969
14408
  FORMAT2_MIN_MANIFEST_VERSION: () => FORMAT2_MIN_MANIFEST_VERSION,
14409
+ FieldNamedTwiceError: () => FieldNamedTwiceError,
13970
14410
  Format2QueryScopeError: () => Db3QueryScopeError,
13971
14411
  Format2RowCache: () => Db3RowCache,
13972
14412
  Format2StorageCapabilityError: () => Db3StorageCapabilityError,
@@ -14057,8 +14497,10 @@ __export(browser_exports, {
14057
14497
  conditionHolds: () => conditionHolds,
14058
14498
  conditionProblem: () => conditionProblem,
14059
14499
  countViewRows: () => countViewRows,
14500
+ currentNameOf: () => currentNameOf,
14060
14501
  db3JsonText: () => db3JsonText,
14061
14502
  db3ViewTranslator: () => db3ViewTranslator,
14503
+ declareFieldNameTypes: () => declareFieldNameTypes,
14062
14504
  declaredTypeProblem: () => declaredTypeProblem,
14063
14505
  declineRecordLogIndex: () => declineRecordLogIndex,
14064
14506
  decodeRecordLogChunk: () => decodeRecordLogChunk,
@@ -14076,6 +14518,9 @@ __export(browser_exports, {
14076
14518
  estimateMaterializedBytes: () => estimateMaterializedBytes,
14077
14519
  explainViewRead: () => explainViewRead,
14078
14520
  features: () => features,
14521
+ fieldNameMapOf: () => fieldNameMapOf,
14522
+ fieldNameTypesOf: () => fieldNameTypesOf,
14523
+ fieldNamesOfClass: () => fieldNamesOfClass,
14079
14524
  fieldUniqueConstraintName: () => fieldUniqueConstraintName,
14080
14525
  findNearOperator: () => findNearOperator,
14081
14526
  findReservedFieldNameInToml: () => findReservedFieldNameInToml,
@@ -14098,6 +14543,7 @@ __export(browser_exports, {
14098
14543
  loadYjs: () => loadYjs,
14099
14544
  localConstraints: () => localConstraints,
14100
14545
  localIndexList: () => localIndexList,
14546
+ namesAnyModel: () => namesAnyModel,
14101
14547
  omitStringsetConstraints: () => omitStringsetConstraints,
14102
14548
  parseSnapshotChunkPath: () => parseSnapshotChunkPath,
14103
14549
  planRecordLogDelete: () => planRecordLogDelete,
@@ -14127,12 +14573,21 @@ __export(browser_exports, {
14127
14573
  requestStoragePersistence: () => requestStoragePersistence,
14128
14574
  resetJsBao: () => resetJsBao,
14129
14575
  resolveChunkOrdinal: () => resolveChunkOrdinal,
14576
+ resolveUpsertTarget: () => resolveUpsertTarget,
14130
14577
  schemaToToml: () => schemaToToml,
14131
14578
  serveRecordLogStoreHost: () => serveRecordLogStoreHost,
14132
14579
  storedConditionHolds: () => storedConditionHolds,
14580
+ storedNameOf: () => storedNameOf,
14133
14581
  syncInferredMeta: () => syncInferredMeta,
14134
14582
  syncModelMeta: () => syncModelMeta,
14135
14583
  syncRecordLogIndexes: () => syncRecordLogIndexes,
14584
+ toCurrentAggregateRows: () => toCurrentAggregateRows,
14585
+ toCurrentRow: () => toCurrentRow,
14586
+ toStoredAggregate: () => toStoredAggregate,
14587
+ toStoredData: () => toStoredData,
14588
+ toStoredFilter: () => toStoredFilter,
14589
+ toStoredIncludes: () => toStoredIncludes,
14590
+ toStoredKeys: () => toStoredKeys,
14136
14591
  traceViewRead: () => traceViewRead,
14137
14592
  uniqueIndexMapName: () => uniqueIndexMapName,
14138
14593
  uniqueStringsetMessage: () => uniqueStringsetMessage,
@@ -15094,8 +15549,8 @@ var CHUNK_PATH_OWN = /^([A-Za-z][A-Za-z0-9_]*)\/(\d+)$/;
15094
15549
  var CHUNK_PATH_SOURCED = /^(\d+)-([A-Za-z0-9_-]{1,64})\/([A-Za-z][A-Za-z0-9_]*)\/(\d+)$/;
15095
15550
  function parseSnapshotChunkPath(path) {
15096
15551
  if (!path || typeof path !== "string") return null;
15097
- const own2 = CHUNK_PATH_OWN.exec(path);
15098
- 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]) };
15099
15554
  const sourced = CHUNK_PATH_SOURCED.exec(path);
15100
15555
  if (!sourced) return null;
15101
15556
  return {
@@ -16400,7 +16855,7 @@ var IncludeSpecError = class _IncludeSpecError extends DocumentQueryError {
16400
16855
  Object.setPrototypeOf(this, _IncludeSpecError.prototype);
16401
16856
  }
16402
16857
  };
16403
- var isPlainObject4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
16858
+ var isPlainObject5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
16404
16859
  var identifierError = (value, label) => {
16405
16860
  try {
16406
16861
  assertValidIdentifier(value, label);
@@ -16411,7 +16866,7 @@ var identifierError = (value, label) => {
16411
16866
  };
16412
16867
  function validateIncludeSpec(spec, options = {}) {
16413
16868
  const strict = options.strict === true;
16414
- 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";
16415
16870
  const s = spec ?? {};
16416
16871
  if (!s.model || typeof s.model !== "string") return "include: 'model' is required";
16417
16872
  if (identifierError(s.model, "include model")) return `include: invalid model name '${s.model}'`;
@@ -16443,15 +16898,15 @@ function validateIncludeSpec(spec, options = {}) {
16443
16898
  if (s.limit !== void 0 && !(Number.isInteger(s.limit) && s.limit > 0)) {
16444
16899
  return "hasMany limit must be a positive integer";
16445
16900
  }
16446
- 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";
16447
16902
  if (s.projection !== void 0) {
16448
- if (!isPlainObject4(s.projection)) return "projection must be an object";
16903
+ if (!isPlainObject5(s.projection)) return "projection must be an object";
16449
16904
  for (const field of Object.keys(s.projection)) {
16450
16905
  if (identifierError(field, "include projection field")) return `invalid projection field '${field}'`;
16451
16906
  }
16452
16907
  }
16453
16908
  if (s.sort !== void 0) {
16454
- if (!isPlainObject4(s.sort)) return "sort must be an object";
16909
+ if (!isPlainObject5(s.sort)) return "sort must be an object";
16455
16910
  if (Object.values(s.sort).some((dir) => dir !== 1 && dir !== -1)) return "sort directions must be 1 or -1";
16456
16911
  }
16457
16912
  if (s.include !== void 0) {
@@ -18073,8 +18528,8 @@ function includedJsonBytes(records) {
18073
18528
  const recordBytes = (record) => {
18074
18529
  const known = sizes.get(record);
18075
18530
  if (known !== void 0) return known;
18076
- const { _related: related, ...own2 } = record;
18077
- let bytes2 = jsonBytes(own2);
18531
+ const { _related: related, ...own3 } = record;
18532
+ let bytes2 = jsonBytes(own3);
18078
18533
  if (related !== void 0 && related !== null && typeof related === "object" && !Array.isArray(related)) {
18079
18534
  let inner = 2;
18080
18535
  let entries = 0;
@@ -18178,16 +18633,16 @@ var RecordLogExplainRefusal = class _RecordLogExplainRefusal extends DocumentQue
18178
18633
  };
18179
18634
  var RECORD_LOG_VIEW_PRIMARY_KEY_INDEX = "sqlite_autoindex_record_log_view_1";
18180
18635
  var OPS = ["query", "count", "aggregate"];
18181
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
18636
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
18182
18637
  var invalid = (message, details = {}) => new RecordLogExplainRefusal("INVALID_ARGUMENT", 400, message, details);
18183
18638
  function checkedRequest(model, request) {
18184
- 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? }");
18185
18640
  const { op, filter, options, aggregate, index, setFields } = request;
18186
18641
  if (typeof model !== "string" || model.length === 0) throw invalid("explain takes a model name");
18187
18642
  if (!OPS.includes(op)) throw invalid("op must be query, count or aggregate", { op });
18188
- if (filter !== void 0 && !isObject(filter)) throw invalid("filter must be an object");
18189
- if (options !== void 0 && !isObject(options)) throw invalid("options must be an object");
18190
- 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");
18191
18646
  if (index !== void 0 && index !== null && (typeof index !== "string" || index.length === 0)) {
18192
18647
  throw invalid("index must be an index name or none", { index });
18193
18648
  }
@@ -18202,7 +18657,7 @@ function filterFields(filter, into) {
18202
18657
  for (const branch of filter) filterFields(branch, into);
18203
18658
  return;
18204
18659
  }
18205
- if (!isObject(filter)) return;
18660
+ if (!isObject2(filter)) return;
18206
18661
  for (const [key, value] of Object.entries(filter)) {
18207
18662
  if (key === "$search") continue;
18208
18663
  if (key.startsWith("$")) filterFields(value, into);
@@ -18212,12 +18667,12 @@ function filterFields(filter, into) {
18212
18667
  function aggregateOutputKeys(aggregate) {
18213
18668
  const keys = /* @__PURE__ */ new Set(["count"]);
18214
18669
  for (const operation of aggregate.operations ?? []) {
18215
- if (isObject(operation) && typeof operation.type === "string") {
18670
+ if (isObject2(operation) && typeof operation.type === "string") {
18216
18671
  keys.add(operation.type === "count" ? "count" : `${operation.type}_${String(operation.field)}`);
18217
18672
  }
18218
18673
  }
18219
18674
  (aggregate.groupBy ?? []).forEach((level, index) => {
18220
- if (!isObject(level) || typeof level.field !== "string") return;
18675
+ if (!isObject2(level) || typeof level.field !== "string") return;
18221
18676
  if (typeof level.period === "string") keys.add(`${level.field}_${level.period}`);
18222
18677
  if (typeof level.contains === "string") {
18223
18678
  keys.add(`ss_${level.field}_${index}`);
@@ -18234,14 +18689,14 @@ function fieldsOfRead(request) {
18234
18689
  filterFields(aggregate.filter, fields);
18235
18690
  for (const level of aggregate.groupBy ?? []) {
18236
18691
  if (typeof level === "string") fields.add(level);
18237
- 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);
18238
18693
  }
18239
- const sort = isObject(aggregate.sort) ? aggregate.sort.field : void 0;
18694
+ const sort = isObject2(aggregate.sort) ? aggregate.sort.field : void 0;
18240
18695
  if (typeof sort === "string" && !aggregateOutputKeys(aggregate).has(sort)) fields.add(sort);
18241
18696
  return fields;
18242
18697
  }
18243
18698
  filterFields(request.filter, fields);
18244
- if (request.op === "query" && isObject(request.options?.sort)) {
18699
+ if (request.op === "query" && isObject2(request.options?.sort)) {
18245
18700
  for (const field of Object.keys(request.options.sort)) fields.add(field);
18246
18701
  }
18247
18702
  return fields;
@@ -19294,13 +19749,13 @@ var RecordLogClient = class {
19294
19749
  * replacement every one whose last change came before it began. The
19295
19750
  * records a dropped attempt's load named are forgotten with it.
19296
19751
  */
19297
- settleReceipts(full, own2) {
19752
+ settleReceipts(full, own3) {
19298
19753
  const tables = this.tables;
19299
19754
  const state = tables.receipts?.() ?? null;
19300
19755
  if (!state || !tables.setReceipts) return;
19301
19756
  const since = full ? state.since : null;
19302
- const mine = own2 === void 0 ? void 0 : state.attempts.find((a) => a.attempt === own2);
19303
- 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;
19304
19759
  const attempts = state.attempts.filter((a) => !ended(a));
19305
19760
  const nextSince = full ? null : state.since;
19306
19761
  if (attempts.length === state.attempts.length && nextSince === state.since) return;
@@ -25423,10 +25878,10 @@ var OpfsEngine = class {
25423
25878
  report.skipped.push({ pool: directory, reason: "unreachable" });
25424
25879
  return;
25425
25880
  }
25426
- const keep = new Set(options.keep ?? []);
25881
+ const keep3 = new Set(options.keep ?? []);
25427
25882
  const wanted2 = [];
25428
25883
  for (const docId of stored) {
25429
- if (keep.has(docId)) report.skipped.push({ pool: docId, reason: "keep" });
25884
+ if (keep3.has(docId)) report.skipped.push({ pool: docId, reason: "keep" });
25430
25885
  else wanted2.push(docId);
25431
25886
  }
25432
25887
  await this.withExclusiveAll(
@@ -26522,8 +26977,8 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
26522
26977
  }
26523
26978
  this.mirror = { ...this.mirror, nextSeq, pending, lowestPending: lowest };
26524
26979
  if (confirmed) {
26525
- const own2 = this.mirror.writer;
26526
- 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));
26527
26982
  this.noteSettled(reply);
26528
26983
  }
26529
26984
  if (committed.length) {
@@ -26628,10 +27083,10 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
26628
27083
  }
26629
27084
  /** This writer's entries a reply settled: what waits on them resolves with their rows. */
26630
27085
  noteSettled(reply) {
26631
- const own2 = this.mirror.writer;
26632
- 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]));
26633
27088
  for (const { writer, seq } of reply.settled ?? []) {
26634
- if (writer !== own2) continue;
27089
+ if (writer !== own3) continue;
26635
27090
  this.unsettled.delete(seq);
26636
27091
  const settlement = { rows: rowsOf4.get(seq) ?? [] };
26637
27092
  this.settlements.set(seq, settlement);
@@ -27923,14 +28378,14 @@ var ACCESS_REFUSED_CODES = /* @__PURE__ */ new Set(["ACCESS_DENIED", "DOC_ACCESS
27923
28378
  function typeOfOpened(frame, docId) {
27924
28379
  if (!("db3Type" in frame) || frame.db3Type === void 0) return { type: { typed: "no" } };
27925
28380
  const type = frame.db3Type;
27926
- const isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
27927
- const models = isObject2(type) ? type.models : void 0;
27928
- const vectors = isObject2(type) ? type.vectors : void 0;
27929
- const enums = isObject2(type) ? type.enums : void 0;
27930
- const cleared = isObject2(type) ? type.cleared : 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;
27931
28386
  const isValues = (value) => Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string");
27932
- const isEncoding = (value) => isObject2(value) && typeof value.dims === "number" && Number.isInteger(value.dims) && value.dims >= 1 && isVectorElement(value.element);
27933
- 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))) && (cleared === void 0 || models !== void 0 && isObject2(cleared) && Object.values(cleared).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));
27934
28389
  if (!wellFormed) {
27935
28390
  Logger.warn(`[record-log] ${docId}: record.opened carried a db3Type this client cannot read; the type it holds is kept`);
27936
28391
  return {};
@@ -28293,10 +28748,10 @@ var RecordLogDocumentSession = class {
28293
28748
  this.store.resumeAcknowledgements?.();
28294
28749
  this.phase = "opening";
28295
28750
  const generation = this.generation;
28296
- const own2 = this.store.writer();
28751
+ const own3 = this.store.writer();
28297
28752
  const state = await this.store.storedState();
28298
28753
  if (generation !== this.generation) return;
28299
- 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 }));
28300
28755
  if (this.orphans.length) {
28301
28756
  Logger.info(`[record-log] ${this.docId}: draining ${this.orphans.length} earlier session writer(s) before opening`);
28302
28757
  }
@@ -29605,8 +30060,8 @@ var RecordLogDocumentSession = class {
29605
30060
  }
29606
30061
  /** This client's writer's entries the room acknowledged: confirmed, and their waiters resolve. */
29607
30062
  settleAcknowledged(acknowledged) {
29608
- const own2 = this.store.writer();
29609
- 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);
29610
30065
  if (!seqs.length) return;
29611
30066
  const touched = this.store.acknowledged(seqs);
29612
30067
  if (touched.length) this.host.notify(touched);
@@ -30282,7 +30737,7 @@ var VECTOR_QUANTIZERS = ["pq", "opq", "bq"];
30282
30737
  var isPositiveInteger = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1;
30283
30738
  function vectorOptionsProblem(options) {
30284
30739
  if (options === void 0) return null;
30285
- 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? }";
30286
30741
  const vector = options;
30287
30742
  const unknown = Object.keys(vector).find((key) => key !== "distance" && key !== "index");
30288
30743
  if (unknown !== void 0) return `vector options take distance and index, not ${JSON.stringify(unknown)}`;
@@ -30292,7 +30747,7 @@ function vectorOptionsProblem(options) {
30292
30747
  const index = vector.index;
30293
30748
  if (index === void 0 || index === "exact") return null;
30294
30749
  const shape = `vector.index must be "exact" or { mode: "ann", nbucket?, codesize?, quantizer? }`;
30295
- if (!isPlainObject5(index)) return shape;
30750
+ if (!isPlainObject6(index)) return shape;
30296
30751
  const ann = index;
30297
30752
  if (ann.mode !== "ann") return shape;
30298
30753
  const extra = Object.keys(ann).find((key) => !["mode", "nbucket", "codesize", "quantizer"].includes(key));
@@ -30305,7 +30760,7 @@ function vectorOptionsProblem(options) {
30305
30760
  }
30306
30761
  return null;
30307
30762
  }
30308
- var isPlainObject5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30763
+ var isPlainObject6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30309
30764
  function parseLocalRegistration(body, support) {
30310
30765
  if (!body || typeof body !== "object" || Array.isArray(body)) {
30311
30766
  throw invalid2("An index registration is an object: { model, field | fields, kind?, on?, unique?, name? }");
@@ -30326,7 +30781,7 @@ function parseLocalRegistration(body, support) {
30326
30781
  for (const options of ["text", "vector"]) {
30327
30782
  if (raw[options] === void 0) continue;
30328
30783
  if (kind !== options) throw invalid2(`${options} options apply to kind: "${options}" only`);
30329
- 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`);
30330
30785
  }
30331
30786
  if (kind === "members" && raw.fields !== void 0) {
30332
30787
  throw invalid2(`A member index is { model, field, kind: "members" }: it covers one field and takes no fields`);
@@ -32018,6 +32473,7 @@ init_BaseModel();
32018
32473
  init_ModelRegistry();
32019
32474
  init_uniqueIndex();
32020
32475
  init_vector();
32476
+ init_fieldNames();
32021
32477
  function defineModelSchema(input) {
32022
32478
  for (const [field, options] of Object.entries(input.fields)) {
32023
32479
  const problem = vectorFieldProblem(options);
@@ -32053,20 +32509,35 @@ function buildDefinedModelSchema(input) {
32053
32509
  if (schema.runtimeShape && schema.runtimeShape.class === modelClass) {
32054
32510
  return schema.runtimeShape;
32055
32511
  }
32512
+ const fieldNames = fieldNameMapOf(fields);
32056
32513
  const fieldsMap = /* @__PURE__ */ new Map();
32057
32514
  for (const [fieldName, fieldOptions] of Object.entries(fields)) {
32058
- 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
+ }
32059
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;
32060
32530
  const resolvedUniqueConstraints = resolveUniqueConstraints(
32061
32531
  name,
32062
32532
  fieldsMap,
32063
- options.uniqueConstraints
32533
+ shapeOptions.uniqueConstraints
32064
32534
  );
32065
32535
  schema.runtimeShape = {
32066
32536
  class: modelClass,
32067
- options,
32537
+ options: shapeOptions,
32068
32538
  fields: fieldsMap,
32069
- resolvedUniqueConstraints
32539
+ resolvedUniqueConstraints,
32540
+ fieldNames
32070
32541
  };
32071
32542
  return schema.runtimeShape;
32072
32543
  }
@@ -32317,6 +32788,7 @@ function schemaToToml(schema) {
32317
32788
  }
32318
32789
 
32319
32790
  // src/models/tomlLoader.ts
32791
+ init_fieldNames();
32320
32792
  var import_smol_toml2 = require("smol-toml");
32321
32793
  init_reservedFields();
32322
32794
  init_uniqueIndex();
@@ -32500,7 +32972,7 @@ var FIELD_KEYS = [
32500
32972
  { key: "description", prop: "description", kind: "string", storage: false, contexts: ioOnly },
32501
32973
  { key: "schema", prop: "schema", kind: "table", storage: false, contexts: ioOnly }
32502
32974
  ];
32503
- var own = (record, key) => Object.prototype.hasOwnProperty.call(record, key);
32975
+ var own2 = (record, key) => Object.prototype.hasOwnProperty.call(record, key);
32504
32976
  var isTable = (value) => value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
32505
32977
  var positiveInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
32506
32978
  function rowFor(key) {
@@ -32561,7 +33033,7 @@ function judge(row, value, decl, spec, table) {
32561
33033
  switch (row.kind) {
32562
33034
  case "flag":
32563
33035
  if (row.flagTier === "always" && typeof value !== "boolean") return { problem: { code: "bad-boolean", key: row.key } };
32564
- 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)) {
32565
33037
  return { problem: { code: "enforce-without-enum", key: "enforce_enum" } };
32566
33038
  }
32567
33039
  if (row.needs === "deprecated" && value === true && table.deprecated !== true) {
@@ -32614,7 +33086,7 @@ function readFieldTable(raw, context) {
32614
33086
  else if (entry !== "allowed") problems.push({ code: "unknown-key", key, allowed: [...spec.keys] });
32615
33087
  }
32616
33088
  const type = table.type;
32617
- if (typeof type === "string" && spec.refusedTypes && own(spec.refusedTypes, type)) {
33089
+ if (typeof type === "string" && spec.refusedTypes && own2(spec.refusedTypes, type)) {
32618
33090
  problems.push({ code: "refused-type", type, reason: spec.refusedTypes[type] });
32619
33091
  return { decl: null, problems };
32620
33092
  }
@@ -32623,7 +33095,7 @@ function readFieldTable(raw, context) {
32623
33095
  return { decl: null, problems };
32624
33096
  }
32625
33097
  const decl = { type };
32626
- 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);
32627
33099
  const ordered = [...rows.filter((row) => row.kind !== "typed-default"), ...rows.filter((row) => row.kind === "typed-default")];
32628
33100
  for (const row of ordered) {
32629
33101
  const judged = judge(row, table[row.key], decl, spec, table);
@@ -33040,6 +33512,12 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
33040
33512
  })
33041
33513
  );
33042
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
+ }
33043
33521
  return schemas;
33044
33522
  }
33045
33523
  function findReservedFieldNameInToml(tomlString) {
@@ -33727,3 +34205,4 @@ init_documentTypes();
33727
34205
  init_jsonFields();
33728
34206
  init_vector();
33729
34207
  init_yjsRuntime();
34208
+ init_fieldNames();