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

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
@@ -5204,6 +5204,74 @@ var init_write = __esm({
5204
5204
  }
5205
5205
  });
5206
5206
 
5207
+ // src/record-log-client/declared-types.ts
5208
+ function isRepresentableDate(value) {
5209
+ if (typeof value === "number") return Number.isFinite(value) && !Number.isNaN(new Date(value).getTime());
5210
+ const shape = ISO_DATE_STRING.exec(value);
5211
+ if (!shape) return false;
5212
+ if (Number.isNaN(Date.parse(value.replace(" ", "T")))) return false;
5213
+ const [, year, month, day] = shape;
5214
+ const roundTrip = /* @__PURE__ */ new Date(`${year}-${month}-${day}T00:00:00Z`);
5215
+ return roundTrip.getUTCFullYear() === Number(year) && roundTrip.getUTCMonth() + 1 === Number(month) && roundTrip.getUTCDate() === Number(day);
5216
+ }
5217
+ function receivedKind(value) {
5218
+ if (Array.isArray(value)) return "an array";
5219
+ return typeof value;
5220
+ }
5221
+ function declaredTypeProblem(mutations, type) {
5222
+ const declaredModels = Object.keys(type.models).sort();
5223
+ for (const [at, m] of mutations.entries()) {
5224
+ const where2 = at === 0 ? "m" : `also[${at - 1}]`;
5225
+ if (declaredModels.length && !Object.prototype.hasOwnProperty.call(type.models, m.model)) {
5226
+ return {
5227
+ code: "DB3_MODEL_NOT_DECLARED",
5228
+ message: `${where2}: ${m.model} is not a model of the db3's type ${type.name}; it declares ${declaredModels.join(", ")}`
5229
+ };
5230
+ }
5231
+ if (m.kind === "delete") continue;
5232
+ const kinds = type.models[m.model];
5233
+ if (!kinds || !Object.keys(kinds).length) continue;
5234
+ const declaredOf = (field) => Object.prototype.hasOwnProperty.call(kinds, field) ? kinds[field] : void 0;
5235
+ const refuse = (field, declared, received) => ({
5236
+ code: "DOCUMENT_ENTRY_INVALID",
5237
+ message: `${where2}: ${m.model} id=${m.id}: field "${field}" is declared ${declared}; the entry wrote ${received}`
5238
+ });
5239
+ for (const [field, value] of Object.entries(m.fields ?? {})) {
5240
+ if (field === "id" || value === null) continue;
5241
+ const declared = declaredOf(field);
5242
+ if (declared === void 0) continue;
5243
+ const kind = m.kind === "increment" ? "number" : receivedKind(value);
5244
+ if (declared === "stringset") return refuse(field, declared, `a scalar (${kind})`);
5245
+ if (!SCALAR_KINDS.has(declared)) continue;
5246
+ const matches = declared === "date" ? (kind === "string" || kind === "number") && (m.kind === "increment" || isRepresentableDate(value)) : declared === "id" ? kind === "string" : kind === declared;
5247
+ if (!matches) return refuse(field, declared, kind === "string" && declared === "date" ? "a string that is not an ISO date" : kind);
5248
+ }
5249
+ for (const field of Object.keys(m.stringSetDeltas ?? {})) {
5250
+ const declared = declaredOf(field);
5251
+ if (declared !== void 0 && declared !== "stringset") return refuse(field, declared, "a string-set change");
5252
+ }
5253
+ }
5254
+ return null;
5255
+ }
5256
+ function assertRecordLogDeclaredTypes(documentId, mutations, type, report) {
5257
+ if (!type || !mutations.length) return;
5258
+ const problem = declaredTypeProblem(mutations, type);
5259
+ if (!problem) return;
5260
+ const error = new RecordLogWriteRefusedError(problem.code, documentId, problem.message, { scope: "local" });
5261
+ const [first, ...rest] = mutations;
5262
+ report?.({ documentId, model: first.model, recordId: first.id, error, writes: refusedWritesOf({ seq: 0, m: first, also: rest }) });
5263
+ throw error;
5264
+ }
5265
+ var SCALAR_KINDS, ISO_DATE_STRING;
5266
+ var init_declared_types = __esm({
5267
+ "src/record-log-client/declared-types.ts"() {
5268
+ "use strict";
5269
+ init_types();
5270
+ SCALAR_KINDS = /* @__PURE__ */ new Set(["string", "number", "boolean", "date", "id"]);
5271
+ ISO_DATE_STRING = /^(\d{4})-(\d{2})-(\d{2})(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
5272
+ }
5273
+ });
5274
+
5207
5275
  // src/record-log/types.ts
5208
5276
  function recordKeyString(key) {
5209
5277
  return `${key.model}${KEY_SEPARATOR}${key.id}`;
@@ -6951,6 +7019,11 @@ function stagedForRead(ormContext, store, model, id) {
6951
7019
  const group = activeRecordLogTransactions.get(ormContext) ?? (unbound && unbound.owner === ormContext ? unbound : null);
6952
7020
  return group?.staged(store, model, id);
6953
7021
  }
7022
+ function declaredTypeOf(store) {
7023
+ const models = store.declaredTypes();
7024
+ const name = store.marks().db3Type?.name;
7025
+ return models && name ? { name, models } : null;
7026
+ }
6954
7027
  function recordLogTransactionOf(ormContext) {
6955
7028
  const bound = activeRecordLogTransactions.get(ormContext);
6956
7029
  if (bound) return bound;
@@ -6988,6 +7061,7 @@ var init_BaseModel = __esm({
6988
7061
  init_fieldCoercion();
6989
7062
  init_OrmContext();
6990
7063
  init_write();
7064
+ init_declared_types();
6991
7065
  init_types();
6992
7066
  init_guess();
6993
7067
  init_types2();
@@ -7083,6 +7157,7 @@ var init_BaseModel = __esm({
7083
7157
  try {
7084
7158
  for (const entry of entries) {
7085
7159
  assertRecordLogEntry(store.docId, entry.mutations, report, entry.upsertOn ? { upsertOn: entry.upsertOn } : {});
7160
+ assertRecordLogDeclaredTypes(store.docId, entry.mutations, declaredTypeOf(store), report);
7086
7161
  }
7087
7162
  seqs = await store.trackLocalWrite(
7088
7163
  () => store.run("transaction", async (ops) => {
@@ -9845,6 +9920,7 @@ var init_BaseModel = __esm({
9845
9920
  };
9846
9921
  const entryUpsertOn = upsertOn ?? (upsertOnField !== null && guards.ifNotExists ? upsertOnField : void 0);
9847
9922
  assertRecordLogEntry(docId, [mutation], report, entryUpsertOn !== void 0 ? { upsertOn: entryUpsertOn } : {});
9923
+ if (!transaction) assertRecordLogDeclaredTypes(docId, [mutation], declaredTypeOf(store), report);
9848
9924
  this._format2Row = store.entryFor(modelName, this.id);
9849
9925
  if (transaction) {
9850
9926
  stagedEntry = transaction.add(store, { mutation, upsertOn, instance: this, existing });
@@ -9984,6 +10060,7 @@ var init_BaseModel = __esm({
9984
10060
  await store.trackLocalWrite(
9985
10061
  () => store.run("increment", async (ops) => {
9986
10062
  assertRecordLogEntry(docId, [mutation], report);
10063
+ if (!transaction) assertRecordLogDeclaredTypes(docId, [mutation], declaredTypeOf(store), report);
9987
10064
  const viewRow = await ops.read(modelName, id);
9988
10065
  const staged = transaction?.staged(store, modelName, id);
9989
10066
  const existing = staged === void 0 ? viewRow : staged;
@@ -11441,7 +11518,10 @@ var init_BaseModel = __esm({
11441
11518
  /**
11442
11519
  * Execute a callback with automatic transaction handling for all modified
11443
11520
  * models. On a db3 the saves made inside land as one entry per db3, or one
11444
- * per record with `options.atomic` set to `false`.
11521
+ * per record with `options.atomic` set to `false`. "Atomic" describes that
11522
+ * entry: the room applies it whole or refuses it whole. It does not undo
11523
+ * the callback itself — if the callback throws, the saves it already made
11524
+ * still land, and the error is rethrown after.
11445
11525
  */
11446
11526
  static async withTransaction(callback, options) {
11447
11527
  const modifiedModels = /* @__PURE__ */ new Set();
@@ -11837,6 +11917,7 @@ __export(browser_exports, {
11837
11917
  aggregateViewRows: () => aggregateViewRows,
11838
11918
  applyChange: () => applyChange,
11839
11919
  applyGuess: () => applyGuess,
11920
+ assertRecordLogDeclaredTypes: () => assertRecordLogDeclaredTypes,
11840
11921
  assertRecordLogEntry: () => assertRecordLogEntry,
11841
11922
  assertRecordLogRecordInput: () => assertRecordLogRecordInput,
11842
11923
  assertRecordLogWriteAllowed: () => assertRecordLogWriteAllowed,
@@ -11853,6 +11934,7 @@ __export(browser_exports, {
11853
11934
  conditionProblem: () => conditionProblem,
11854
11935
  countViewRows: () => countViewRows,
11855
11936
  db3ViewTranslator: () => db3ViewTranslator,
11937
+ declaredTypeProblem: () => declaredTypeProblem,
11856
11938
  decodeRecordLogChunk: () => decodeRecordLogChunk,
11857
11939
  decodeRecordLogError: () => decodeRecordLogError,
11858
11940
  defineModelSchema: () => defineModelSchema,
@@ -15326,7 +15408,9 @@ function recordLogClientDDL() {
15326
15408
  replacing INTEGER,
15327
15409
  receipt TEXT,
15328
15410
  segment TEXT,
15329
- staged INTEGER
15411
+ staged INTEGER,
15412
+ typed TEXT,
15413
+ db3_type TEXT
15330
15414
  )`,
15331
15415
  `CREATE TABLE IF NOT EXISTS record_log_writers (
15332
15416
  doc_id TEXT NOT NULL,
@@ -15420,7 +15504,9 @@ function recordLogClientDDL() {
15420
15504
  var RECORD_LOG_CLIENT_ADDED_COLUMNS = Object.freeze([
15421
15505
  { table: "record_log_state", column: "receipt", add: `ALTER TABLE record_log_state ADD COLUMN receipt TEXT` },
15422
15506
  { table: "record_log_state", column: "segment", add: `ALTER TABLE record_log_state ADD COLUMN segment TEXT` },
15423
- { table: "record_log_state", column: "staged", add: `ALTER TABLE record_log_state ADD COLUMN staged INTEGER` }
15507
+ { table: "record_log_state", column: "staged", add: `ALTER TABLE record_log_state ADD COLUMN staged INTEGER` },
15508
+ { table: "record_log_state", column: "typed", add: `ALTER TABLE record_log_state ADD COLUMN typed TEXT` },
15509
+ { table: "record_log_state", column: "db3_type", add: `ALTER TABLE record_log_state ADD COLUMN db3_type TEXT` }
15424
15510
  ]);
15425
15511
  function recordLogFieldIndexName(kind, model, name, table = "view") {
15426
15512
  const tag = kind === "field" ? "f" : "u";
@@ -15533,6 +15619,37 @@ var SqlRecordLogTables = class {
15533
15619
  this.ensureState();
15534
15620
  this.sql.exec(`UPDATE record_log_state SET permission = ? WHERE doc_id = ?`, permission, this.docId);
15535
15621
  }
15622
+ /** The typed mark, the type and its held declarations. */
15623
+ typeState() {
15624
+ const state = this.state();
15625
+ const typed = state?.typed === "yes" ? "yes" : state?.typed === "no" ? "no" : "unknown";
15626
+ if (typed !== "yes" || !state?.db3_type) return { typed, db3Type: null, declarations: null };
15627
+ try {
15628
+ const held = JSON.parse(String(state.db3_type));
15629
+ return { typed, db3Type: { name: held.name, hash: held.hash ?? null }, declarations: held.models ?? null };
15630
+ } catch {
15631
+ return { typed, db3Type: null, declarations: null };
15632
+ }
15633
+ }
15634
+ /**
15635
+ * Record what the room said of the type: untyped clears the type; typed
15636
+ * keeps the held declarations when the hash is theirs and none were sent.
15637
+ */
15638
+ setType(update) {
15639
+ this.ensureState();
15640
+ if (update.typed === "no") {
15641
+ this.sql.exec(`UPDATE record_log_state SET typed = 'no', db3_type = NULL WHERE doc_id = ?`, this.docId);
15642
+ return;
15643
+ }
15644
+ const held = this.typeState();
15645
+ const { name, hash, models } = update.db3Type;
15646
+ const kept = models ?? (hash !== null && held.db3Type?.hash === hash ? held.declarations : null);
15647
+ this.sql.exec(
15648
+ `UPDATE record_log_state SET typed = 'yes', db3_type = ? WHERE doc_id = ?`,
15649
+ JSON.stringify({ name, hash: kept ? hash : null, models: kept }),
15650
+ this.docId
15651
+ );
15652
+ }
15536
15653
  setLastCatchUpAt(at) {
15537
15654
  this.ensureState();
15538
15655
  this.sql.exec(`UPDATE record_log_state SET last_catch_up_at = ? WHERE doc_id = ?`, at, this.docId);
@@ -16180,6 +16297,11 @@ var RecordLogStore = class {
16180
16297
  };
16181
16298
  });
16182
16299
  }
16300
+ /** The permission mark alone. */
16301
+ permissionMark() {
16302
+ const [state] = rowsOf2(this.sql, `SELECT permission FROM record_log_state WHERE doc_id = ?`, this.docId);
16303
+ return state?.permission ?? null;
16304
+ }
16183
16305
  /** Everything a facade mirrors, in one read. */
16184
16306
  marks() {
16185
16307
  const epochs = this.tables.epochs();
@@ -16208,7 +16330,8 @@ var RecordLogStore = class {
16208
16330
  pending: Number(pending?.n ?? 0),
16209
16331
  unacked: writer ? this.unackedOf(writer) : [],
16210
16332
  receipt: latestReceipt(this.tables.receipts()),
16211
- segment: this.tables.heldSegment()
16333
+ segment: this.tables.heldSegment(),
16334
+ ...this.tables.typeState()
16212
16335
  };
16213
16336
  }
16214
16337
  /** A writer's unacknowledged, unwithdrawn entries and the records each touches. */
@@ -16978,13 +17101,16 @@ var RecordLogStore = class {
16978
17101
  }
16979
17102
  return { changed: this.settleBulk([...keys.values()]), models };
16980
17103
  }
16981
- /** Record what the room said about epochs and constraints, and the permission the client holds. */
17104
+ /** Record what the room said about epochs, constraints and the db3's type, and the permission the client holds. */
16982
17105
  setState(command) {
16983
17106
  return this.sql.transaction(() => {
16984
17107
  const client = this.client(command.writer);
16985
17108
  if (command.notice) client.notice(command.notice.current, command.notice.next, command.notice.entries);
16986
17109
  if (command.constraints) this.tables.setConstraints(command.constraints);
16987
- if (command.permission !== void 0) this.tables.setPermission(command.permission);
17110
+ if (command.permission !== void 0 && (command.permissionFrom === void 0 || this.permissionMark() === command.permissionFrom)) {
17111
+ this.tables.setPermission(command.permission);
17112
+ }
17113
+ if (command.type) this.tables.setType(command.type);
16988
17114
  return this.marks();
16989
17115
  });
16990
17116
  }
@@ -20617,13 +20743,21 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
20617
20743
  return reply;
20618
20744
  });
20619
20745
  }
20620
- /** Record epochs, constraints and permission; refresh the mirror. */
20746
+ /** Record epochs, constraints, permission and what the room said of the db3's type; refresh the mirror. */
20621
20747
  setState(state) {
20622
20748
  return this.run("setState", async () => {
20623
20749
  this.mirror = await this.host.dispatch({ kind: "setState", writer: this.writer(), ...state });
20624
20750
  return this.mirror;
20625
20751
  });
20626
20752
  }
20753
+ /**
20754
+ * The declarations of the db3's type the room sent this device (#5020),
20755
+ * per model each declared field's kind; `null` while the db3 is not known
20756
+ * to be typed or none were received yet.
20757
+ */
20758
+ declaredTypes() {
20759
+ return this.mirror.typed === "yes" ? this.mirror.declarations ?? null : null;
20760
+ }
20627
20761
  /**
20628
20762
  * Whether the local pre-check should hold a save to a unique constraint:
20629
20763
  * every constraint is checked unless the room has said it keeps it out of
@@ -21146,7 +21280,28 @@ var RecordLogSender = class {
21146
21280
  // src/record-log-client/session.ts
21147
21281
  init_types();
21148
21282
  var ACCESS_REFUSED_MESSAGE = "Access denied to document";
21149
- var ACCESS_REFUSED_CODES = /* @__PURE__ */ new Set(["ACCESS_DENIED", "DOC_ACCESS_DENIED", "DB3_SYNC_OFF"]);
21283
+ var ACCESS_REFUSED_CODES = /* @__PURE__ */ new Set(["ACCESS_DENIED", "DOC_ACCESS_DENIED", "DB3_SYNC_OFF", "DOCUMENT_DELETED"]);
21284
+ function typeOfOpened(frame, docId) {
21285
+ if (!("db3Type" in frame) || frame.db3Type === void 0) return { type: { typed: "no" } };
21286
+ const type = frame.db3Type;
21287
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
21288
+ const models = isObject(type) ? type.models : void 0;
21289
+ const wellFormed = isObject(type) && typeof type.name === "string" && type.name !== "" && typeof type.hash === "string" && type.hash !== "" && (models === void 0 || isObject(models) && Object.values(models).every((fields) => isObject(fields) && Object.values(fields).every((kind) => typeof kind === "string")));
21290
+ if (!wellFormed) {
21291
+ Logger.warn(`[record-log] ${docId}: record.opened carried a db3Type this client cannot read; the type it holds is kept`);
21292
+ return {};
21293
+ }
21294
+ return {
21295
+ type: {
21296
+ typed: "yes",
21297
+ db3Type: {
21298
+ name: type.name,
21299
+ hash: type.hash,
21300
+ ...models !== void 0 ? { models } : {}
21301
+ }
21302
+ }
21303
+ };
21304
+ }
21150
21305
  function isAccessRefusal(frame) {
21151
21306
  const type = frame.messageType;
21152
21307
  if (type !== void 0 && !(typeof type === "string" && type.startsWith("record."))) return false;
@@ -21465,7 +21620,8 @@ var RecordLogDocumentSession = class {
21465
21620
  const nextSeq = unacked.length ? unacked[0].seq : current.orphan ? Math.max(1, ...pending.map((p) => p.seq + 1)) : marks.nextSeq;
21466
21621
  this.phase = "opening";
21467
21622
  this.loadInProgress = null;
21468
- const sendAhead = !current.orphan && this.openedOnConnection === 0 && [...this.history.opened].every((writer) => writer === current.writer) && nextSeq > marks.resumedAt;
21623
+ const typed = marks.typed ?? "unknown";
21624
+ const sendAhead = !current.orphan && this.openedOnConnection === 0 && [...this.history.opened].every((writer) => writer === current.writer) && nextSeq > marks.resumedAt && (typed !== "unknown" || !this.host.awaitTypeBeforeDeclaring);
21469
21625
  this.openedOnConnection++;
21470
21626
  this.history.opened.add(current.writer);
21471
21627
  const fetches = typeof this.host.connection()?.fetchArtifact === "function";
@@ -21489,13 +21645,19 @@ var RecordLogDocumentSession = class {
21489
21645
  acks: "compact",
21490
21646
  // A room past this client's wire version refuses the open (DB3_CLIENT_OUTDATED).
21491
21647
  wireVersion: RECORD_LOG_WIRE_VERSION,
21492
- ...fetches ? { accepts: this.failedReceipts >= RECORD_LOG_RECEIPT_FAILURES_BEFORE_ROWS ? [] : accepts } : {}
21648
+ ...fetches ? { accepts: this.failedReceipts >= RECORD_LOG_RECEIPT_FAILURES_BEFORE_ROWS ? [] : accepts } : {},
21649
+ // The type revision whose declarations this device holds: the room
21650
+ // sends them again only for another one (#5020).
21651
+ ...typed === "yes" && marks.db3Type?.hash ? { db3TypeHash: marks.db3Type.hash } : {}
21493
21652
  });
21494
21653
  if (!sendAhead) return;
21495
- const models = this.host.declarations();
21496
- const ahead = { declarations: JSON.stringify(models), refused: false, seqs: [] };
21654
+ const ahead = { declarations: null, refused: false, seqs: [] };
21497
21655
  this.ahead = ahead;
21498
- this.sender.enqueueControl({ type: "record.declare", models });
21656
+ if (typed !== "yes") {
21657
+ const models = this.host.declarations();
21658
+ ahead.declarations = JSON.stringify(models);
21659
+ this.sender.enqueueControl({ type: "record.declare", models });
21660
+ }
21499
21661
  for (const entry of unacked) this.sender.enqueue(wireEntryOf(entry));
21500
21662
  this.sendingAhead = true;
21501
21663
  try {
@@ -21744,7 +21906,9 @@ var RecordLogDocumentSession = class {
21744
21906
  ...Array.isArray(frame.constraints) ? { constraints: frame.constraints } : {},
21745
21907
  // The room opened the document for this client's writer: an access
21746
21908
  // refusal it answered before is over.
21747
- ...!this.current.orphan && this.store.marks().permission === "refused" ? { permission: null } : {}
21909
+ ...!this.current.orphan && this.store.marks().permission === "refused" ? { permission: null } : {},
21910
+ // The room says whether the db3 is typed, and by what (#5020).
21911
+ ...typeOfOpened(frame, this.docId)
21748
21912
  });
21749
21913
  if (generation !== this.generation) return;
21750
21914
  this.lastSeq = Number(frame.lastSeq ?? 0);
@@ -22408,8 +22572,12 @@ var RecordLogDocumentSession = class {
22408
22572
  if (ahead && !ahead.refused) {
22409
22573
  if (!unsent.length) await this.store.refreshMarks();
22410
22574
  if (generation !== this.generation) return;
22411
- const models = this.host.declarations();
22412
- if (JSON.stringify(models) !== ahead.declarations) this.sender.enqueueControl({ type: "record.declare", models });
22575
+ if (this.store.marks().typed === "yes") {
22576
+ if (ahead.declarations === null) this.host.declared?.(this.docId);
22577
+ } else {
22578
+ const models = this.host.declarations();
22579
+ if (JSON.stringify(models) !== ahead.declarations) this.sender.enqueueControl({ type: "record.declare", models });
22580
+ }
22413
22581
  for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
22414
22582
  return this.synced();
22415
22583
  }
@@ -22424,7 +22592,8 @@ var RecordLogDocumentSession = class {
22424
22592
  return;
22425
22593
  }
22426
22594
  this.sender.requeueInFlight(unsent.map(wireEntryOf));
22427
- this.sender.enqueueControl({ type: "record.declare", models: this.host.declarations() });
22595
+ if (this.store.marks().typed === "yes") this.host.declared?.(this.docId);
22596
+ else this.sender.enqueueControl({ type: "record.declare", models: this.host.declarations() });
22428
22597
  for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
22429
22598
  return this.synced();
22430
22599
  }
@@ -22670,18 +22839,20 @@ var RecordLogDocumentSession = class {
22670
22839
  * is marked `permission: "refused"` (local writes are refused from now),
22671
22840
  * its unjudged entries stay for the room to judge once access returns,
22672
22841
  * nothing more is sent, and the open is reported failed with
22673
- * `ACCESS_DENIED`, or `DB3_SYNC_OFF` when the db3's sync was turned off
22674
- * (#4799). The own writer's next `record.opened` lifts the mark.
22842
+ * `ACCESS_DENIED`, `DB3_SYNC_OFF` when the db3's sync was turned off
22843
+ * (#4799), or `DOCUMENT_DELETED` when the db3 was deleted (#5049). The own
22844
+ * writer's next `record.opened` lifts the mark.
22675
22845
  */
22676
22846
  async accessRefused(frame) {
22677
22847
  if (this.phase === "closed") return;
22678
- const syncOff = frame.code === "DB3_SYNC_OFF";
22848
+ const reason = frame.code === "DB3_SYNC_OFF" || frame.code === "DOCUMENT_DELETED" ? frame.code : "ACCESS_DENIED";
22849
+ const why = reason === "DB3_SYNC_OFF" ? "because its sync is off" : reason === "DOCUMENT_DELETED" ? "because it was deleted" : "for access";
22679
22850
  Logger.warn(
22680
- `[record-log] ${this.docId}: the room refused ${frame.messageType ?? "a record frame"} ${syncOff ? "because its sync is off" : "for access"}; the document stays readable here, its unsent writes are kept, and nothing more is sent`
22851
+ `[record-log] ${this.docId}: the room refused ${frame.messageType ?? "a record frame"} ${why}; the document stays readable here, its unsent writes are kept, and nothing more is sent`
22681
22852
  );
22682
22853
  this.disconnected();
22683
22854
  await this.store.setState({ permission: "refused" });
22684
- this.host.syncFailed(this.docId, syncOff ? "DB3_SYNC_OFF" : "ACCESS_DENIED");
22855
+ this.host.syncFailed(this.docId, reason);
22685
22856
  }
22686
22857
  /**
22687
22858
  * The room refused this writer's writes for the whole document (it is
@@ -22706,9 +22877,15 @@ var RecordLogDocumentSession = class {
22706
22877
  const code = String(frame.code ?? "");
22707
22878
  const current = this.current;
22708
22879
  if (code === "DB3_DECLARATION_REFUSED_TYPED" && frame.messageType === "record.declare") {
22709
- Logger.warn(
22880
+ Logger.debug(
22710
22881
  `[record-log] ${this.docId}: the db3 is typed by ${frame.db3Type ?? "its type"}; the room keeps the type's declarations, and this client's models are judged against them.`
22711
22882
  );
22883
+ if (typeof frame.db3Type === "string" && frame.db3Type) {
22884
+ const held = this.store.marks().db3Type;
22885
+ await this.store.setState({
22886
+ type: { typed: "yes", db3Type: { name: frame.db3Type, hash: held?.name === frame.db3Type ? held.hash : null } }
22887
+ });
22888
+ }
22712
22889
  this.host.declared?.(this.docId);
22713
22890
  return;
22714
22891
  }
@@ -22907,6 +23084,7 @@ var RecordLogSessions = class {
22907
23084
  store,
22908
23085
  {
22909
23086
  connection: () => this.connection,
23087
+ awaitTypeBeforeDeclaring: this.host.awaitTypeBeforeDeclaring === true,
22910
23088
  declarations: () => this.host.declarations(),
22911
23089
  notify: (records) => this.host.notify(records),
22912
23090
  reportRefused: (event) => this.host.reportRefused(event),
@@ -22999,6 +23177,9 @@ var RecordLogDocumentBinding = class {
22999
23177
  this.ormContext = ormContext;
23000
23178
  this.storeScope = storeScope;
23001
23179
  this.sessions = new RecordLogSessions({
23180
+ // A db3 this device has not heard about may be typed: its first open
23181
+ // declares only once the room says it is not (#5020).
23182
+ awaitTypeBeforeDeclaring: true,
23002
23183
  declarations: () => this.declarations(),
23003
23184
  notify: (records) => this.notify(records),
23004
23185
  reportRefused: (event) => this.ormContext.reportRecordLogWriteRefused(event)
@@ -23010,6 +23191,10 @@ var RecordLogDocumentBinding = class {
23010
23191
  createdLocally = /* @__PURE__ */ new Set();
23011
23192
  /** Bound db3s withdrawn from reads and writes while their release runs. */
23012
23193
  hidden = /* @__PURE__ */ new Set();
23194
+ /** Opens in flight, by document: a concurrent open of the same document joins it. */
23195
+ opening = /* @__PURE__ */ new Map();
23196
+ /** Bound db3s whose models' query tables are loaded (`connect` completed). */
23197
+ connected = /* @__PURE__ */ new Set();
23013
23198
  /** Told that a bound db3's unacknowledged entries changed. */
23014
23199
  pendingListeners = /* @__PURE__ */ new Set();
23015
23200
  /** Told every bound db3's view-row changes. */
@@ -23026,10 +23211,25 @@ var RecordLogDocumentBinding = class {
23026
23211
  const persistent = platform.persistent && !(volatile && platform.probed);
23027
23212
  if (!persistent) throw new Db3StorageCapabilityError("not-persistent", 0, platform.quotaBytes, []);
23028
23213
  }
23029
- /** Open `docId`'s store, once, and register it on the instance. */
23030
- async open(docId) {
23214
+ /**
23215
+ * Open `docId`'s store, once, and register it on the instance. A second
23216
+ * open while the first is under way gets the first's store, so the engine
23217
+ * hosts the document once (#5049).
23218
+ */
23219
+ open(docId) {
23031
23220
  const mine = this.opened.get(docId);
23032
- if (mine && this.ormContext.recordLogDocuments.get(docId) === mine) return mine;
23221
+ if (mine && this.ormContext.recordLogDocuments.get(docId) === mine) return Promise.resolve(mine);
23222
+ const running = this.opening.get(docId);
23223
+ if (running) return running;
23224
+ const opening = this.openOnce(docId);
23225
+ this.opening.set(docId, opening);
23226
+ const settled = () => {
23227
+ if (this.opening.get(docId) === opening) this.opening.delete(docId);
23228
+ };
23229
+ opening.then(settled, settled);
23230
+ return opening;
23231
+ }
23232
+ async openOnce(docId) {
23033
23233
  const host = await this.createHost(docId);
23034
23234
  const store = await RecordLogStoreAsync.open(host, docId, { storeKey: this.storeKey() });
23035
23235
  this.opened.set(docId, store);
@@ -23072,6 +23272,37 @@ var RecordLogDocumentBinding = class {
23072
23272
  Logger.info(`[record-log] ${docId}: connected with write access again; saves are allowed`);
23073
23273
  await store.setState({ permission: null });
23074
23274
  }
23275
+ /**
23276
+ * Take the type the client knows `docId` was created with (#5020): a
23277
+ * store the room has not yet told whether the db3 is typed is marked typed
23278
+ * by `type`, so its first open declares nothing. A mark the room set is
23279
+ * kept.
23280
+ */
23281
+ async seedType(docId, type) {
23282
+ const store = this.opened.get(docId);
23283
+ if (!store || (await store.refreshMarks()).typed !== "unknown") return;
23284
+ await store.setState({ type: { typed: "yes", db3Type: { name: type, hash: null } } });
23285
+ }
23286
+ /**
23287
+ * Take a permission the client heard for a bound db3 while it stays
23288
+ * connected (#5020): the connected document's hint becomes `permission`,
23289
+ * and the store's mark follows it, `read` on a read-only grant and lifted
23290
+ * on a write-capable one, as the room's `WRITE_ACCESS_DENIED` and a
23291
+ * connect with write access set and lift it. A `refused` mark is the
23292
+ * room's to lift. Nothing happens for a document not bound here.
23293
+ */
23294
+ async permissionChanged(docId, permission) {
23295
+ const store = this.opened.get(docId);
23296
+ if (!store) return;
23297
+ const connected = this.ormContext.connectedDocuments.get(docId);
23298
+ if (connected) connected.permissionHint = permission;
23299
+ const before = store.marks().permission;
23300
+ const marks = permission === "read" ? await store.setState({ permission: "read", permissionFrom: null }) : await store.setState({ permission: null, permissionFrom: "read" });
23301
+ if (marks.permission === before) return;
23302
+ Logger.info(
23303
+ permission === "read" ? `[record-log] ${docId}: the client may only read now; saves are refused here` : `[record-log] ${docId}: the client may write again; saves are allowed`
23304
+ );
23305
+ }
23075
23306
  /**
23076
23307
  * The database a document opened now is stored in: an engine hosting its
23077
23308
  * own stores keeps one per scope; otherwise every document shares the
@@ -23087,10 +23318,14 @@ var RecordLogDocumentBinding = class {
23087
23318
  if (createdLocally) this.createdLocally.add(docId);
23088
23319
  else this.createdLocally.delete(docId);
23089
23320
  }
23090
- /** Whether bound `docId` is resident ({@link isRecordLogResident}); `false` when it is not bound here. */
23321
+ /**
23322
+ * Whether bound `docId` is resident ({@link isRecordLogResident}) and
23323
+ * connected (its models' query tables loaded, #5049); `false` when it is
23324
+ * not bound here.
23325
+ */
23091
23326
  isResident(docId) {
23092
23327
  const store = this.opened.get(docId);
23093
- if (!store || this.hidden.has(docId)) return false;
23328
+ if (!store || this.hidden.has(docId) || !this.connected.has(docId)) return false;
23094
23329
  return isRecordLogResident(store.marks(), this.createdLocally.has(docId));
23095
23330
  }
23096
23331
  /**
@@ -23159,6 +23394,7 @@ var RecordLogDocumentBinding = class {
23159
23394
  const store = this.opened.get(docId);
23160
23395
  if (!store) return;
23161
23396
  this.hidden.add(docId);
23397
+ this.connected.delete(docId);
23162
23398
  store.refuseLocalWrites();
23163
23399
  if (this.ormContext.recordLogDocuments.get(docId) === store) this.ormContext.recordLogDocuments.delete(docId);
23164
23400
  this.ormContext.connectedDocuments.delete(docId);
@@ -23245,12 +23481,15 @@ var RecordLogDocumentBinding = class {
23245
23481
  /**
23246
23482
  * Bind `docId` once its models are initialized: its store, opened once,
23247
23483
  * its lookup indexes reconciled from the store's cached index lists (the
23248
- * room's list arrives later through {@link syncIndexes}).
23484
+ * room's list arrives later through {@link syncIndexes}). From here it is
23485
+ * resident, when its store holds a readable copy; a second connect (a
23486
+ * re-bind) keeps it so.
23249
23487
  */
23250
23488
  async connect(docId) {
23251
23489
  const store = await this.open(docId);
23252
23490
  store.resumeAcknowledgements();
23253
23491
  await store.syncIndexes();
23492
+ if (this.opened.get(docId) === store) this.connected.add(docId);
23254
23493
  }
23255
23494
  /**
23256
23495
  * Cache the room's index list for `docId` and reconcile the store's
@@ -23290,6 +23529,7 @@ var RecordLogDocumentBinding = class {
23290
23529
  }
23291
23530
  store.refuseLocalWrites();
23292
23531
  this.createdLocally.delete(docId);
23532
+ this.connected.delete(docId);
23293
23533
  this.hidden.delete(docId);
23294
23534
  this.unsubscribers.get(docId)?.();
23295
23535
  this.unsubscribers.delete(docId);
@@ -23437,6 +23677,8 @@ var DocumentManagerImpl = class {
23437
23677
  bindingEpoch = 0;
23438
23678
  /** db3 connects not yet settled; an unbind of every db3 waits for them. */
23439
23679
  recordLogConnects = /* @__PURE__ */ new Set();
23680
+ /** db3 connects under way, by document: a failed one releases its store only when it is the last (#5049). */
23681
+ recordLogConnecting = /* @__PURE__ */ new Map();
23440
23682
  /**
23441
23683
  * The `(model, document)` pairs whose initialization for this instance
23442
23684
  * COMPLETED (#3615).
@@ -23510,19 +23752,22 @@ var DocumentManagerImpl = class {
23510
23752
  */
23511
23753
  async withdrawIfOvertaken(docId, epoch, opened) {
23512
23754
  if (this.bindingEpoch === epoch) return;
23513
- if (opened && this.recordLog.storeOf(docId) === opened && !this.connectedDocuments.has(docId)) {
23514
- try {
23515
- await this.modelRegistry.removeDocumentData(docId, this.dbEngine, { skipQueryTableWipe: true });
23516
- this.ormContext.disposeObserversForDocument(docId);
23517
- await this.recordLog.disconnect(docId);
23518
- } catch (error) {
23519
- Logger.error(`[DocumentManager] ${docId}: releasing a withdrawn binding failed:`, error);
23520
- }
23521
- }
23755
+ await this.releaseUnpublished(docId, opened);
23522
23756
  throw new Error(
23523
23757
  `[DocumentManager] Document ${docId} was not bound: every db3 was unbound (the storage identity changed) while it connected.`
23524
23758
  );
23525
23759
  }
23760
+ /** Release the store a db3 connect opened and did not publish, if it is still the bound one. */
23761
+ async releaseUnpublished(docId, opened) {
23762
+ if (!opened || this.recordLog.storeOf(docId) !== opened || this.connectedDocuments.has(docId)) return;
23763
+ try {
23764
+ await this.modelRegistry.removeDocumentData(docId, this.dbEngine, { skipQueryTableWipe: true });
23765
+ this.ormContext.disposeObserversForDocument(docId);
23766
+ await this.recordLog.disconnect(docId);
23767
+ } catch (error) {
23768
+ Logger.error(`[DocumentManager] ${docId}: releasing an unpublished binding failed:`, error);
23769
+ }
23770
+ }
23526
23771
  async connectDocumentInner(docId, yDoc, permissionHint, options, epoch) {
23527
23772
  const documentFormat = options?.documentFormat ?? 1;
23528
23773
  const existing = this.connectedDocuments.get(docId);
@@ -23549,26 +23794,39 @@ var DocumentManagerImpl = class {
23549
23794
  `[DocumentManager] Connecting document ${docId} with permission: ${permissionHint}`
23550
23795
  );
23551
23796
  let opened = null;
23552
- if (documentFormat === 3) {
23553
- await this.recordLog.assertCanHost(docId);
23554
- await this.withdrawIfOvertaken(docId, epoch, null);
23555
- opened = await this.recordLog.open(docId);
23556
- await this.withdrawIfOvertaken(docId, epoch, opened);
23557
- this.recordLog.setCreatedLocally(docId, options?.createdLocally !== false);
23558
- await this.recordLog.adoptPermission(docId, permissionHint);
23559
- await this.withdrawIfOvertaken(docId, epoch, opened);
23560
- }
23561
- await this.modelRegistry.initializeAllForDocument(
23562
- yDoc,
23563
- this.dbEngine,
23564
- docId,
23565
- permissionHint,
23566
- documentFormat
23567
- );
23568
- if (documentFormat === 3) {
23569
- await this.withdrawIfOvertaken(docId, epoch, opened);
23570
- await this.recordLog.connect(docId);
23571
- await this.withdrawIfOvertaken(docId, epoch, opened);
23797
+ if (documentFormat === 3) this.recordLogConnecting.set(docId, (this.recordLogConnecting.get(docId) ?? 0) + 1);
23798
+ try {
23799
+ if (documentFormat === 3) {
23800
+ await this.recordLog.assertCanHost(docId);
23801
+ await this.withdrawIfOvertaken(docId, epoch, null);
23802
+ opened = await this.recordLog.open(docId);
23803
+ await this.withdrawIfOvertaken(docId, epoch, opened);
23804
+ this.recordLog.setCreatedLocally(docId, options?.createdLocally !== false);
23805
+ if (options?.type) await this.recordLog.seedType(docId, options.type);
23806
+ await this.recordLog.adoptPermission(docId, permissionHint);
23807
+ await this.withdrawIfOvertaken(docId, epoch, opened);
23808
+ }
23809
+ await this.modelRegistry.initializeAllForDocument(
23810
+ yDoc,
23811
+ this.dbEngine,
23812
+ docId,
23813
+ permissionHint,
23814
+ documentFormat
23815
+ );
23816
+ if (documentFormat === 3) {
23817
+ await this.withdrawIfOvertaken(docId, epoch, opened);
23818
+ await this.recordLog.connect(docId);
23819
+ await this.withdrawIfOvertaken(docId, epoch, opened);
23820
+ }
23821
+ } catch (error) {
23822
+ if (opened && this.recordLogConnecting.get(docId) === 1) await this.releaseUnpublished(docId, opened);
23823
+ throw error;
23824
+ } finally {
23825
+ if (documentFormat === 3) {
23826
+ const left = (this.recordLogConnecting.get(docId) ?? 1) - 1;
23827
+ if (left > 0) this.recordLogConnecting.set(docId, left);
23828
+ else this.recordLogConnecting.delete(docId);
23829
+ }
23572
23830
  }
23573
23831
  this.connectedDocuments.set(docId, connectedDoc);
23574
23832
  for (const modelName of this.modelRegistry.getActiveModels().keys()) {
@@ -23589,6 +23847,7 @@ var DocumentManagerImpl = class {
23589
23847
  async rebindRecordLogDocument(docId, yDoc, permissionHint, options, epoch) {
23590
23848
  Logger.info(`[DocumentManager] Rebinding format-3 document ${docId} in place (permission: ${permissionHint})`);
23591
23849
  if (options?.createdLocally !== void 0) this.recordLog.setCreatedLocally(docId, options.createdLocally);
23850
+ if (options?.type) await this.recordLog.seedType(docId, options.type);
23592
23851
  await this.recordLog.adoptPermission(docId, permissionHint);
23593
23852
  await this.modelRegistry.initializeAllForDocument(yDoc, this.dbEngine, docId, permissionHint, 3);
23594
23853
  await this.recordLog.connect(docId);
@@ -23633,6 +23892,12 @@ var DocumentManagerImpl = class {
23633
23892
  onSyncProgress: (listener) => binding.sessions.onSyncProgress(listener),
23634
23893
  onWriteRefused: (listener) => this.ormContext.onRecordLogWriteRefused(listener),
23635
23894
  onDeclared: (listener) => binding.onDeclared(listener),
23895
+ permissionChanged: async (docId, permission) => {
23896
+ if (!binding.storeOf(docId)) return;
23897
+ const connected = this.connectedDocuments.get(docId);
23898
+ if (connected) connected.permissionHint = permission;
23899
+ await binding.permissionChanged(docId, permission);
23900
+ },
23636
23901
  syncIndexes: (docId, indexes) => binding.syncIndexes(docId, indexes),
23637
23902
  storedState: (docId) => binding.probe(docId),
23638
23903
  syncMarks: (docId) => binding.storeOf(docId)?.marks() ?? null,
@@ -24461,6 +24726,7 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
24461
24726
  if (!models || typeof models !== "object") {
24462
24727
  throw new Error("TOML schema must have a [models] section");
24463
24728
  }
24729
+ const isTypeFile = parsed.type !== null && typeof parsed.type === "object" && !Array.isArray(parsed.type);
24464
24730
  const schemas = [];
24465
24731
  for (const [modelName, modelDef] of Object.entries(models)) {
24466
24732
  checkUnknownKeys(
@@ -24471,6 +24737,9 @@ function loadSchemaFromTomlString(tomlString, options = {}) {
24471
24737
  );
24472
24738
  const fields = {};
24473
24739
  const declaredFields = /* @__PURE__ */ new Map();
24740
+ if (isTypeFile && !(modelDef.fields && Object.prototype.hasOwnProperty.call(modelDef.fields, "id"))) {
24741
+ fields.id = { type: "id", autoAssign: true };
24742
+ }
24474
24743
  if (modelDef.fields) {
24475
24744
  for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
24476
24745
  const context = `[models.${modelName}.fields.${fieldName}]`;
@@ -24768,6 +25037,7 @@ init_types();
24768
25037
  init_guess();
24769
25038
  init_condition();
24770
25039
  init_write();
25040
+ init_declared_types();
24771
25041
 
24772
25042
  // src/cli/v2/toml-writer.ts
24773
25043
  function commentLines(comments) {