js-bao 0.12.0-alpha.15 → 0.12.0-alpha.16

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
@@ -279,7 +279,7 @@ var init_StringSet = __esm({
279
279
  });
280
280
 
281
281
  // src/types/documentTypes.ts
282
- var DocumentClosedError, DocumentFormatUnsupportedError, ModelRegistrationTimeoutError, DocumentResolutionError;
282
+ var DocumentClosedError, DocumentWriteAccessDeniedError, DocumentFormatUnsupportedError, ModelRegistrationTimeoutError, DocumentResolutionError;
283
283
  var init_documentTypes = __esm({
284
284
  "src/types/documentTypes.ts"() {
285
285
  "use strict";
@@ -290,6 +290,19 @@ var init_documentTypes = __esm({
290
290
  this.name = "DocumentClosedError";
291
291
  }
292
292
  };
293
+ DocumentWriteAccessDeniedError = class _DocumentWriteAccessDeniedError extends Error {
294
+ /**
295
+ * @param documentId - The document the write was to.
296
+ * @param message - What was refused, naming the read-only permission.
297
+ */
298
+ constructor(documentId, message) {
299
+ super(message);
300
+ this.documentId = documentId;
301
+ this.name = "DocumentWriteAccessDeniedError";
302
+ Object.setPrototypeOf(this, _DocumentWriteAccessDeniedError.prototype);
303
+ }
304
+ code = "WRITE_ACCESS_DENIED";
305
+ };
293
306
  DocumentFormatUnsupportedError = class extends Error {
294
307
  constructor(documentId, documentFormat) {
295
308
  super(
@@ -2053,7 +2066,7 @@ var init_DocumentQueryTranslator = __esm({
2053
2066
  });
2054
2067
 
2055
2068
  // src/models/db3QueryScope.ts
2056
- var Db3QueryScopeError, Db3NotResidentError;
2069
+ var Db3QueryScopeError, Db3NotResidentError, Db3ModelOnOtherClientError;
2057
2070
  var init_db3QueryScope = __esm({
2058
2071
  "src/models/db3QueryScope.ts"() {
2059
2072
  "use strict";
@@ -2083,6 +2096,19 @@ var init_db3QueryScope = __esm({
2083
2096
  /** Stable across builds, so an app can branch on it rather than on text. */
2084
2097
  code = "DB3_NOT_RESIDENT";
2085
2098
  };
2099
+ Db3ModelOnOtherClientError = class _Db3ModelOnOtherClientError extends Error {
2100
+ constructor(modelName, documentId) {
2101
+ super(
2102
+ `[${modelName}] cannot save into the db3 '${documentId}': this model class is bound to another live client in this process, which holds no copy of that db3, so the save would go there. A model class binds to the first client that uses it. Give each client its own model classes, or write through client.db3.records('${documentId}').`
2103
+ );
2104
+ this.modelName = modelName;
2105
+ this.documentId = documentId;
2106
+ this.name = "Db3ModelOnOtherClientError";
2107
+ Object.setPrototypeOf(this, _Db3ModelOnOtherClientError.prototype);
2108
+ }
2109
+ /** Stable across builds, so an app can branch on it rather than on text. */
2110
+ code = "DB3_MODEL_ON_OTHER_CLIENT";
2111
+ };
2086
2112
  }
2087
2113
  });
2088
2114
 
@@ -3188,8 +3214,8 @@ var init_logger = __esm({
3188
3214
 
3189
3215
  // src/models/vectorFields.ts
3190
3216
  function vectorEncodingFor(declared, model, field, options) {
3191
- const has = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
3192
- if (declared && has(declared, model) && has(declared[model], field)) return declared[model][field];
3217
+ const has2 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
3218
+ if (declared && has2(declared, model) && has2(declared[model], field)) return declared[model][field];
3193
3219
  return vectorEncodingOf(options);
3194
3220
  }
3195
3221
  function readVectorValue(model, field, value, encoding) {
@@ -4276,6 +4302,14 @@ var init_reservedFieldNames = __esm({
4276
4302
  breaks: ["swift"],
4277
4303
  reason: "the generated struct's coding keys on the Swift client"
4278
4304
  },
4305
+ UniqueConstraint: {
4306
+ breaks: ["swift"],
4307
+ reason: "the generated struct's upsert constraint names on the Swift client"
4308
+ },
4309
+ UniqueField: {
4310
+ breaks: ["swift"],
4311
+ reason: "the generated struct's upsert field names on the Swift client"
4312
+ },
4279
4313
  applyAutoStampsForSave: {
4280
4314
  breaks: ["js"],
4281
4315
  reason: "a record method on the JavaScript client",
@@ -6270,7 +6304,7 @@ var init_types = __esm({
6270
6304
  RECORD_LOG_UP_BATCH_MAX = 200;
6271
6305
  RECORD_LOG_FRAME_ENTRIES_MAX = 64;
6272
6306
  RECORD_LOG_FIRST_EPOCH = 1;
6273
- RECORD_LOG_WIRE_VERSION = 3;
6307
+ RECORD_LOG_WIRE_VERSION = 4;
6274
6308
  RecordLogStaleReceiptError = class _RecordLogStaleReceiptError extends Error {
6275
6309
  /**
6276
6310
  * @param attempt - The attempt the command carried.
@@ -6332,6 +6366,9 @@ function assertRecordLogWriteAllowed(permission, docId, write, report) {
6332
6366
  report({ documentId: docId, model: write.model, recordId: write.recordId, error, writes: [write] });
6333
6367
  throw error;
6334
6368
  }
6369
+ function recordLogReadOnlyRefusal(docId, message) {
6370
+ return new RecordLogWriteRefusedError("WRITE_ACCESS_DENIED", docId, message, { scope: "local" });
6371
+ }
6335
6372
  function travels(field) {
6336
6373
  return field !== "id" && field !== "type" && !field.startsWith("_meta_");
6337
6374
  }
@@ -6734,6 +6771,11 @@ function isRepresentableDate(value) {
6734
6771
  const roundTrip = /* @__PURE__ */ new Date(`${year}-${month}-${day}T00:00:00Z`);
6735
6772
  return roundTrip.getUTCFullYear() === Number(year) && roundTrip.getUTCMonth() + 1 === Number(month) && roundTrip.getUTCDate() === Number(day);
6736
6773
  }
6774
+ function enumRefusalMessage(model, id, field, values, value) {
6775
+ const listed = values.length > ENUM_VALUES_SHOWN ? `${values.slice(0, ENUM_VALUES_SHOWN).join(", ")} \u2026 and ${values.length - ENUM_VALUES_SHOWN} more` : values.join(", ");
6776
+ const written = typeof value === "string" && value.length > WRITTEN_QUOTED_MAX ? `a string of ${value.length} characters` : JSON.stringify(value) ?? String(value);
6777
+ return `${model} id=${id}: field "${field}" takes one of ${listed}; the write is ${written}`;
6778
+ }
6737
6779
  function receivedKind(value) {
6738
6780
  if (Array.isArray(value)) return "an array";
6739
6781
  return typeof value;
@@ -6741,10 +6783,10 @@ function receivedKind(value) {
6741
6783
  function declaredTypeProblem(mutations, type) {
6742
6784
  const vectors = type.vectors;
6743
6785
  if (vectors) {
6744
- const has = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
6786
+ const has2 = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
6745
6787
  const vector = vectorMutationsProblem(
6746
6788
  mutations,
6747
- (model, field) => has(vectors, model) && has(vectors[model], field) ? vectors[model][field] : void 0
6789
+ (model, field) => has2(vectors, model) && has2(vectors[model], field) ? vectors[model][field] : void 0
6748
6790
  );
6749
6791
  if (vector) return { code: "DB3_VECTOR_INVALID", message: vector };
6750
6792
  }
@@ -6779,9 +6821,34 @@ function declaredTypeProblem(mutations, type) {
6779
6821
  const declared = declaredOf(field);
6780
6822
  if (declared !== void 0 && declared !== "stringset" && declared !== "vector") return refuse(field, declared, "a string-set change");
6781
6823
  }
6824
+ const outside = type.enums ? enumMutationProblem(where2, m, type.enums) : null;
6825
+ if (outside) return outside;
6826
+ }
6827
+ return null;
6828
+ }
6829
+ function enumMutationProblem(where2, m, enums) {
6830
+ if (m.kind === "increment" || m.kind === "delete" || !m.fields || !has(enums, m.model)) return null;
6831
+ const enforced = enums[m.model];
6832
+ for (const field of Object.keys(enforced)) {
6833
+ if (!has(m.fields, field)) continue;
6834
+ const value = m.fields[field];
6835
+ const values = enforced[field];
6836
+ if (typeof value !== "string" || values.indexOf(value) >= 0) continue;
6837
+ return { code: "DB3_VALUE_NOT_IN_ENUM", message: `${where2}: ${enumRefusalMessage(m.model, m.id, field, values, value)}` };
6782
6838
  }
6783
6839
  return null;
6784
6840
  }
6841
+ function assertRecordLogDeclaredEnums(documentId, mutations, enums, report) {
6842
+ if (!enums || !mutations.length) return;
6843
+ for (const [at, m] of mutations.entries()) {
6844
+ const problem = enumMutationProblem(at === 0 ? "m" : `also[${at - 1}]`, m, enums);
6845
+ if (!problem) continue;
6846
+ const error = new RecordLogWriteRefusedError(problem.code, documentId, problem.message, { scope: "local" });
6847
+ const [first, ...rest] = mutations;
6848
+ report?.({ documentId, model: first.model, recordId: first.id, error, writes: refusedWritesOf({ seq: 0, m: first, also: rest }) });
6849
+ throw error;
6850
+ }
6851
+ }
6785
6852
  function assertRecordLogDeclaredTypes(documentId, mutations, type, report) {
6786
6853
  if (!type || !mutations.length) return;
6787
6854
  const problem = declaredTypeProblem(mutations, type);
@@ -6791,7 +6858,7 @@ function assertRecordLogDeclaredTypes(documentId, mutations, type, report) {
6791
6858
  report?.({ documentId, model: first.model, recordId: first.id, error, writes: refusedWritesOf({ seq: 0, m: first, also: rest }) });
6792
6859
  throw error;
6793
6860
  }
6794
- var SCALAR_KINDS, ISO_DATE_STRING;
6861
+ var SCALAR_KINDS, ISO_DATE_STRING, ENUM_VALUES_SHOWN, WRITTEN_QUOTED_MAX, has;
6795
6862
  var init_declared_types = __esm({
6796
6863
  "src/record-log-client/declared-types.ts"() {
6797
6864
  "use strict";
@@ -6799,6 +6866,9 @@ var init_declared_types = __esm({
6799
6866
  init_types();
6800
6867
  SCALAR_KINDS = /* @__PURE__ */ new Set(["string", "number", "boolean", "date", "id"]);
6801
6868
  ISO_DATE_STRING = /^(\d{4})-(\d{2})-(\d{2})(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
6869
+ ENUM_VALUES_SHOWN = 20;
6870
+ WRITTEN_QUOTED_MAX = 64;
6871
+ has = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
6802
6872
  }
6803
6873
  });
6804
6874
 
@@ -8496,6 +8566,16 @@ function reindexFailure(modelConstructor, modelName, recordId, docId, error) {
8496
8566
  function heldMutationsOf(w) {
8497
8567
  return [w.held.mutation, w.held.increment].filter((m) => m !== void 0);
8498
8568
  }
8569
+ function db3HeldOnlyByAnotherContext(ormContext, docId, modelClass) {
8570
+ if (ormContext.getRecordLogStore(docId) !== null) return false;
8571
+ for (const other of liveOrmContexts) {
8572
+ if (other === ormContext || other.destroyed) continue;
8573
+ if (other.getRecordLogStore(docId) === null) continue;
8574
+ const handed = other.modelRegistry?.getActiveModels();
8575
+ if (handed && [...handed.values()].includes(modelClass)) return true;
8576
+ }
8577
+ return false;
8578
+ }
8499
8579
  function stagedForRead(ormContext, store, model, id) {
8500
8580
  const unbound = unboundRecordLogTransaction;
8501
8581
  const group = activeRecordLogTransactions.get(ormContext) ?? (unbound && unbound.owner === ormContext ? unbound : null);
@@ -8511,7 +8591,7 @@ function refusalRecords(error) {
8511
8591
  function declaredTypeOf(store) {
8512
8592
  const models = store.declaredTypes();
8513
8593
  const name = store.marks().db3Type?.name;
8514
- return models && name ? { name, models, vectors: store.declaredVectors() } : null;
8594
+ return models && name ? { name, models, vectors: store.declaredVectors(), enums: store.declaredEnums() } : null;
8515
8595
  }
8516
8596
  function encodeVectorFields(data, fields, declared, model, id) {
8517
8597
  for (const [field, options] of fields) {
@@ -10853,6 +10933,9 @@ var init_BaseModel = __esm({
10853
10933
  if (source.value) {
10854
10934
  targetDocId = source.value;
10855
10935
  targetSource = source.name;
10936
+ if (db3HeldOnlyByAnotherContext(saveContext, targetDocId, modelConstructor)) {
10937
+ throw new Db3ModelOnOtherClientError(modelName, targetDocId);
10938
+ }
10856
10939
  const documentInfo2 = this.constructor.connectedDocuments.get(targetDocId);
10857
10940
  if (!documentInfo2) {
10858
10941
  const db3Named = source.name === "db3" || (source.name === "modelDefault" || source.name === "globalDefault") && saveContext.db3Defaults.has(targetDocId);
@@ -10885,9 +10968,8 @@ var init_BaseModel = __esm({
10885
10968
  );
10886
10969
  }
10887
10970
  if (permissionHint === "read" && !options?.forceWrite) {
10888
- throw new Error(
10889
- `[${modelName}] Cannot save to document '${targetDocId}' with read-only permission. Use forceWrite option to override.`
10890
- );
10971
+ const message = `[${modelName}] Cannot save to document '${targetDocId}' with read-only permission. Use forceWrite option to override.`;
10972
+ throw targetIsDb3 ? recordLogReadOnlyRefusal(targetDocId, message) : new DocumentWriteAccessDeniedError(targetDocId, message);
10891
10973
  }
10892
10974
  if (!targetYDoc && !targetIsDb3) {
10893
10975
  throw new Error(
@@ -10947,7 +11029,8 @@ var init_BaseModel = __esm({
10947
11029
  (event) => saveContext.reportRecordLogWriteRefused(event)
10948
11030
  );
10949
11031
  if (recordLogStore.marks().permission === "read") {
10950
- throw new Error(
11032
+ throw recordLogReadOnlyRefusal(
11033
+ targetDocId,
10951
11034
  `[${modelName}] Cannot save to document '${targetDocId}' with read-only permission.`
10952
11035
  );
10953
11036
  }
@@ -11653,7 +11736,7 @@ var init_BaseModel = __esm({
11653
11736
  const write = { model: modelName, recordId: id, kind: "increment", fields: { ...fields }, seq: 0 };
11654
11737
  assertRecordLogWriteAllowed(store.marks().permission, docId, write, report);
11655
11738
  if (store.marks().permission === "read" || modelConstructor.connectedDocuments.get(docId)?.permissionHint === "read") {
11656
- throw new Error(`[${modelName}] Cannot increment in document '${docId}' with read-only permission.`);
11739
+ throw recordLogReadOnlyRefusal(docId, `[${modelName}] Cannot increment in document '${docId}' with read-only permission.`);
11657
11740
  }
11658
11741
  const mutation = planRecordLogIncrement(modelName, id, fields, options.condition);
11659
11742
  const transaction = recordLogTransactionOf(ormContext);
@@ -11839,7 +11922,8 @@ var init_BaseModel = __esm({
11839
11922
  (event) => resolveOrmContext(modelConstructor).reportRecordLogWriteRefused(event)
11840
11923
  );
11841
11924
  if (documentInfo.permissionHint === "read" || recordLogStore.marks().permission === "read") {
11842
- throw new Error(
11925
+ throw recordLogReadOnlyRefusal(
11926
+ docId,
11843
11927
  `[${modelName}] Cannot delete from document '${docId}' with read-only permission.`
11844
11928
  );
11845
11929
  }
@@ -13491,12 +13575,14 @@ __export(browser_exports, {
13491
13575
  DatabaseFactory: () => BrowserDatabaseFactory,
13492
13576
  Db3DriftExceededError: () => Db3DriftExceededError,
13493
13577
  Db3IndexNotOnDeviceError: () => Db3IndexNotOnDeviceError,
13578
+ Db3ModelOnOtherClientError: () => Db3ModelOnOtherClientError,
13494
13579
  Db3NotResidentError: () => Db3NotResidentError,
13495
13580
  Db3QueryScopeError: () => Db3QueryScopeError,
13496
13581
  Db3RowCache: () => Db3RowCache,
13497
13582
  Db3StorageCapabilityError: () => Db3StorageCapabilityError,
13498
13583
  Db3StoreOutdatedError: () => Db3StoreOutdatedError,
13499
13584
  DocumentClosedError: () => DocumentClosedError,
13585
+ DocumentWriteAccessDeniedError: () => DocumentWriteAccessDeniedError,
13500
13586
  FORMAT2_MANIFEST_VERSION: () => FORMAT2_MANIFEST_VERSION,
13501
13587
  FORMAT2_MIN_MANIFEST_VERSION: () => FORMAT2_MIN_MANIFEST_VERSION,
13502
13588
  Format2QueryScopeError: () => Db3QueryScopeError,
@@ -13569,6 +13655,7 @@ __export(browser_exports, {
13569
13655
  aggregateViewRows: () => aggregateViewRows,
13570
13656
  applyChange: () => applyChange,
13571
13657
  applyGuess: () => applyGuess,
13658
+ assertRecordLogDeclaredEnums: () => assertRecordLogDeclaredEnums,
13572
13659
  assertRecordLogDeclaredTypes: () => assertRecordLogDeclaredTypes,
13573
13660
  assertRecordLogEntry: () => assertRecordLogEntry,
13574
13661
  assertRecordLogRecordInput: () => assertRecordLogRecordInput,
@@ -19949,11 +20036,11 @@ var SqlRecordLogTables = class {
19949
20036
  this.ensureState();
19950
20037
  this.sql.exec(`UPDATE record_log_state SET permission = ? WHERE doc_id = ?`, permission, this.docId);
19951
20038
  }
19952
- /** The typed mark, the type and its held declarations and vector fields. */
20039
+ /** The typed mark, the type and its held declarations, vector fields and enforced enums. */
19953
20040
  typeState() {
19954
20041
  const state = this.state();
19955
20042
  const typed = state?.typed === "yes" ? "yes" : state?.typed === "no" ? "no" : "unknown";
19956
- const none = { declarations: null, vectors: null, vectorsKnown: true };
20043
+ const none = { declarations: null, vectors: null, vectorsKnown: true, enums: null, enumsKnown: true };
19957
20044
  if (typed !== "yes" || !state?.db3_type) return { typed, db3Type: null, ...none };
19958
20045
  try {
19959
20046
  const held = JSON.parse(String(state.db3_type));
@@ -19964,7 +20051,10 @@ var SqlRecordLogTables = class {
19964
20051
  declarations,
19965
20052
  vectors: held.vectors ?? null,
19966
20053
  // An entry with declarations and no `vectors` key was written before vector fields (#5225).
19967
- vectorsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held, "vectors")
20054
+ vectorsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held, "vectors"),
20055
+ enums: held.enums ?? null,
20056
+ // An entry with declarations and no `enums` key was written before enforced enums (#5897).
20057
+ enumsKnown: declarations === null || Object.prototype.hasOwnProperty.call(held, "enums")
19968
20058
  };
19969
20059
  } catch {
19970
20060
  return { typed, db3Type: null, ...none };
@@ -19985,9 +20075,16 @@ var SqlRecordLogTables = class {
19985
20075
  const keepsHeld = models === void 0 && hash !== null && held.db3Type?.hash === hash;
19986
20076
  const kept = models ?? (keepsHeld ? held.declarations : null);
19987
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;
19988
20079
  this.sql.exec(
19989
20080
  `UPDATE record_log_state SET typed = 'yes', db3_type = ? WHERE doc_id = ?`,
19990
- JSON.stringify({ name, hash: kept ? hash : null, models: kept, ...kept && vectors !== void 0 ? { vectors } : {} }),
20081
+ JSON.stringify({
20082
+ name,
20083
+ hash: kept ? hash : null,
20084
+ models: kept,
20085
+ ...kept && vectors !== void 0 ? { vectors } : {},
20086
+ ...kept && enums !== void 0 ? { enums } : {}
20087
+ }),
19991
20088
  this.docId
19992
20089
  );
19993
20090
  }
@@ -20991,8 +21088,8 @@ var RecordLogStore = class {
20991
21088
  this.sql.transaction(() => {
20992
21089
  for (const statement of recordLogClientDDL()) this.sql.exec(statement);
20993
21090
  for (const { table, column, add } of RECORD_LOG_CLIENT_ADDED_COLUMNS) {
20994
- const has = rowsOf3(this.sql, `SELECT 1 FROM pragma_table_info(?) WHERE name = ?`, table, column).length > 0;
20995
- if (!has) this.sql.exec(add);
21091
+ const has2 = rowsOf3(this.sql, `SELECT 1 FROM pragma_table_info(?) WHERE name = ?`, table, column).length > 0;
21092
+ if (!has2) this.sql.exec(add);
20996
21093
  }
20997
21094
  if (this.indexSupport?.vector === false) dropVectorTriggers(this.sql);
20998
21095
  });
@@ -26455,6 +26552,15 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
26455
26552
  declaredVectors() {
26456
26553
  return this.mirror.typed === "yes" ? this.mirror.vectors ?? null : null;
26457
26554
  }
26555
+ /**
26556
+ * The enforced enums of the db3's type the room sent beside its
26557
+ * declarations (#5897), per model each enforced field's values; `null`
26558
+ * while the db3 is not known to be typed, its type enforces none, or none
26559
+ * were received yet.
26560
+ */
26561
+ declaredEnums() {
26562
+ return this.mirror.typed === "yes" ? this.mirror.enums ?? null : null;
26563
+ }
26458
26564
  /**
26459
26565
  * Whether the local pre-check should hold a save to a unique constraint:
26460
26566
  * every constraint is checked unless the room has said it keeps it out of
@@ -26529,6 +26635,7 @@ init_documentTypes();
26529
26635
  init_logger();
26530
26636
  init_guess();
26531
26637
  init_types();
26638
+ init_declared_types();
26532
26639
  init_vectorFields();
26533
26640
  init_vector();
26534
26641
  init_write();
@@ -26773,7 +26880,7 @@ var RecordLogRecords = class {
26773
26880
  report
26774
26881
  );
26775
26882
  if (this.deps.permission() === "read" || store.marks().permission === "read") {
26776
- throw new Error(`[record-log] Cannot save ${model} ${id} to document '${docId}' with read-only permission.`);
26883
+ throw recordLogReadOnlyRefusal(docId, `[record-log] Cannot save ${model} ${id} to document '${docId}' with read-only permission.`);
26777
26884
  }
26778
26885
  const { condition, ifNotExists, upsertOn } = options;
26779
26886
  if (upsertOn !== void 0 && kind !== "put") {
@@ -26795,6 +26902,7 @@ var RecordLogRecords = class {
26795
26902
  const planned = kind === "delete" ? planRecordLogDelete(model, id, condition) : planRecordLogRecordWrite({ model, id, kind, existing, data: fields, condition, ifNotExists });
26796
26903
  const mutation = kind === "delete" && ifNotExists !== void 0 ? { ...planned, ifNotExists } : planned;
26797
26904
  assertRecordLogEntry(docId, [mutation], report, upsertOn !== void 0 ? { upsertOn } : {});
26905
+ assertRecordLogDeclaredEnums(docId, [mutation], store.declaredEnums(), report);
26798
26906
  guarded = mutation.condition !== void 0 || mutation.ifNotExists !== void 0;
26799
26907
  upsertValue = upsertOn !== void 0 ? mutation.fields?.[upsertOn] : void 0;
26800
26908
  let resolved;
@@ -27101,8 +27209,10 @@ function typeOfOpened(frame, docId) {
27101
27209
  const isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
27102
27210
  const models = isObject2(type) ? type.models : void 0;
27103
27211
  const vectors = isObject2(type) ? type.vectors : void 0;
27212
+ const enums = isObject2(type) ? type.enums : void 0;
27213
+ const isValues = (value) => Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string");
27104
27214
  const isEncoding = (value) => isObject2(value) && typeof value.dims === "number" && Number.isInteger(value.dims) && value.dims >= 1 && isVectorElement(value.element);
27105
- 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)));
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)));
27106
27216
  if (!wellFormed) {
27107
27217
  Logger.warn(`[record-log] ${docId}: record.opened carried a db3Type this client cannot read; the type it holds is kept`);
27108
27218
  return {};
@@ -27114,7 +27224,8 @@ function typeOfOpened(frame, docId) {
27114
27224
  name: type.name,
27115
27225
  hash: type.hash,
27116
27226
  ...models !== void 0 ? { models } : {},
27117
- ...vectors !== void 0 ? { vectors } : {}
27227
+ ...vectors !== void 0 ? { vectors } : {},
27228
+ ...enums !== void 0 ? { enums } : {}
27118
27229
  }
27119
27230
  }
27120
27231
  };
@@ -27140,7 +27251,8 @@ var HAND_BACK_CODES = /* @__PURE__ */ new Set([
27140
27251
  "DB3_RECORD_NOT_FOUND",
27141
27252
  "DB3_TRIGGER_REFUSED",
27142
27253
  "DB3_MODEL_NOT_DECLARED",
27143
- "DB3_RESOURCE_HELD"
27254
+ "DB3_RESOURCE_HELD",
27255
+ "DB3_VALUE_NOT_IN_ENUM"
27144
27256
  ]);
27145
27257
  var RECORD_LOG_DRAIN_WAIT_MS = 15e3;
27146
27258
  var RECORD_LOG_RESULT_GAP_MS = 2e3;
@@ -27519,8 +27631,9 @@ var RecordLogDocumentSession = class {
27519
27631
  ...unfinished ? { unfinished } : {},
27520
27632
  // The type revision whose declarations this device holds: the room
27521
27633
  // sends them again only for another one (#5020). Declarations held
27522
- // without their vector fields (written before #5225) are asked for again.
27523
- ...typed === "yes" && marks.db3Type?.hash && marks.vectorsKnown !== false ? { db3TypeHash: marks.db3Type.hash } : {}
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 } : {}
27524
27637
  });
27525
27638
  if (!sendAhead) return;
27526
27639
  const ahead = { declarations: null, refused: false, seqs: [] };
@@ -31471,7 +31584,7 @@ var FIELD_CONTEXTS = {
31471
31584
  model: {
31472
31585
  values: "as-written",
31473
31586
  types: FIELD_TYPES,
31474
- keys: ["type", "indexed", "unique", "required", "auto_assign", "auto_stamp", "max_length", "max_count", "default", "enum", "dims", "element"]
31587
+ keys: ["type", "indexed", "unique", "required", "auto_assign", "auto_stamp", "max_length", "max_count", "default", "enum", "enforce_enum", "dims", "element"]
31475
31588
  },
31476
31589
  property: {
31477
31590
  values: "checked",
@@ -31578,6 +31691,17 @@ var FIELD_KEYS = [
31578
31691
  types: ["string"],
31579
31692
  typesTier: "always"
31580
31693
  },
31694
+ {
31695
+ key: "enforce_enum",
31696
+ prop: "enforceEnum",
31697
+ kind: "flag",
31698
+ storage: false,
31699
+ contexts: { model: "allowed", property: "unknown", io: "unknown" },
31700
+ types: ["string"],
31701
+ typesTier: "always",
31702
+ flagTier: "always",
31703
+ needs: "enum"
31704
+ },
31581
31705
  {
31582
31706
  key: "dims",
31583
31707
  prop: "dims",
@@ -31671,7 +31795,7 @@ function typedDefault(decl, value) {
31671
31795
  return Array.isArray(value) ? { value: [...value] } : { problem: "default must be an array for an array field" };
31672
31796
  }
31673
31797
  }
31674
- function judge(row, value, decl, spec) {
31798
+ function judge(row, value, decl, spec, table) {
31675
31799
  const checked = spec.values === "checked";
31676
31800
  if (row.types && row.typesTier && (checked || row.typesTier === "always") && row.types.indexOf(decl.type) < 0) {
31677
31801
  const types = row.types.filter((type) => spec.types.indexOf(type) >= 0);
@@ -31679,7 +31803,11 @@ function judge(row, value, decl, spec) {
31679
31803
  }
31680
31804
  switch (row.kind) {
31681
31805
  case "flag":
31682
- if (!checked) return { value: value === true ? true : void 0 };
31806
+ 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)) {
31808
+ return { problem: { code: "enforce-without-enum", key: "enforce_enum" } };
31809
+ }
31810
+ if (row.flagTier === "always" || !checked) return { value: value === true ? true : void 0 };
31683
31811
  return typeof value === "boolean" ? { value } : { problem: { code: "bad-boolean", key: row.key } };
31684
31812
  case "literal": {
31685
31813
  const literals = row.literals ?? [];
@@ -31735,27 +31863,62 @@ function readFieldTable(raw, context) {
31735
31863
  const rows = FIELD_KEYS.filter((row) => row.kind !== "type" && row.contexts[context] === "allowed" && own(table, row.key) && table[row.key] !== void 0);
31736
31864
  const ordered = [...rows.filter((row) => row.kind !== "typed-default"), ...rows.filter((row) => row.kind === "typed-default")];
31737
31865
  for (const row of ordered) {
31738
- const judged = judge(row, table[row.key], decl, spec);
31866
+ const judged = judge(row, table[row.key], decl, spec, table);
31739
31867
  if ("problem" in judged) problems.push(judged.problem);
31740
31868
  else if (judged.value !== void 0) decl[row.prop] = judged.value;
31741
31869
  }
31742
31870
  return { decl, problems };
31743
31871
  }
31872
+ function fieldProblemMessage(problem) {
31873
+ switch (problem.code) {
31874
+ case "unknown-key":
31875
+ return `unknown key "${problem.key}". Allowed: ${problem.allowed.join(", ")}`;
31876
+ case "refused-key":
31877
+ case "refused-type":
31878
+ case "bad-default":
31879
+ return problem.reason;
31880
+ case "unknown-type":
31881
+ return `type must be one of ${problem.allowed.join(", ")}`;
31882
+ case "not-for-type":
31883
+ return `${problem.key} is only valid on a ${problem.types.join(" or ")} field, not ${problem.type}`;
31884
+ case "bad-literal":
31885
+ return `${problem.key} must be one of ${problem.literals.join(", ")}${problem.note ? ` ${problem.note}` : ""}`;
31886
+ case "bad-boolean":
31887
+ return `${problem.key} must be true or false`;
31888
+ case "bad-positive-integer":
31889
+ return `${problem.key} must be a positive integer`;
31890
+ case "bad-number":
31891
+ return `${problem.key} must be a number`;
31892
+ case "bad-string":
31893
+ return `${problem.key} must be a string`;
31894
+ case "bad-table":
31895
+ return `${problem.key} must be a table`;
31896
+ case "bad-items":
31897
+ return 'items names the item type as a string (items = "string", or a shared shape); write an item table as item';
31898
+ case "enum-not-list":
31899
+ case "enum-member-not-string":
31900
+ return "enum must be a non-empty array of strings";
31901
+ case "enum-repeats":
31902
+ return "enum repeats a value";
31903
+ case "enforce-without-enum":
31904
+ return "enforce_enum needs an enum to enforce";
31905
+ }
31906
+ }
31744
31907
 
31745
31908
  // src/models/sharedEnums.ts
31746
31909
  var import_smol_toml = require("smol-toml");
31747
31910
  var isTable2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
31748
31911
  var fail = (message) => ({ ok: false, message });
31749
31912
  function expandSharedEnumField(raw, resolve) {
31750
- const has = (key) => isTable2(raw) && Object.prototype.hasOwnProperty.call(raw, key);
31751
- if (!has("ref")) return { ok: true, field: raw };
31752
- const beside = ["type", "enum"].filter(has);
31913
+ const has2 = (key) => isTable2(raw) && Object.prototype.hasOwnProperty.call(raw, key);
31914
+ if (!has2("ref")) return { ok: true, field: raw };
31915
+ const beside = ["type", "enum"].filter(has2);
31753
31916
  const [it, them] = beside.length > 1 ? ["both", "them"] : ["it", "it"];
31754
31917
  if (beside.length > 0) return fail(`${beside.join(" and ")} cannot sit beside ref; the shared enum supplies ${it}, so remove ${them}.`);
31755
31918
  const found = resolve(raw.ref);
31756
31919
  if (!found.ok) return found;
31757
31920
  const entries = Object.entries(raw).flatMap(([k, v]) => k === "ref" ? [["type", "string"], ["enum", found.values]] : [[k, v]]);
31758
- return { ok: true, field: Object.fromEntries(entries) };
31921
+ return { ok: true, field: Object.fromEntries(entries), sharedEnum: { file: found.file, name: found.name, values: [...found.values] } };
31759
31922
  }
31760
31923
 
31761
31924
  // src/models/tomlLoader.ts
@@ -31791,7 +31954,7 @@ function checkUnknownKeys(raw, known, context, strict) {
31791
31954
  function firstProblem(problems, ...codes) {
31792
31955
  return problems.find((problem) => codes.includes(problem.code));
31793
31956
  }
31794
- function parseFieldOptions(raw, context, strict, vectors, sharedEnums) {
31957
+ function parseFieldOptions(raw, context, strict, vectors, fieldName, sharedEnums) {
31795
31958
  const expanded = sharedEnums ? expandSharedEnumField(raw, sharedEnums) : { ok: true, field: raw };
31796
31959
  if (!expanded.ok) throw new Error(`${context}: ref ${JSON.stringify(raw.ref)}: ${expanded.message}`);
31797
31960
  const { decl, problems } = readFieldTable(raw = expanded.field, "model");
@@ -31820,7 +31983,9 @@ function parseFieldOptions(raw, context, strict, vectors, sharedEnums) {
31820
31983
  `${context}: invalid auto_stamp value "${autoStamp.value}". Must be one of: ${autoStamp.literals.join(", ")}`
31821
31984
  );
31822
31985
  }
31823
- const badEnum = firstProblem(problems, "not-for-type", "enum-not-list", "enum-member-not-string");
31986
+ const badEnum = problems.find(
31987
+ (problem) => problem.code === "not-for-type" && problem.key === "enum" || problem.code === "enum-not-list" || problem.code === "enum-member-not-string"
31988
+ );
31824
31989
  if (badEnum?.code === "not-for-type") {
31825
31990
  throw new Error(
31826
31991
  `${context}: \`enum\` is only valid on a "string" field, not "${badEnum.type}".`
@@ -31832,6 +31997,7 @@ function parseFieldOptions(raw, context, strict, vectors, sharedEnums) {
31832
31997
  if (badEnum) {
31833
31998
  throw new Error(`${context}: \`enum\` values must all be strings.`);
31834
31999
  }
32000
+ enforceEnumProblem(raw, decl, problems, context, fieldName, vectors);
31835
32001
  const opts = { type: decl.type };
31836
32002
  if (decl.type === "vector") {
31837
32003
  opts.dims = decl.dims;
@@ -31846,8 +32012,31 @@ function parseFieldOptions(raw, context, strict, vectors, sharedEnums) {
31846
32012
  if (decl.maxCount !== void 0) opts.maxCount = decl.maxCount;
31847
32013
  if (decl.default !== void 0) opts.default = decl.default;
31848
32014
  if (decl.enum !== void 0) opts.enum = [...decl.enum];
32015
+ if (decl.enforceEnum === true) opts.enforceEnum = true;
31849
32016
  return opts;
31850
32017
  }
32018
+ function enforceEnumProblem(raw, decl, problems, context, fieldName, vectors) {
32019
+ if (!Object.prototype.hasOwnProperty.call(raw, "enforce_enum")) return;
32020
+ for (const problem of problems) {
32021
+ if (!("key" in problem) || problem.key !== "enforce_enum") continue;
32022
+ if (problem.code === "not-for-type") {
32023
+ throw new Error(`${context}: enforce_enum is only valid on a "string" field, not "${problem.type}".`);
32024
+ }
32025
+ throw new Error(`${context}: ${fieldProblemMessage(problem)}`);
32026
+ }
32027
+ if (decl.enforceEnum !== true) return;
32028
+ if (fieldName === "id") throw new Error(`${context}: enforce_enum cannot be set on the id field`);
32029
+ if (!vectors) {
32030
+ throw new Error(
32031
+ `${context}: enforce_enum belongs to a db3 type (a schema with a [type] table); a document schema or a database type cannot declare it`
32032
+ );
32033
+ }
32034
+ if (decl.default !== void 0 && (typeof decl.default !== "string" || (decl.enum ?? []).indexOf(decl.default) < 0)) {
32035
+ throw new Error(
32036
+ `${context}: enforce_enum: default ${JSON.stringify(decl.default)} is not one of the enum's values`
32037
+ );
32038
+ }
32039
+ }
31851
32040
  function requireField(raw, field, context) {
31852
32041
  if (!raw[field]) {
31853
32042
  throw new Error(`Relationship ${context}: missing required field "${field}"`);
@@ -31930,7 +32119,7 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
31930
32119
  throw new ReservedFieldNameError(`${context}: ${reserved}`);
31931
32120
  }
31932
32121
  }
31933
- const fieldOptions = parseFieldOptions(fieldDef, context, strict, vectors, options.sharedEnums);
32122
+ const fieldOptions = parseFieldOptions(fieldDef, context, strict, vectors, fieldName, options.sharedEnums);
31934
32123
  declaredFields.set(fieldName, fieldOptions);
31935
32124
  fields[fieldName] = fieldOptions;
31936
32125
  }
@@ -32238,6 +32427,7 @@ var CAMEL_TO_SNAKE2 = {
32238
32427
  autoStamp: "auto_stamp",
32239
32428
  maxLength: "max_length",
32240
32429
  maxCount: "max_count",
32430
+ enforceEnum: "enforce_enum",
32241
32431
  relatedIdField: "related_id_field",
32242
32432
  joinModel: "join_model",
32243
32433
  joinModelLocalField: "join_model_local_field",
@@ -32296,6 +32486,7 @@ function renderModelsToml(models) {
32296
32486
  if (opts.enum !== void 0) {
32297
32487
  lines.push(`enum = [${opts.enum.map((v) => tomlValue2(v)).join(", ")}]`);
32298
32488
  }
32489
+ if (opts.enforceEnum === true) lines.push("enforce_enum = true");
32299
32490
  if (Array.isArray(opts.default)) {
32300
32491
  lines.push(`default = [${opts.default.map((v) => tomlValue2(v)).join(", ")}]`);
32301
32492
  } else if (opts.default !== void 0) {
@@ -32480,6 +32671,8 @@ var SWIFT_CODEGEN_RESERVED_NAMES = [
32480
32671
  "Set",
32481
32672
  "String",
32482
32673
  "Type",
32674
+ "UniqueConstraint",
32675
+ "UniqueField",
32483
32676
  "UpsertMode",
32484
32677
  "Void"
32485
32678
  ];
@@ -32642,7 +32835,10 @@ function declaredOptions(model, field, declared, noteField, warn) {
32642
32835
  const maxCount = option(declared, "maxCount", "max_count");
32643
32836
  if (typeof maxCount === "number") options.maxCount = maxCount;
32644
32837
  const values = option(declared, "enum", "enum");
32645
- if (Array.isArray(values) && values.every((value) => typeof value === "string")) options.enum = values;
32838
+ if (Array.isArray(values) && values.every((value) => typeof value === "string")) {
32839
+ options.enum = values;
32840
+ if (values.length > 0 && options.type === "string" && option(declared, "enforceEnum", "enforce_enum") === true) options.enforceEnum = true;
32841
+ }
32646
32842
  const fallback = option(declared, "default", "default");
32647
32843
  if (fallback !== void 0) {
32648
32844
  const literal4 = literalDefault(fallback);