@forestfuture/active-record 0.9.0 → 0.10.0

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.
@@ -1,5 +1,5 @@
1
- import { $ as FilteredMark, A as authenticateBy, B as RecordState, C as Filtered, Ct as isIgnoringColumns, D as isFiltered, Dt as requireModelName, E as filteredValues, Et as rejectAbstract, F as rejectMissingDigests, G as columnOf, H as state, I as resetPurposeOf, J as requireDefined, K as define, L as resetTokenDefinitions, M as hashPasswords, Mt as staticBelow, N as passwordConfirmations, O as shownKey, Ot as requireTableName, P as passwordFailures, Q as fullMessageOf, R as secretAttributeNames, S as FILTERED, St as inferTableNames, T as defaultFilterAttributes, U as attributeOf, V as linksOf, W as attributesForColumn, X as addFailure, Z as clearErrors, _ as isLocking, _t as declared, a as isGenerated, at as specProblem, b as isThenable, bt as defineModelName, c as methodsOffFixes, ct as generateTokens, d as enumNameProblem, et as inspectCustom, ft as aliasesIn, g as withArticle, gt as declare, h as noMatch, ht as withAttributeNames, i as isBase, it as humanAttributeName, j as defineSecurePasswordMethods, jt as ancestors, k as shownValue$1, kt as tableOwnerModelName, l as defineEnumMethods, lt as expiryAfter, m as castInherited, mt as isAlias, n as defineGeneratedStatics, nt as styled, o as schemaAdapter, ot as defineSecureTokenMethods, p as attributeFor, pt as attributeName, q as initialValues, r as hasSettledAttributes, rt as attributesNamedInMessages, s as settleGenerated, t as defineAttributeAccessors, tt as printed, u as defineEnumStatics, ut as secondsOf, v as lockVersion, vt as declaredByClass, w as boundValue, x as refuseThenable, xt as explainMissingTable, y as checkNormalizedName, yt as seal, z as withSecurePasswords } from "./generated-model-L4WAqgOZ.mjs";
2
- import { $ as UnknownAssociation, A as AssociationNotLoaded, C as pluralize, D as underscore, F as IncompatibleRelation, G as RecordInvalid, H as NotNullViolation, I as InvalidForeignKey, J as RecordNotSaved, K as RecordNotDestroyed, L as InvalidModel, M as CheckViolation, O as AbortAfterPersistence, P as DeleteRestriction, Q as StrictValidationFailed, R as InvalidToken, T as camelize, U as ReadonlyAssociation, V as NoDatabase, X as SoleRecordExceeded, Y as RecordNotUnique, Z as StaleRecord, b as enumValuesOf, c as castValue, d as uncastable, f as writeUntypedValue, g as orderDecimal, i as hexOf, j as CallbackAbort, k as ActiveRecordError, m as zonelessDateTime, nt as abort, q as RecordNotFound, tt as UnknownModelName, w as singularize, y as enumValidations, z as IrreversibleOrder } from "./identifiers-CzqYL_nC.mjs";
1
+ import { $ as FilteredMark, A as authenticateBy, B as RecordState, C as Filtered, Ct as isIgnoringColumns, D as isFiltered, Dt as requireModelName, E as filteredValues, Et as rejectAbstract, F as rejectMissingDigests, G as columnOf, H as state, I as resetPurposeOf, J as requireDefined, K as define, L as resetTokenDefinitions, M as hashPasswords, Mt as staticBelow, N as passwordConfirmations, O as shownKey, Ot as requireTableName, P as passwordFailures, Q as fullMessageOf, R as secretAttributeNames, S as FILTERED, St as inferTableNames, T as defaultFilterAttributes, U as attributeOf, V as linksOf, W as attributesForColumn, X as addFailure, Z as clearErrors, _ as isLocking, _t as declared, a as isGenerated, at as specProblem, b as isThenable, bt as defineModelName, c as methodsOffFixes, ct as generateTokens, d as enumNameProblem, et as inspectCustom, ft as aliasesIn, g as withArticle, gt as declare, h as noMatch, ht as withAttributeNames, i as isBase, it as humanAttributeName, j as defineSecurePasswordMethods, jt as ancestors, k as shownValue$1, kt as tableOwnerModelName, l as defineEnumMethods, lt as expiryAfter, m as castInherited, mt as isAlias, n as defineGeneratedStatics, nt as styled, o as schemaAdapter, ot as defineSecureTokenMethods, p as attributeFor, pt as attributeName, q as initialValues, r as hasSettledAttributes, rt as attributesNamedInMessages, s as settleGenerated, t as defineAttributeAccessors, tt as printed, u as defineEnumStatics, ut as secondsOf, v as lockVersion, vt as declaredByClass, w as boundValue, x as refuseThenable, xt as explainMissingTable, y as checkNormalizedName, yt as seal, z as withSecurePasswords } from "./generated-model-DiQb9_3C.mjs";
2
+ import { $ as IrreversibleOrder, A as orderDecimal, C as incoming, D as refuseReferenceValue, G as CallbackAbort, H as AbortAfterPersistence, J as DeleteRestriction, K as CheckViolation, L as pluralize, N as enumValidations, O as sql, P as enumValuesOf, Q as InvalidToken, R as singularize, S as column, T as isAttributeReference, U as ActiveRecordError, V as underscore, W as AssociationNotLoaded, X as InvalidForeignKey, Y as IncompatibleRelation, Z as InvalidModel, _ as refuseNestedReference, _t as UnknownModelName, at as ReadonlyRecord, b as IncomingReference, c as castValue, ct as RecordNotDestroyed, d as uncastable, dt as RecordNotUnique, f as writeUntypedValue, ft as SoleRecordExceeded, ht as UnknownAssociation, i as hexOf, it as ReadonlyAttribute, lt as RecordNotFound, m as zonelessDateTime, mt as StrictValidationFailed, nt as NotNullViolation, pt as StaleRecord, rt as ReadonlyAssociation, st as RecordInvalid, tt as NoDatabase, ut as RecordNotSaved, v as ColumnReference, vt as abort, w as incomingRefusal, x as SafeSql, y as ColumnValue, z as camelize } from "./identifiers-DRLEguFD.mjs";
3
3
  // src/foreign-keys.ts
4
4
  /**
5
5
  * Gives each declaration its foreign key: the one passed, or else inferred from
@@ -493,92 +493,6 @@ function requireKnownContexts(record, given) {
493
493
  if (name === void 0) return;
494
494
  throw new TypeError(`${nameOf$1(model)} has no validation context "${name}"; list it in static validationContexts`);
495
495
  }
496
- // src/bulk-rows.ts
497
- /** The "[" and "]" around a JSON value's rows. */
498
- const brackets = 2;
499
- /** The "," between two rows of a JSON value. */
500
- const comma = 1;
501
- /**
502
- * `rows` of `names`' values, assigned, in groups whose JSON value is at most `maxBytes` long in
503
- * UTF-8 (all in one when it's undefined); listeners see a filtered attribute as "[FILTERED]".
504
- */
505
- function rowGroups(model, names, rows, maxBytes) {
506
- const jsonRows = rows.map(jsonRowOf(model, names));
507
- if (maxBytes === void 0) return [{
508
- kind: "json",
509
- value: jsonValue(jsonRows)
510
- }];
511
- const groups = [];
512
- let pending = [];
513
- let bytes = brackets;
514
- const flush = () => {
515
- if (pending.length > 0) groups.push({
516
- kind: "json",
517
- value: jsonValue(pending)
518
- });
519
- pending = [];
520
- };
521
- for (const row of jsonRows) {
522
- const size = utf8Length(row.text);
523
- if (brackets + size > maxBytes) {
524
- flush();
525
- groups.push({
526
- kind: "values",
527
- row: row.values
528
- });
529
- continue;
530
- }
531
- if (pending.length > 0 && bytes + comma + size > maxBytes) flush();
532
- bytes = pending.length === 0 ? brackets + size : bytes + comma + size;
533
- pending.push(row);
534
- }
535
- flush();
536
- return groups;
537
- }
538
- /** A function that writes a row of `names`' values as JSON, and as listeners see it. */
539
- function jsonRowOf(model, names) {
540
- const attributes = names.map((name) => attributeFor(model, name));
541
- const filtered = names.map((name) => isFiltered(model, name));
542
- const hiding = filtered.includes(true);
543
- return (values) => {
544
- const stored = values.map((value, index) => inJson(attributes[index].store(value)));
545
- const text = JSON.stringify(stored);
546
- if (!hiding) return {
547
- values,
548
- text,
549
- shown: text
550
- };
551
- return {
552
- values,
553
- text,
554
- shown: JSON.stringify(stored.map((cell, index) => filtered[index] ? FILTERED : cell))
555
- };
556
- };
557
- }
558
- /** Rows as one JSON value, which listeners see with filtered attributes hidden. */
559
- function jsonValue(rows) {
560
- const json = `[${rows.map(({ text }) => text).join(",")}]`;
561
- if (rows.every(({ text, shown }) => text === shown)) return json;
562
- return new Filtered(json, `[${rows.map(({ shown }) => shown).join(",")}]`);
563
- }
564
- /**
565
- * `text`'s length in UTF-8 bytes, counted without encoding a copy of it. A code unit below
566
- * U+0080 is one byte, below U+0800 two, and any other three, except that a surrogate pair is four
567
- * between its two units. JSON text has no lone surrogates: `JSON.stringify` escapes them.
568
- */
569
- function utf8Length(text) {
570
- let bytes = text.length;
571
- for (let index = 0; index < text.length; index++) {
572
- const unit = text.charCodeAt(index);
573
- if (unit < 128) continue;
574
- bytes += unit < 2048 || unit >= 55296 && unit <= 57343 ? 1 : 2;
575
- }
576
- return bytes;
577
- }
578
- /** A stored cell as a bulk write's JSON holds it: bytes as hex text, which JSON has no form for (#20). */
579
- function inJson(cell) {
580
- return cell instanceof Uint8Array ? hexOf(cell) : cell;
581
- }
582
496
  // src/comparisons.ts
583
497
  /** @internal The library's key for reading a Comparison's parts. */
584
498
  const comparisonParts = Symbol("comparisonParts");
@@ -685,59 +599,6 @@ function compileEquality(dialect, { column, attribute }, value, params) {
685
599
  if (value.includes(null)) parts.push(`${column} IS NULL`);
686
600
  return parts.length > 0 ? `(${parts.join(" OR ")})` : NOTHING;
687
601
  }
688
- // src/sql.ts
689
- /**
690
- * A SQL fragment built with the `sql` tagged template (ADR-0006). The template
691
- * text is written by the developer; every interpolated value is bound as a
692
- * parameter and never becomes SQL text.
693
- */
694
- var SafeSql = class {
695
- strings;
696
- values;
697
- /** @internal Use the `sql` tag instead. */
698
- constructor(strings, values) {
699
- this.strings = strings;
700
- this.values = values;
701
- }
702
- };
703
- function sql(strings, ...values) {
704
- return new SafeSql([...strings], values);
705
- }
706
- /** A reference to an attribute's column, resolved against the query's Model when compiled. */
707
- var ColumnReference = class {
708
- attribute;
709
- /** @internal Use `column()` instead. */
710
- constructor(attribute) {
711
- this.attribute = attribute;
712
- }
713
- /**
714
- * A value of this attribute for a fragment, converted as the attribute stores it: a `Date`
715
- * as the integer of an attribute kept as a Unix time, a boolean as 0 or 1, and so on. It's
716
- * still a bound parameter. Without it, a value has no attribute to say how it's stored (#142).
717
- */
718
- value(value) {
719
- return new ColumnValue(this.attribute, value);
720
- }
721
- };
722
- /** A value of an attribute, from `column(attribute).value(value)`, converted when compiled. */
723
- var ColumnValue = class {
724
- attribute;
725
- /** What was given, before it's cast as an assigned value of the attribute. */
726
- assigned;
727
- /** @internal Use `column(attribute).value(value)` instead. */
728
- constructor(attribute, assigned) {
729
- this.attribute = attribute;
730
- this.assigned = assigned;
731
- }
732
- };
733
- /** Whether a fragment's interpolated value names an attribute: a column, or a typed value. */
734
- function isAttributeReference(value) {
735
- return value instanceof ColumnReference || value instanceof ColumnValue;
736
- }
737
- /** Names the column of `attribute` inside an `sql` fragment, quoted and mapped (ADR-0004). */
738
- function column(attribute) {
739
- return new ColumnReference(attribute);
740
- }
741
602
  // src/query.ts
742
603
  /** @internal The library's key for the query a Relation describes. */
743
604
  const queryOf = Symbol("queryOf");
@@ -816,13 +677,15 @@ const SHAPE_CLAUSES = [
816
677
  "order",
817
678
  "limit",
818
679
  "offset",
819
- "distinct"
680
+ "distinct",
681
+ "readonly"
820
682
  ];
821
683
  /** Whether two descriptions agree on one shape clause, by that clause's own rule. */
822
684
  function isSameClause(clause, a, b) {
823
685
  switch (clause) {
824
686
  case "select": return isSameList(a.select, b.select, (x, y) => x === y);
825
687
  case "order": return isSameList(a.order, b.order, isSameOrderTerm);
688
+ case "readonly": return (a.readonly ?? false) === (b.readonly ?? false);
826
689
  default: return Object.is(a[clause], b[clause]);
827
690
  }
828
691
  }
@@ -907,6 +770,7 @@ function merged(a, b) {
907
770
  };
908
771
  for (const clause of SHAPE_CLAUSES) if (isSet(b, clause)) Object.assign(result, { [clause]: b[clause] });
909
772
  if (b.reordered) result.reordered = true;
773
+ if (b.readonly !== void 0) result.readonly = b.readonly;
910
774
  return result;
911
775
  }
912
776
  /** What `merge()` unions of `b`'s with `a`'s: includes, joins, `createWith`, and owner links. */
@@ -1202,54 +1066,6 @@ function compileReturning(model, attributes) {
1202
1066
  return ` RETURNING ${columnsIn(unqualifiedSource(model), attributes)}`;
1203
1067
  }
1204
1068
  /**
1205
- * `INSERT` of several rows, all with the attributes `names`, bound as one JSON parameter, which
1206
- * the dialect reads them from: one statement and one bound value, whatever the number of rows,
1207
- * within D1's limit of 100 bound parameters per statement. Rows whose JSON would pass the
1208
- * dialect's `maxValueBytes` take several statements, and a row whose JSON alone would pass it
1209
- * binds each of its values apart, as `compileInsert` does (#392).
1210
- */
1211
- function compileInsertRows(dialect, model, { names, rows, conflict, returning }) {
1212
- const attributes = names.map((name) => attributeFor(model, name));
1213
- const columns = attributes.map(({ column }) => quoteIdentifier(column)).join(", ");
1214
- const table = quoteIdentifier(model.table);
1215
- const { select, from } = dialect.bulkRows(table, attributes);
1216
- const end = compileConflict(model, names, conflict) + compileReturning(model, returning);
1217
- return rowGroups(model, names, rows, dialect.maxValueBytes).map((group) => {
1218
- if (group.kind === "json") return {
1219
- sql: `INSERT INTO ${table} (${columns}) SELECT ${select} FROM ${from} WHERE true${end}`,
1220
- params: [group.value],
1221
- model
1222
- };
1223
- const params = [];
1224
- const values = compileValues(attributes, group.row, params);
1225
- return {
1226
- sql: `INSERT INTO ${table} ${values}${end}`,
1227
- params,
1228
- model
1229
- };
1230
- });
1231
- }
1232
- /**
1233
- * `ON CONFLICT DO NOTHING`, or `ON CONFLICT (…) DO UPDATE SET` the `update` attributes (every
1234
- * inserted one by default) except the `uniqueBy` ones and `createdAt`,
1235
- * `WHERE` the clashing row already has the new row's `ownedBy` values (#451).
1236
- */
1237
- function compileConflict(model, names, conflict) {
1238
- if (conflict === void 0) return "";
1239
- if (conflict.kind === "skip") return " ON CONFLICT DO NOTHING";
1240
- const column = (name) => quoteIdentifier(attributeFor(model, name).column);
1241
- const target = conflict.uniqueBy.map(column).join(", ");
1242
- const updated = (conflict.update ?? names).filter((name) => !conflict.uniqueBy.includes(name) && name !== "createdAt");
1243
- if (updated.length === 0) return ` ON CONFLICT (${target}) DO NOTHING`;
1244
- return ` ON CONFLICT (${target}) DO UPDATE SET ${updated.map((name) => `${column(name)} = excluded.${column(name)}`).join(", ")}${compileOwnedBy(model, conflict.ownedBy, column)}`;
1245
- }
1246
- /** ` WHERE "t"."a" = excluded."a" AND …`: the clashing row already has the new row's values. */
1247
- function compileOwnedBy(model, ownedBy, column) {
1248
- if (ownedBy.length === 0) return "";
1249
- const table = quoteIdentifier(model.table);
1250
- return ` WHERE ${ownedBy.map((name) => `${table}.${column(name)} = excluded.${column(name)}`).join(" AND ")}`;
1251
- }
1252
- /**
1253
1069
  * `UPDATE … SET … WHERE <primary key> = ?` for the given attribute values, or an `sql`
1254
1070
  * fragment's sets, `RETURNING` the `returning` attributes. `storedKey` is the key as stored in
1255
1071
  * D1 (the row's key before any change to it), so it's bound as-is.
@@ -1530,20 +1346,30 @@ function compilePagination(dialect, { limit, offset }, params) {
1530
1346
  function compileFragment(fragment, source, params) {
1531
1347
  let text = fragment.strings[0] ?? "";
1532
1348
  fragment.values.forEach((value, index) => {
1533
- if (value instanceof ColumnReference) text += columnIn(source, value.attribute);
1534
- else if (value instanceof ColumnValue) {
1535
- const attribute = attributeFor(source.model, value.attribute);
1536
- attribute.bindCells(params, attribute.storeNormalized(value.assigned));
1537
- text += "\0";
1538
- } else {
1539
- params.push(writeUntypedValue(value));
1540
- text += "\0";
1541
- }
1349
+ text += compileFragmentValue(value, source, params);
1542
1350
  text += fragment.strings[index + 1] ?? "";
1543
1351
  });
1544
1352
  return text;
1545
1353
  }
1354
+ /** One of a fragment's values: a column, or an incoming value, as SQL, or a value bound. */
1355
+ function compileFragmentValue(value, source, params) {
1356
+ if (value instanceof ColumnReference) return columnIn(source, value.attribute);
1357
+ if (value instanceof IncomingReference) return incomingColumn(source, value.attribute);
1358
+ if (value instanceof ColumnValue) {
1359
+ const attribute = attributeFor(source.model, value.attribute);
1360
+ attribute.bindCells(params, attribute.storeNormalized(value.assigned));
1361
+ } else params.push(writeUntypedValue(value));
1362
+ return "\0";
1363
+ }
1364
+ /** `excluded."column"`: the row an upsert writes, which only its `onDuplicate` reads (#531). */
1365
+ function incomingColumn(source, attribute) {
1366
+ if (source.allowsIncoming !== true) throw incomingRefusal(attribute);
1367
+ return `excluded.${quoteIdentifier(attributeFor(source.model, attribute).column)}`;
1368
+ }
1546
1369
  // src/fragment-guard.ts
1370
+ function isRowValueReference(value) {
1371
+ return value instanceof ColumnReference || value instanceof IncomingReference;
1372
+ }
1547
1373
  /** A comparison operator, alone between two interpolations. */
1548
1374
  const comparison$1 = /^\s*(?:=|==|<>|!=|<=|>=|<|>)\s*$/;
1549
1375
  /** `BETWEEN` or `NOT BETWEEN`, alone before the first bound. */
@@ -1556,23 +1382,23 @@ function bareDatetimeKind(value) {
1556
1382
  if (typeof value !== "string") return void 0;
1557
1383
  return castValue({ type: "datetime" }, value) !== uncastable || zonelessDateTime.test(value) ? "string" : void 0;
1558
1384
  }
1559
- /** The column a value at `index` follows, with only a comparison or `BETWEEN` between them. */
1560
- function columnBefore(fragment, index) {
1385
+ /** The column or incoming value a value at `index` follows, with only a comparison or `BETWEEN` between them. */
1386
+ function referenceBefore(fragment, index) {
1561
1387
  const { strings, values } = fragment;
1562
1388
  const between = strings[index] ?? "";
1563
1389
  const before = values[index - 1];
1564
- if (before instanceof ColumnReference && (comparison$1.test(between) || betweenLower.test(between))) return before;
1390
+ if (isRowValueReference(before) && (comparison$1.test(between) || betweenLower.test(between))) return before;
1565
1391
  const column = values[index - 2];
1566
- return betweenUpper.test(between) && betweenLower.test(strings[index - 1] ?? "") && column instanceof ColumnReference ? column : void 0;
1392
+ return betweenUpper.test(between) && betweenLower.test(strings[index - 1] ?? "") && isRowValueReference(column) ? column : void 0;
1567
1393
  }
1568
- /** The column a value at `index` precedes: after a comparison, or the bounds of `BETWEEN`. */
1569
- function columnAfter(fragment, index) {
1394
+ /** The column or incoming value a value at `index` precedes: after a comparison, or the bounds of `BETWEEN`. */
1395
+ function referenceAfter(fragment, index) {
1570
1396
  const { strings, values } = fragment;
1571
1397
  const between = strings[index + 1] ?? "";
1572
1398
  const after = values[index + 1];
1573
- if (after instanceof ColumnReference && (comparison$1.test(between) || betweenLower.test(between))) return after;
1399
+ if (isRowValueReference(after) && (comparison$1.test(between) || betweenLower.test(between))) return after;
1574
1400
  const upper = values[index + 2];
1575
- return betweenLower.test(between) && betweenUpper.test(strings[index + 2] ?? "") && upper instanceof ColumnReference ? upper : void 0;
1401
+ return betweenLower.test(between) && betweenUpper.test(strings[index + 2] ?? "") && isRowValueReference(upper) ? upper : void 0;
1576
1402
  }
1577
1403
  /**
1578
1404
  * Throws `TypeError` when a fragment puts a bare date directly beside the column of an attribute
@@ -1583,7 +1409,7 @@ function refuseBareDates(model, fragment) {
1583
1409
  fragment.values.forEach((value, index) => {
1584
1410
  const kind = bareDatetimeKind(value);
1585
1411
  if (kind === void 0) return;
1586
- const reference = columnBefore(fragment, index) ?? columnAfter(fragment, index);
1412
+ const reference = referenceBefore(fragment, index) ?? referenceAfter(fragment, index);
1587
1413
  if (reference === void 0) return;
1588
1414
  const { storage } = columnOf(model, reference.attribute);
1589
1415
  if (storage === void 0) return;
@@ -1625,11 +1451,13 @@ function attributeOrder(attribute, value, method) {
1625
1451
  * A fragment's `column()` references must name declared attributes, and so must its typed
1626
1452
  * values, which must also be values those attributes can hold, so a mistake surfaces where the
1627
1453
  * fragment is written, not when the query runs (#142). A bare date beside an integer-stored
1628
- * column is refused too (#149).
1454
+ * column is refused too (#149). So is `incoming()`, unless it's an upsert's `onDuplicate`
1455
+ * (#531).
1629
1456
  */
1630
- function checkFragment(model, fragment) {
1457
+ function checkFragment(model, fragment, { allowsIncoming = false } = {}) {
1631
1458
  for (const value of fragment.values) {
1632
1459
  if (!isAttributeReference(value)) continue;
1460
+ if (value instanceof IncomingReference && !allowsIncoming) throw incomingRefusal(value.attribute);
1633
1461
  columnOf(model, value.attribute);
1634
1462
  if (value instanceof ColumnValue) attributeFor(model, value.attribute).cast(value.assigned);
1635
1463
  }
@@ -1652,9 +1480,19 @@ function checkConditions(model, conditions, method) {
1652
1480
  for (const [name, value] of Object.entries(conditions)) {
1653
1481
  const { type } = columnOf(model, name);
1654
1482
  rejectUndefined(value, name, method);
1483
+ for (const each of conditionValues(value)) {
1484
+ refuseReferenceValue(each, `${method}() gives ${name}`);
1485
+ if (type === "json") refuseNestedReference(each, `${method}() gives ${name}`);
1486
+ }
1655
1487
  if (value instanceof Comparison) requireOrdered$1(type, name, method);
1656
1488
  }
1657
1489
  }
1490
+ /** A condition's values: a list's items, a comparison's values, or the value itself. */
1491
+ function conditionValues(value) {
1492
+ if (Array.isArray(value)) return value;
1493
+ if (value instanceof Comparison) return value[comparisonParts].values;
1494
+ return [value];
1495
+ }
1658
1496
  /** Attribute changes for `updateAll`, checked like conditions: declared, and not undefined. */
1659
1497
  function checkChanges(model, changes) {
1660
1498
  checkConditions(model, changes, "updateAll");
@@ -1688,16 +1526,89 @@ function returnedNames(model, returning) {
1688
1526
  }
1689
1527
  /**
1690
1528
  * An upsert's conflict: update, matching on `uniqueBy` (the primary key by default), a row
1691
- * that already has the new row's `ownedBy` values (#451).
1529
+ * that already has the new row's `ownedBy` values (#451), only `updateOnly`'s attributes when
1530
+ * it's given (#36).
1692
1531
  */
1693
- function updateOn(model, options, ownedBy) {
1532
+ function updateOn(model, options, { ownedBy, method }) {
1694
1533
  const uniqueBy = [options.uniqueBy ?? model.primaryKey].flat();
1695
1534
  for (const name of uniqueBy) columnOf(model, name);
1696
- return {
1535
+ if (options.onDuplicate !== void 0) {
1536
+ if (options.updateOnly !== void 0) throw new TypeError(`${method}() takes updateOnly or onDuplicate, not both`);
1537
+ return {
1538
+ kind: "update",
1539
+ uniqueBy,
1540
+ ownedBy,
1541
+ set: onDuplicateSets(model, options.onDuplicate, {
1542
+ uniqueBy,
1543
+ ownedBy,
1544
+ method
1545
+ })
1546
+ };
1547
+ }
1548
+ if (options.updateOnly === void 0) return {
1697
1549
  kind: "update",
1698
1550
  uniqueBy,
1699
1551
  ownedBy
1700
1552
  };
1553
+ return {
1554
+ kind: "update",
1555
+ uniqueBy,
1556
+ ownedBy,
1557
+ update: updatedNames(model, [options.updateOnly].flat(), {
1558
+ uniqueBy,
1559
+ method,
1560
+ option: "updateOnly",
1561
+ kept: []
1562
+ })
1563
+ };
1564
+ }
1565
+ /**
1566
+ * `onDuplicate`'s attributes, by their own names, checked as `updateOnly`'s are, and what each
1567
+ * is set to: its fragment, checked, or its value cast and normalized as an assigned value is
1568
+ * (#531). It can't name an owner's key, `ownedBy`, so it can't give a row to another owner.
1569
+ */
1570
+ function onDuplicateSets(model, given, { uniqueBy, ownedBy, method }) {
1571
+ if (typeof given !== "object" || given === null || Array.isArray(given) || given instanceof SafeSql) throw new TypeError(`${method}() onDuplicate takes an object of attributes, each an sql\`…\` fragment or a value`);
1572
+ const entries = Object.entries(given);
1573
+ const names = updatedNames(model, entries.map(([name]) => name), {
1574
+ uniqueBy,
1575
+ method,
1576
+ option: "onDuplicate",
1577
+ kept: ownedBy
1578
+ });
1579
+ return entries.map(([given, value], index) => {
1580
+ const name = names[index];
1581
+ refuseReferenceValue(value, `${method}() onDuplicate gives ${given}`);
1582
+ if (!(value instanceof SafeSql)) return {
1583
+ name,
1584
+ value: attributeFor(model, name).assigned(value)
1585
+ };
1586
+ checkFragment(model, value, { allowsIncoming: true });
1587
+ return {
1588
+ name,
1589
+ value
1590
+ };
1591
+ });
1592
+ }
1593
+ /**
1594
+ * The attributes `updateOnly` or `onDuplicate` names, by their own names, checked: each one an
1595
+ * attribute an update can write, not one of the owner's `kept` keys, and at least one (#36, #531).
1596
+ */
1597
+ function updatedNames(model, given, { uniqueBy, method, option, kept }) {
1598
+ if (given.length === 0) throw new TypeError(`${method}() ${option} names no attributes; to leave a clashing row as it is, use ${method === "upsert" ? "insert(row" : "insertAll(rows"}, { onDuplicate: "skip" })`);
1599
+ const matched = new Set(uniqueBy.map((name) => attributeName(model, name)));
1600
+ return given.map((name) => {
1601
+ const own = attributeName(model, name);
1602
+ const refusal = kept.includes(own) ? "which its owner's records keep" : updateRefusal(model, own, matched);
1603
+ if (refusal !== void 0) throw new TypeError(`${method}() ${option} can't name ${name}, ${refusal}`);
1604
+ return own;
1605
+ });
1606
+ }
1607
+ /** Why an upsert can't update `name` on a clash, if it can't. */
1608
+ function updateRefusal(model, name, matched) {
1609
+ if (columnOf(model, name).readonly === true) return "which is read-only";
1610
+ if (matched.has(name)) return "which uniqueBy matches on";
1611
+ if (name === "createdAt") return "which an update keeps";
1701
1612
  }
1702
1613
  /** The query a write statement targets; rows from `distinct()` have no identity to write to. */
1703
1614
  function writableQuery(query, method) {
@@ -1790,6 +1701,61 @@ function normalizedValue(attribute, value) {
1790
1701
  function assignedValues(model, values) {
1791
1702
  return Object.fromEntries(Object.entries(values).map(([name, value]) => [name, attributeFor(model, name).assigned(value)]));
1792
1703
  }
1704
+ // src/readonly-records.ts
1705
+ /**
1706
+ * Refuses `action` on a read-only record, before its validation, callbacks or statements; and a
1707
+ * save of a persisted record whose read-only attribute changed without being assigned, in place.
1708
+ */
1709
+ function requireWritable(record, action) {
1710
+ if (record[state].isReadonly) throw new ReadonlyRecord(record, action);
1711
+ if (action === "save") requireReadonlyAttributesKept(record);
1712
+ }
1713
+ /** The attributes every save writes, which can't be read-only: its timestamp and lock version. */
1714
+ const writtenBySaves = ["updatedAt", lockVersion];
1715
+ /** A read-only attribute every save writes anyway, as a message, or undefined. */
1716
+ function readonlyProblem(where, name, readonly) {
1717
+ if (readonly !== true || !writtenBySaves.includes(name)) return void 0;
1718
+ return `${where} is written by every save, so it can't be readonly`;
1719
+ }
1720
+ /** Refuses a write straight to a row that sets a read-only attribute, `names`, before it's sent. */
1721
+ function requireWritableColumns(model, names) {
1722
+ for (const given of names) {
1723
+ const name = attributeName(model, given);
1724
+ if (model.attributeDefinitions.get(name)?.readonly === true) throw new ReadonlyAttribute(model.name, name);
1725
+ }
1726
+ }
1727
+ /** A persisted record's read-only attributes, as it was loaded or created, or `ReadonlyAttribute`. */
1728
+ function requireReadonlyAttributesKept(record) {
1729
+ const recordState = record[state];
1730
+ if (!recordState.isPersisted) return;
1731
+ requireWritableColumns(record.constructor, recordState.changedNames());
1732
+ }
1733
+ /**
1734
+ * Refuses a save that would write a read-only record through its owner's associations: saving or
1735
+ * destroying one marked for destruction. Checked before the owner's validation and callbacks.
1736
+ */
1737
+ function requireSavesWritable(records) {
1738
+ for (const record of records) {
1739
+ requireWritable(record, record[state].isMarkedForDestruction ? "destroy" : "save");
1740
+ requireLinksWritable(record);
1741
+ }
1742
+ }
1743
+ /**
1744
+ * The read-only foreign keys a save would fill once a new record is inserted, refused before:
1745
+ * a persisted record's, pointed at a new one, and a persisted record's its new owner would fill.
1746
+ */
1747
+ function requireLinksWritable(record) {
1748
+ const model = record.constructor;
1749
+ if (record[state].isPersisted) for (const [name, target] of record[state].autosaves.allBelongsTo()) {
1750
+ if (!target[state].isNew) continue;
1751
+ requireWritableColumns(model, [resolveAssociation(model, name).ownerAttribute]);
1752
+ }
1753
+ if (!record[state].isNew) return;
1754
+ for (const { association, record: linked, keepsKey, destroys } of autosavedAfter(record, /* @__PURE__ */ new Set())) {
1755
+ if (keepsKey || destroys || !linked[state].isPersisted) continue;
1756
+ requireWritableColumns(modelOf(linked), [association.definition.foreignKey]);
1757
+ }
1758
+ }
1793
1759
  // src/constraints.ts
1794
1760
  /** Each kind's class, and a readable label, since bundlers may rename the error classes. */
1795
1761
  const VIOLATIONS = {
@@ -1855,6 +1821,26 @@ function runWithStore(store, fn) {
1855
1821
  storage$1 ??= newStorage();
1856
1822
  return storage$1.run(store, fn);
1857
1823
  }
1824
+ /**
1825
+ * Empties every request cache in the running `withDatabase` call's request (#218), a nested call's
1826
+ * included: a write on any Database inside it may change rows another of its databases cached,
1827
+ * the same database through another handle included.
1828
+ */
1829
+ function clearRequestCaches() {
1830
+ for (const cache of requestStore()?.caches ?? []) cache.clear();
1831
+ }
1832
+ /**
1833
+ * Runs `fn` with its reads, and the reads it awaits, neither answered from the request caches nor
1834
+ * kept in them: batch iteration's, each a different query that would only fill them (#218). Its
1835
+ * writes still clear them.
1836
+ */
1837
+ function withoutRequestCache(fn) {
1838
+ const store = requestStore();
1839
+ return store === void 0 ? fn() : runWithStore({
1840
+ ...store,
1841
+ uncached: true
1842
+ }, fn);
1843
+ }
1858
1844
  // src/executor.ts
1859
1845
  /**
1860
1846
  * Calls a query listener, which never changes the query's outcome: a listener that throws is
@@ -1888,11 +1874,13 @@ var DatabaseExecutor = class {
1888
1874
  adapter;
1889
1875
  #driver;
1890
1876
  #onQuery;
1877
+ #cachesRequests;
1891
1878
  #origin = "connect";
1892
- constructor(adapter, driver, onQuery) {
1879
+ constructor(adapter, driver, onQuery, cache = {}) {
1893
1880
  this.adapter = adapter;
1894
1881
  this.#driver = driver;
1895
1882
  this.#onQuery = onQuery;
1883
+ this.#cachesRequests = cache.request !== false;
1896
1884
  }
1897
1885
  get dialect() {
1898
1886
  return this.adapter.dialect;
@@ -1926,18 +1914,55 @@ var DatabaseExecutor = class {
1926
1914
  #scope() {
1927
1915
  return requestStore()?.scopes.get(this)?.held;
1928
1916
  }
1917
+ /** The request cache of the running `withDatabase` scope a statement is sent in, if any. */
1918
+ #cache() {
1919
+ if (!this.#cachesRequests) return void 0;
1920
+ const store = requestStore();
1921
+ if (store?.uncached === true) return void 0;
1922
+ const scope = store?.scopes.get(this);
1923
+ return scope === void 0 || scope.hasEnded ? void 0 : scope.cache;
1924
+ }
1929
1925
  /** Runs one statement and resolves to its rows. */
1930
1926
  async all(query) {
1931
- return (await this.#one(this.#sendable(query))).rows;
1927
+ return (await this.#readOne(this.#sendable(query))).rows;
1928
+ }
1929
+ /** Sends one read, unless the request cache has its answer, or an identical read is in flight. */
1930
+ async #readOne(query) {
1931
+ const cache = this.#cache();
1932
+ const cached = cache?.get(query);
1933
+ if (cached === void 0) {
1934
+ const answer = this.#one(query);
1935
+ cache?.set(query, answer);
1936
+ return answer;
1937
+ }
1938
+ const result = await cached;
1939
+ this.#reportCached(query);
1940
+ return result;
1932
1941
  }
1933
1942
  /** Runs one statement for its effect and resolves to its result. */
1934
1943
  async run(query) {
1935
- return this.#one(this.#sendable(query));
1944
+ return this.#writing(() => this.#one(this.#sendable(query)));
1936
1945
  }
1937
1946
  /** Runs reads together and resolves to each one's result. */
1938
1947
  async read(statements) {
1939
1948
  const sent = statements.map((statement) => this.#sendable(statement));
1940
- return this.#together(sent, () => this.#driver.read(sent, this.#scope()));
1949
+ const cache = this.#cache();
1950
+ if (cache === void 0) return this.#readTogether(sent);
1951
+ const hits = sent.map((statement) => cache.get(statement));
1952
+ const missing = sent.filter((_, index) => hits[index] === void 0);
1953
+ const fetched = this.#readTogether(missing);
1954
+ missing.forEach((statement, index) => cache.set(statement, fetched.then((results) => results[index])));
1955
+ const answers = await Promise.all(hits.map((hit) => hit ?? Promise.resolve(null)));
1956
+ sent.forEach((statement, index) => {
1957
+ if (hits[index] !== void 0) this.#reportCached(statement);
1958
+ });
1959
+ const results = await fetched;
1960
+ let next = 0;
1961
+ return answers.map((answer) => answer ?? results[next++]);
1962
+ }
1963
+ /** Sends reads together, unless there are none. */
1964
+ #readTogether(statements) {
1965
+ return this.#together(statements, () => this.#driver.read(statements, this.#scope()));
1941
1966
  }
1942
1967
  /** `query` as it's sent and reported: with its database's placeholders. */
1943
1968
  #sendable(query) {
@@ -1973,8 +1998,20 @@ var DatabaseExecutor = class {
1973
1998
  async write(statements) {
1974
1999
  const sent = statements.map((statement) => this.#sendable(statement));
1975
2000
  const [only] = sent;
1976
- if (sent.length === 1 && only !== void 0) return [await this.#one(only)];
1977
- return this.#together(sent, () => this.#driver.write(sent, this.#scope()));
2001
+ if (sent.length === 1 && only !== void 0) return [await this.#writing(() => this.#one(only))];
2002
+ return this.#writing(() => this.#together(sent, () => this.#driver.write(sent, this.#scope())));
2003
+ }
2004
+ /**
2005
+ * Sends a write, clearing the request caches before it's sent and again once it settles, failed
2006
+ * or not: a read sent meanwhile may have read the rows before it, so its answer isn't kept.
2007
+ */
2008
+ async #writing(send) {
2009
+ clearRequestCaches();
2010
+ try {
2011
+ return await send();
2012
+ } finally {
2013
+ clearRequestCaches();
2014
+ }
1978
2015
  }
1979
2016
  async #one(query, mayRetry = true) {
1980
2017
  const started = performance.now();
@@ -2000,6 +2037,13 @@ var DatabaseExecutor = class {
2000
2037
  const { adapter } = this;
2001
2038
  return adapter.refusal(error) ?? explainMissingTable(adapter, translateConstraintError(adapter, error, models), models);
2002
2039
  }
2040
+ /** Reports a read answered from the request cache: no time, and no `meta`. */
2041
+ #reportCached(statement) {
2042
+ this.#report(statement, {
2043
+ durationMs: 0,
2044
+ cached: true
2045
+ });
2046
+ }
2003
2047
  /** Reports a statement to the database's listener, then to its Model's (`static onQuery`). */
2004
2048
  #report({ sql, params, model }, outcome) {
2005
2049
  const event = {
@@ -2333,8 +2377,7 @@ function addToCount(record, attribute, by) {
2333
2377
  const recordState = record[state];
2334
2378
  if (recordState.isDestroyed || !(attribute in recordState.attributes())) return;
2335
2379
  const count = recordState.read(attribute);
2336
- recordState.write(attribute, (typeof count === "number" ? count : 0) + by);
2337
- recordState.commitColumns([attribute]);
2380
+ recordState.takeStored(attribute, (typeof count === "number" ? count : 0) + by);
2338
2381
  }
2339
2382
  /**
2340
2383
  * `counter`'s change by `by` on the target the record's row points at, found by the row's key
@@ -2426,46 +2469,238 @@ function typeCondition(owner, { attribute, value }, params) {
2426
2469
  type.bind(params, value);
2427
2470
  return `${quoteIdentifier(type.column)} = `;
2428
2471
  }
2429
- // src/timestamps.ts
2430
- /** Whether the Model declares `name` as a datetime attribute, which turns its timestamp on. */
2431
- function hasTimestamp(model, name) {
2432
- return model.attributeDefinitions.get(name)?.type === "datetime";
2433
- }
2434
- /**
2435
- * The timestamps to add to a write: `createdAt` and `updatedAt` on insert, `updatedAt` on
2436
- * update. Never one the write already assigns.
2437
- */
2438
- function timestampsFor(model, write, own) {
2439
- const now = /* @__PURE__ */ new Date();
2440
- const assigned = new Set(own.map(([name]) => name));
2441
- return (write === "insert" ? ["createdAt", "updatedAt"] : ["updatedAt"]).filter((name) => hasTimestamp(model, name) && !assigned.has(name)).map((name) => [name, now]);
2442
- }
2443
- // src/statement.ts
2444
- /** @internal The library's key for what `db.batch` needs from a Statement. */
2445
- const statementParts = Symbol("statementParts");
2446
- const noRows = () => [];
2472
+ // src/bulk-rows.ts
2473
+ /** The "[" and "]" around a JSON value's rows. */
2474
+ const brackets = 2;
2475
+ /** The "," between two rows of a JSON value. */
2476
+ const comma = 1;
2447
2477
  /**
2448
- * A bulk write prepared in a batch, by a Batch's methods (`b.insert`, `b.updateAll`,
2449
- * `b.deleteAll`, …). It runs on the Database it was built from, and skips validations,
2450
- * callbacks and hydration. It has no `then`, so it's never run by being awaited.
2478
+ * `rows` of `names`' values, assigned, in groups whose JSON value is at most `maxBytes` long in
2479
+ * UTF-8 (all in one when it's undefined); listeners see a filtered attribute as "[FILTERED]".
2451
2480
  */
2452
- var Statement = class Statement {
2453
- #executor;
2454
- #queries;
2455
- #landed;
2456
- #rows;
2457
- /** Queries sent before its own, in the same batch, whose results aren't its own (#61). */
2458
- #preceding = [];
2459
- /** How many rows its own queries' results say it changed (#61): their `rowsAffected` sum. */
2460
- #affected = rowsAffectedOf;
2461
- /**
2462
- * @internal Statements are built by a Relation's bulk writes, as one query or several sent
2463
- * together (a bulk write past the database's cap on one value, #392). `landed` runs once D1
2464
- * has written it, alone or in a batch (a hasMany's clears what its owner has loaded, #187),
2465
- * with its queries' results, and `rows` reads what it returned.
2466
- */
2467
- constructor(executor, queries, landed = () => {}, rows = noRows) {
2468
- this.#executor = executor;
2481
+ function rowGroups(model, names, rows, maxBytes) {
2482
+ const jsonRows = rows.map(jsonRowOf(model, names));
2483
+ if (maxBytes === void 0) return [{
2484
+ kind: "json",
2485
+ value: jsonValue(jsonRows)
2486
+ }];
2487
+ const groups = [];
2488
+ let pending = [];
2489
+ let bytes = brackets;
2490
+ const flush = () => {
2491
+ if (pending.length > 0) groups.push({
2492
+ kind: "json",
2493
+ value: jsonValue(pending)
2494
+ });
2495
+ pending = [];
2496
+ };
2497
+ for (const row of jsonRows) {
2498
+ const size = utf8Length(row.text);
2499
+ if (brackets + size > maxBytes) {
2500
+ flush();
2501
+ groups.push({
2502
+ kind: "values",
2503
+ row: row.values
2504
+ });
2505
+ continue;
2506
+ }
2507
+ if (pending.length > 0 && bytes + comma + size > maxBytes) flush();
2508
+ bytes = pending.length === 0 ? brackets + size : bytes + comma + size;
2509
+ pending.push(row);
2510
+ }
2511
+ flush();
2512
+ return groups;
2513
+ }
2514
+ /** A function that writes a row of `names`' values as JSON, and as listeners see it. */
2515
+ function jsonRowOf(model, names) {
2516
+ const attributes = names.map((name) => attributeFor(model, name));
2517
+ const filtered = names.map((name) => isFiltered(model, name));
2518
+ const hiding = filtered.includes(true);
2519
+ return (values) => {
2520
+ const stored = values.map((value, index) => inJson(attributes[index].store(value)));
2521
+ const text = JSON.stringify(stored);
2522
+ if (!hiding) return {
2523
+ values,
2524
+ text,
2525
+ shown: text
2526
+ };
2527
+ return {
2528
+ values,
2529
+ text,
2530
+ shown: JSON.stringify(stored.map((cell, index) => filtered[index] ? FILTERED : cell))
2531
+ };
2532
+ };
2533
+ }
2534
+ /** Rows as one JSON value, which listeners see with filtered attributes hidden. */
2535
+ function jsonValue(rows) {
2536
+ const json = `[${rows.map(({ text }) => text).join(",")}]`;
2537
+ if (rows.every(({ text, shown }) => text === shown)) return json;
2538
+ return new Filtered(json, `[${rows.map(({ shown }) => shown).join(",")}]`);
2539
+ }
2540
+ /**
2541
+ * `text`'s length in UTF-8 bytes, counted without encoding a copy of it. A code unit below
2542
+ * U+0080 is one byte, below U+0800 two, and any other three, except that a surrogate pair is four
2543
+ * between its two units. JSON text has no lone surrogates: `JSON.stringify` escapes them.
2544
+ */
2545
+ function utf8Length(text) {
2546
+ let bytes = text.length;
2547
+ for (let index = 0; index < text.length; index++) {
2548
+ const unit = text.charCodeAt(index);
2549
+ if (unit < 128) continue;
2550
+ bytes += unit < 2048 || unit >= 55296 && unit <= 57343 ? 1 : 2;
2551
+ }
2552
+ return bytes;
2553
+ }
2554
+ /** A stored cell as a bulk write's JSON holds it: bytes as hex text, which JSON has no form for (#20). */
2555
+ function inJson(cell) {
2556
+ return cell instanceof Uint8Array ? hexOf(cell) : cell;
2557
+ }
2558
+ // src/bulk-insert-sql.ts
2559
+ /**
2560
+ * `INSERT` of several rows, all with the attributes `names`, bound as one JSON parameter, which
2561
+ * the dialect reads them from: one statement and one bound value, whatever the number of rows,
2562
+ * within D1's limit of 100 bound parameters per statement. Rows whose JSON would pass the
2563
+ * dialect's `maxValueBytes` take several statements, and a row whose JSON alone would pass it
2564
+ * binds each of its values apart, as `compileInsert` does (#392).
2565
+ */
2566
+ function compileInsertRows(dialect, model, { names, rows, conflict, returning }) {
2567
+ const attributes = names.map((name) => attributeFor(model, name));
2568
+ const columns = attributes.map(({ column }) => quoteIdentifier(column)).join(", ");
2569
+ const table = quoteIdentifier(model.table);
2570
+ const { select, from } = dialect.bulkRows(table, attributes);
2571
+ const endParams = [];
2572
+ const end = compileConflict(dialect, model, {
2573
+ names,
2574
+ conflict,
2575
+ params: endParams
2576
+ }) + compileReturning(model, returning);
2577
+ return rowGroups(model, names, rows, dialect.maxValueBytes).map((group) => {
2578
+ if (group.kind === "json") return {
2579
+ sql: `INSERT INTO ${table} (${columns}) SELECT ${select} FROM ${from} WHERE true${end}`,
2580
+ params: [group.value, ...endParams],
2581
+ model
2582
+ };
2583
+ const params = [];
2584
+ const values = compileValues(attributes, group.row, params);
2585
+ return {
2586
+ sql: `INSERT INTO ${table} ${values}${end}`,
2587
+ params: [...params, ...endParams],
2588
+ model
2589
+ };
2590
+ });
2591
+ }
2592
+ /**
2593
+ * `ON CONFLICT DO NOTHING`, or `ON CONFLICT (…) DO UPDATE SET` the `update` attributes (every
2594
+ * inserted one by default) except the `uniqueBy` ones and `createdAt`, or what `set` gives
2595
+ * (#531), and `touch` when one of them changes (#36), `WHERE` the clashing row already has the
2596
+ * new row's `ownedBy` values (#451). The values it binds are appended to `params`.
2597
+ */
2598
+ function compileConflict(dialect, model, { names, conflict, params }) {
2599
+ if (conflict === void 0) return "";
2600
+ if (conflict.kind === "skip") return " ON CONFLICT DO NOTHING";
2601
+ const column = (name) => quoteIdentifier(attributeFor(model, name).column);
2602
+ const target = conflict.uniqueBy.map(column).join(", ");
2603
+ const sets = conflict.set ?? copiedSets(model, names, conflict);
2604
+ if (sets.length === 0) return ` ON CONFLICT (${target}) DO NOTHING`;
2605
+ const written = sets.map((set) => `${column(set.name)} = ${setValue(model, set, params)}`);
2606
+ if (conflict.touch !== void 0) written.push(touchSet(dialect, model, sets, {
2607
+ touch: conflict.touch,
2608
+ params
2609
+ }));
2610
+ return ` ON CONFLICT (${target}) DO UPDATE SET ${written.join(", ")}${compileOwnedBy(model, conflict.ownedBy)}`;
2611
+ }
2612
+ /** What an update sets by default: each `update` attribute to its incoming value. */
2613
+ function copiedSets(model, names, conflict) {
2614
+ return (conflict.update ?? names).filter((name) => !conflict.uniqueBy.includes(name) && name !== "createdAt").map((name) => ({
2615
+ name,
2616
+ value: incoming(name)
2617
+ }));
2618
+ }
2619
+ /**
2620
+ * One value an update sets, as SQL: its incoming value, a fragment (`column()` qualified as the
2621
+ * clashing row's, which Postgres needs, and `incoming()` allowed, #531), or a value bound.
2622
+ */
2623
+ function setValue(model, { name, value }, params) {
2624
+ if (value instanceof IncomingReference) return clashingAndNew(model, value.attribute)[1];
2625
+ if (value instanceof SafeSql) return `(${compileFragment(value, clashSource(model), params)})`;
2626
+ attributeFor(model, name).bind(params, value);
2627
+ return "\0";
2628
+ }
2629
+ /** The clashing row, which an upsert's `onDuplicate` reads, with the row it writes (#531). */
2630
+ function clashSource(model) {
2631
+ return {
2632
+ model,
2633
+ name: quoteIdentifier(model.table),
2634
+ qualified: true,
2635
+ allowsIncoming: true
2636
+ };
2637
+ }
2638
+ /**
2639
+ * `touch` set to the new row's value only when a `sets` attribute's value changes: a clashing
2640
+ * row written again as it was keeps its own (#36). Each set value is compared as it's written, so
2641
+ * a fragment's values are bound again (#531).
2642
+ */
2643
+ function touchSet(dialect, model, sets, { touch, params }) {
2644
+ const same = (set) => {
2645
+ const [left] = clashingAndNew(model, set.name);
2646
+ const right = setValue(model, set, params);
2647
+ const attribute = attributeFor(model, set.name);
2648
+ return dialect.sameValue?.(left, right, attribute) ?? `${left} IS NOT DISTINCT FROM ${right}`;
2649
+ };
2650
+ const unchanged = sets.map(same).join(" AND ");
2651
+ const [kept, given] = clashingAndNew(model, touch);
2652
+ return `${quoteIdentifier(attributeFor(model, touch).column)} = CASE WHEN ${unchanged} THEN ${kept} ELSE ${given} END`;
2653
+ }
2654
+ /** ` WHERE "t"."a" = excluded."a" AND …`: the clashing row already has the new row's values. */
2655
+ function compileOwnedBy(model, ownedBy) {
2656
+ if (ownedBy.length === 0) return "";
2657
+ return ` WHERE ${ownedBy.map((name) => clashingAndNew(model, name).join(" = ")).join(" AND ")}`;
2658
+ }
2659
+ /** `name`'s column in the clashing row and in the new one: `"t"."a"` and `excluded."a"`. */
2660
+ function clashingAndNew(model, name) {
2661
+ const column = quoteIdentifier(attributeFor(model, name).column);
2662
+ return [`${quoteIdentifier(model.table)}.${column}`, `excluded.${column}`];
2663
+ }
2664
+ // src/timestamps.ts
2665
+ /** Whether the Model declares `name` as a datetime attribute, which turns its timestamp on. */
2666
+ function hasTimestamp(model, name) {
2667
+ return model.attributeDefinitions.get(name)?.type === "datetime";
2668
+ }
2669
+ /**
2670
+ * The timestamps to add to a write: `createdAt` and `updatedAt` on insert, `updatedAt` on
2671
+ * update. Never one the write already assigns.
2672
+ */
2673
+ function timestampsFor(model, write, own) {
2674
+ const now = /* @__PURE__ */ new Date();
2675
+ const assigned = new Set(own.map(([name]) => name));
2676
+ return (write === "insert" ? ["createdAt", "updatedAt"] : ["updatedAt"]).filter((name) => hasTimestamp(model, name) && !assigned.has(name)).map((name) => [name, now]);
2677
+ }
2678
+ // src/statement.ts
2679
+ /** @internal The library's key for what `db.batch` needs from a Statement. */
2680
+ const statementParts = Symbol("statementParts");
2681
+ const noRows = () => [];
2682
+ /**
2683
+ * A bulk write prepared in a batch, by a Batch's methods (`b.insert`, `b.updateAll`,
2684
+ * `b.deleteAll`, …). It runs on the Database it was built from, and skips validations,
2685
+ * callbacks and hydration. It has no `then`, so it's never run by being awaited.
2686
+ */
2687
+ var Statement = class Statement {
2688
+ #executor;
2689
+ #queries;
2690
+ #landed;
2691
+ #rows;
2692
+ /** Queries sent before its own, in the same batch, whose results aren't its own (#61). */
2693
+ #preceding = [];
2694
+ /** How many rows its own queries' results say it changed (#61): their `rowsAffected` sum. */
2695
+ #affected = rowsAffectedOf;
2696
+ /**
2697
+ * @internal Statements are built by a Relation's bulk writes, as one query or several sent
2698
+ * together (a bulk write past the database's cap on one value, #392). `landed` runs once D1
2699
+ * has written it, alone or in a batch (a hasMany's clears what its owner has loaded, #187),
2700
+ * with its queries' results, and `rows` reads what it returned.
2701
+ */
2702
+ constructor(executor, queries, landed = () => {}, rows = noRows) {
2703
+ this.#executor = executor;
2469
2704
  this.#queries = queries;
2470
2705
  this.#landed = landed;
2471
2706
  this.#rows = rows;
@@ -2547,7 +2782,8 @@ function insertAssignments(model, attributes) {
2547
2782
  * `INSERT` of `rows` into `model`'s table, as one Statement. Every row must have the same
2548
2783
  * attributes as given; `conflict` skips or updates rows that clash with a unique
2549
2784
  * index. An update sets every attribute in `rows` (the given ones and any a Relation added,
2550
- * #475) and `updatedAt`, never filled-in defaults.
2785
+ * #475), or only those `updateOnly` names, and `updatedAt` when one of them changes (#36), never
2786
+ * filled-in defaults.
2551
2787
  * It returns the attributes `returning` names of each row written.
2552
2788
  */
2553
2789
  function insertStatement(executor, model, rows, { conflict, method, landed, returning }) {
@@ -2560,10 +2796,12 @@ function insertStatement(executor, model, rows, { conflict, method, landed, retu
2560
2796
  throw new TypeError(`${method}(): nothing to insert; give each row at least one attribute`);
2561
2797
  }
2562
2798
  const values = assigned.map((row) => names.map((name) => row.get(name)));
2563
- const resolved = conflict?.kind === "update" ? {
2564
- ...conflict,
2565
- update: [...given, ...names.includes("updatedAt") ? ["updatedAt"] : []]
2566
- } : conflict;
2799
+ const updated = given.filter((name) => model.attributeDefinitions.get(name)?.readonly !== true);
2800
+ const resolved = conflict?.kind === "update" ? resolvedUpdate(conflict, {
2801
+ updated,
2802
+ names,
2803
+ method
2804
+ }) : conflict;
2567
2805
  return new Statement(executor, compileInsertRows(executor.dialect, model, {
2568
2806
  names,
2569
2807
  rows: values,
@@ -2571,6 +2809,31 @@ function insertStatement(executor, model, rows, { conflict, method, landed, retu
2571
2809
  returning
2572
2810
  }), landed, read);
2573
2811
  }
2812
+ /**
2813
+ * An update conflict resolved against the rows: the attributes it updates, which are
2814
+ * `updateOnly`'s (each of them one the rows give) or else every one `updated`, and `updatedAt`
2815
+ * to touch when one of them changes, when the rows write it and it isn't updated itself (#36);
2816
+ * or what `onDuplicate` sets, and `updatedAt` likewise (#531).
2817
+ */
2818
+ function resolvedUpdate(conflict, { updated, names, method }) {
2819
+ if (conflict.set !== void 0) {
2820
+ const setsUpdatedAt = conflict.set.some(({ name }) => name === "updatedAt");
2821
+ const touches = names.includes("updatedAt") && !setsUpdatedAt;
2822
+ return {
2823
+ ...conflict,
2824
+ touch: touches ? "updatedAt" : void 0
2825
+ };
2826
+ }
2827
+ const update = conflict.update ?? updated;
2828
+ const missing = update.find((name) => !updated.includes(name));
2829
+ if (missing !== void 0) throw new TypeError(`${method}() updateOnly names ${missing}, which the rows don't give`);
2830
+ const touchesUpdatedAt = names.includes("updatedAt") && !update.includes("updatedAt");
2831
+ return {
2832
+ ...conflict,
2833
+ update,
2834
+ touch: touchesUpdatedAt ? "updatedAt" : void 0
2835
+ };
2836
+ }
2574
2837
  /** The attributes every row was given; they must be the same for all rows, in any order. */
2575
2838
  function sameAttributes(rows, method) {
2576
2839
  const [first, ...rest] = rows.map((row) => Object.keys(row));
@@ -2805,11 +3068,11 @@ function preparedWritesOf(relation) {
2805
3068
  method: "insertAll",
2806
3069
  returning: options.returning
2807
3070
  }),
2808
- upsert: (attributes, options = {}) => insertRows(relation, [attributes], ownedUpdate(relation, options), {
3071
+ upsert: (attributes, options = {}) => insertRows(relation, [attributes], ownedUpdate(relation, options, "upsert"), {
2809
3072
  method: "upsert",
2810
3073
  returning: options.returning
2811
3074
  }),
2812
- upsertAll: (rows, options = {}) => insertRows(relation, rows, ownedUpdate(relation, options), {
3075
+ upsertAll: (rows, options = {}) => insertRows(relation, rows, ownedUpdate(relation, options, "upsertAll"), {
2813
3076
  method: "upsertAll",
2814
3077
  returning: options.returning
2815
3078
  }),
@@ -2821,8 +3084,11 @@ function preparedWritesOf(relation) {
2821
3084
  * An upsert's conflict through `relation`: through an owner's hasMany, it updates a clashing
2822
3085
  * row only when that row is already the owner's, so it never takes another owner's (#451).
2823
3086
  */
2824
- function ownedUpdate(relation, options) {
2825
- return updateOn(relation.model, options, Object.keys(ownersValues(relation)));
3087
+ function ownedUpdate(relation, options, method) {
3088
+ return updateOn(relation.model, options, {
3089
+ ownedBy: Object.keys(ownersValues(relation)),
3090
+ method
3091
+ });
2826
3092
  }
2827
3093
  function insertRows(relation, rows, conflict, { method, returning }) {
2828
3094
  requireSavedOwner$1(relation, "insert");
@@ -3178,6 +3444,7 @@ function whoseIs(association, linked, otherType) {
3178
3444
  */
3179
3445
  async function pinForSaving(records, needs) {
3180
3446
  const groups = records.map((record) => savingGroups(record));
3447
+ requireSavesWritable(groups.flat().flatMap((group) => group.records));
3181
3448
  await pinBefore(linksOf(groups.flatMap(([own]) => own?.records ?? [])), needs);
3182
3449
  for (const [, ...elsewhere] of groups) for (const group of elsewhere) await pinBefore(linksOf(group.records), needs);
3183
3450
  }
@@ -3548,6 +3815,7 @@ async function loadWith(executor, model, load) {
3548
3815
  const results = await sendTogether(executor, [...own, ...plan?.statements ?? []]);
3549
3816
  const database = await databaseNow(executor);
3550
3817
  const records = (load.rowsOf(results) ?? []).map((row) => hydrate(model, row, database));
3818
+ if (query.readonly === true) for (const record of records) record[state].isReadonly = true;
3551
3819
  await plan?.attach([records], results.slice(own.length), database);
3552
3820
  return {
3553
3821
  records,
@@ -3807,11 +4075,7 @@ function planBranch(planning, start, level, { name, association }) {
3807
4075
  leaveForAfterwards(planning, deferred);
3808
4076
  return;
3809
4077
  }
3810
- const step = {
3811
- association,
3812
- ownersAt,
3813
- select: targets?.select
3814
- };
4078
+ const step = stepFor(association, ownersAt, targets);
3815
4079
  const position = planning.offset + planning.steps.push(step) - 1;
3816
4080
  if (query === void 0 || targets === void 0) return;
3817
4081
  const { target } = association;
@@ -4004,8 +4268,9 @@ async function attachSteps({ steps, gathers, afterwards }, records, rows, execut
4004
4268
  function recordsAtEachPosition(steps, records, rows, executor) {
4005
4269
  const owners = [...records];
4006
4270
  const results = rows.values();
4007
- for (const { association, ownersAt, select, isHop } of steps) {
4271
+ for (const { association, ownersAt, select, isHop, readonly } of steps) {
4008
4272
  const targets = (select === void 0 ? [] : results.next().value ?? []).map((row) => hydrate(association.target, row, executor));
4273
+ if (readonly === true) for (const target of targets) target[state].isReadonly = true;
4009
4274
  if (isHop === void 0) attach(owners[ownersAt] ?? [], association, targets);
4010
4275
  owners.push(targets);
4011
4276
  }
@@ -4022,7 +4287,24 @@ async function preloadStarts(starts, executor) {
4022
4287
  const records = starts.map(({ owners }) => "records" in owners ? owners.records : []);
4023
4288
  await plan.attach(records, rows, database);
4024
4289
  }
4025
- /** The SELECT for an association's targets, `query`, and what to preload for them. */
4290
+ /** A step loading an association's targets, if they can match. */
4291
+ function stepFor(association, ownersAt, targets) {
4292
+ if (targets === void 0) return {
4293
+ association,
4294
+ ownersAt,
4295
+ select: void 0
4296
+ };
4297
+ return {
4298
+ association,
4299
+ ownersAt,
4300
+ select: targets.select,
4301
+ readonly: targets.readonly
4302
+ };
4303
+ }
4304
+ /**
4305
+ * The SELECT for an association's targets, `query`, what to preload for them, and whether its
4306
+ * scope makes them read-only (#358).
4307
+ */
4026
4308
  function targetsOf(dialect, association, query, { nested, needed = [] }) {
4027
4309
  const includes = mergeTrees(query.includes ?? {}, nested);
4028
4310
  const columns = query.select && [
@@ -4036,7 +4318,8 @@ function targetsOf(dialect, association, query, { nested, needed = [] }) {
4036
4318
  select: columns,
4037
4319
  includes
4038
4320
  }),
4039
- includes
4321
+ includes,
4322
+ readonly: query.readonly
4040
4323
  };
4041
4324
  }
4042
4325
  /**
@@ -4271,18 +4554,19 @@ function inspectRelation(modelName, { sql, params }, args) {
4271
4554
  }
4272
4555
  // src/find.ts
4273
4556
  /**
4274
- * The finder rules: `query`'s conditions (plus `extra`), joins and includes, full rows, no
4275
- * order.
4557
+ * The finder rules: `query`'s conditions (plus `extra`), joins, includes and read-only mark (#358),
4558
+ * full rows, no order.
4276
4559
  */
4277
4560
  function finderQuery(query, extra) {
4278
4561
  const conditions = extra === void 0 ? query.conditions : [...query.conditions, extra];
4279
- const { model, joins, includes } = query;
4562
+ const { model, joins, includes, readonly } = query;
4280
4563
  return {
4281
4564
  model,
4282
4565
  conditions,
4283
4566
  order: [],
4284
4567
  includes,
4285
- ...joins !== void 0 && { joins }
4568
+ ...joins !== void 0 && { joins },
4569
+ ...readonly !== void 0 && { readonly }
4286
4570
  };
4287
4571
  }
4288
4572
  /** One row `query` matches by the finder rules (plus `extra`), or null. */
@@ -4339,8 +4623,12 @@ function inKeyOrder(records, keys) {
4339
4623
  const byKey = new Map(records.map((record) => [primaryKeyOf(record), record]));
4340
4624
  return keys.map((key) => byKey.get(key));
4341
4625
  }
4342
- /** What `find(...args)` finds: one record for one id, else an array, in the ids' or the query's order. */
4626
+ /**
4627
+ * What `find(...args)` finds: one record for one id, else an array, in the ids' or the query's
4628
+ * order. A `column()`, typed value or `incoming()` given as an id throws `TypeError` (#546).
4629
+ */
4343
4630
  async function findByIds({ model, query, runner }, args) {
4631
+ for (const id of args.flat()) refuseReferenceValue(id, `find() gives ${model.primaryKey}`, { takesFragment: false });
4344
4632
  const [only] = args;
4345
4633
  if (args.length === 1 && (typeof only === "string" || typeof only === "number")) return findById(runner, query, only);
4346
4634
  const ids = keysToFind(model, args.flat());
@@ -4598,755 +4886,784 @@ async function upToTwo(source) {
4598
4886
  }
4599
4887
  }) + source.unsavedCount();
4600
4888
  }
4601
- // src/query-rewrites.ts
4602
- /** Each part `unscope` drops, as the query without it. */
4603
- const WITHOUT = {
4604
- where: (query) => ({
4605
- ...query,
4606
- conditions: []
4607
- }),
4608
- order: (query) => ({
4609
- ...without(query, "reordered"),
4610
- order: []
4611
- }),
4612
- limit: (query) => without(query, "limit"),
4613
- offset: (query) => without(query, "offset"),
4614
- select: (query) => without(query, "select"),
4615
- distinct: (query) => without(query, "distinct"),
4616
- includes: (query) => without(query, "includes"),
4617
- joins: (query) => withoutJoins(query, "inner"),
4618
- leftJoins: (query) => withoutJoins(query, "left"),
4619
- createWith: (query) => without(query, "createWith")
4620
- };
4621
- /** A copy of `query` without the optional `key`. */
4622
- function without(query, key) {
4623
- const copy = { ...query };
4624
- delete copy[key];
4625
- return copy;
4626
- }
4627
- /** `query` without `part`. */
4628
- function withoutPart(query, part) {
4629
- requirePart(part);
4630
- return keepingOwnerLink(WITHOUT[part](query));
4631
- }
4632
- /** Refuses a part `unscope` and `only` don't know: `"group"`, or a misspelling. */
4633
- function requirePart(part) {
4634
- if (typeof part !== "string" || !Object.hasOwn(WITHOUT, part)) {
4635
- const parts = Object.keys(WITHOUT).map((name) => `"${name}"`);
4636
- throw new TypeError(`A query's parts are ${parts.join(", ")}; got ${String(part)}`);
4637
- }
4638
- }
4639
- /** `query` with only the parts named: every other part is dropped. */
4640
- function withOnly(query, parts) {
4641
- for (const part of parts) requirePart(part);
4642
- return Object.keys(WITHOUT).filter((part) => !parts.includes(part)).reduce(withoutPart, query);
4643
- }
4644
- /** `query` without the associations it joins this way, and their joins in turn. */
4645
- function withoutJoins(query, kind) {
4646
- const joins = (query.joins ?? []).filter((join) => join.kind !== kind);
4647
- const used = joinedPaths(query).find((path) => !joins.some((join) => join.association === path));
4648
- if (used !== void 0) throw new IncompatibleRelation(`unscope() can't drop the join of "${used}": conditions or an order merged onto it use it`);
4649
- return joins.length === 0 ? without(query, "joins") : {
4650
- ...query,
4651
- joins
4652
- };
4653
- }
4654
- /** The associations joined at the top that a merged Relation's conditions or order are on. */
4655
- function joinedPaths({ conditions, order }) {
4656
- return [...conditions.flatMap(joinedPathsIn), ...order.flatMap((term) => term instanceof JoinedOrder ? [term.path] : [])].map((path) => path.split(".")[0]);
4657
- }
4658
- /** The join paths a condition's merged conditions are on, at any depth. */
4659
- function joinedPathsIn(condition) {
4660
- if (condition instanceof JoinedConditions) return [condition.path];
4661
- if (condition instanceof Negated) return joinedPathsIn(condition.condition);
4662
- if (condition instanceof Either) return [...condition.left, ...condition.right].flatMap(joinedPathsIn);
4663
- return [];
4664
- }
4889
+ // src/message-signing.ts
4890
+ /** The bytes of a fingerprint kept in a token: enough that guessing one is hopeless. */
4891
+ const FINGERPRINT_BYTES = 12;
4892
+ const SIGNATURE_BYTES = 32;
4665
4893
  /**
4666
- * `query` without its conditions on `attributes` (`unscope({ where })`): an object condition
4667
- * loses those keys, and a `whereNot` or `or` condition goes when it names only them. A fragment,
4668
- * a condition merged onto a join, and one naming other attributes too are kept.
4894
+ * The longest token: room for an id of about 700 characters, its expiry and a fingerprint, far
4895
+ * more than a key's id needs; signing a longer one throws. A longer token is
4896
+ * refused before its signature is checked, so a huge one costs nothing.
4669
4897
  */
4670
- function withoutConditionsOn(query, attributes) {
4671
- const resolved = new Set(attributes.map((name) => attributeName(query.model, name)));
4672
- const isDropped = (name) => resolved.has(attributeName(query.model, name));
4673
- const link = new Set(query.ownerLink);
4674
- const conditions = query.conditions.flatMap((condition) => link.has(condition) ? [condition] : remainderOf(condition, isDropped));
4675
- return keepingOwnerLink({
4676
- ...query,
4677
- conditions
4678
- });
4679
- }
4680
- /** `query` with `condition` added as part of its link to an association's owner (#350). */
4681
- function withOwnerLink(query, condition) {
4682
- const ownerLink = [...query.ownerLink ?? [], condition];
4898
+ const MAX_TOKEN_LENGTH = 1024;
4899
+ /** base64url without padding. */
4900
+ const BASE64URL = /^[\w-]+$/;
4901
+ /** A signer for `feature`'s tokens: the first secret signs, and each one verifies. */
4902
+ function signerFor(secrets, feature) {
4903
+ const keys = secrets.map((secret) => keysFor(secret, feature));
4683
4904
  return {
4684
- ...query,
4685
- conditions: [...query.conditions, condition],
4686
- ownerLink
4905
+ async sign(purpose, message) {
4906
+ const { id, expiresAt, dependsOn } = message;
4907
+ const key = await keys[0];
4908
+ const fingerprint = Object.hasOwn(message, "dependsOn") ? await fingerprintOf(key, purpose, id, dependsOn) : null;
4909
+ const expiry = expiresAt === void 0 ? null : secondsSinceEpoch(expiresAt);
4910
+ const payload = encode(new TextEncoder().encode(JSON.stringify(trimmed([
4911
+ id,
4912
+ expiry,
4913
+ fingerprint
4914
+ ]))));
4915
+ const signature = await crypto.subtle.sign("HMAC", key.signing, signedBytes(purpose, payload));
4916
+ const token = `${payload}.${encode(new Uint8Array(signature))}`;
4917
+ if (token.length > MAX_TOKEN_LENGTH) throw new TypeError(`A token's id is too long to sign: at most ${MAX_TOKEN_LENGTH} characters in all`);
4918
+ return token;
4919
+ },
4920
+ async verify(purpose, token) {
4921
+ const parts = partsOf(token);
4922
+ if (parts === void 0) return void 0;
4923
+ const data = signedBytes(purpose, parts.payload);
4924
+ const signedWith = await keysThatSigned(keys, data, parts.signature);
4925
+ return signedWith === void 0 ? void 0 : messageIn(signedWith, purpose, parts.payload);
4926
+ }
4687
4927
  };
4688
4928
  }
4929
+ /** A token's payload and signature's bytes, or undefined when it isn't shaped as one, or spelled as `encode` doesn't. */
4930
+ function partsOf(token) {
4931
+ if (token.length > MAX_TOKEN_LENGTH) return void 0;
4932
+ const [payload = "", signature = "", ...rest] = token.split(".");
4933
+ if (rest.length > 0 || !BASE64URL.test(payload) || !BASE64URL.test(signature)) return void 0;
4934
+ const bytes = decode(signature);
4935
+ return bytes?.length === SIGNATURE_BYTES && encode(bytes) === signature ? {
4936
+ payload,
4937
+ signature: bytes
4938
+ } : void 0;
4939
+ }
4689
4940
  /**
4690
- * `query` with each condition of its owner link that a rewrite dropped added back (#350): within
4691
- * an `or`, dropping the `or` drops the link with it, so the link is ANDed on again.
4941
+ * The keys whose signature `data` has, if any's. Every key is tried, so the time taken doesn't
4942
+ * say which signed it.
4692
4943
  */
4693
- function keepingOwnerLink(query) {
4694
- const lost = (query.ownerLink ?? []).filter((link) => !query.conditions.some((condition) => hasLink(condition, link)));
4695
- return lost.length === 0 ? query : {
4696
- ...query,
4697
- conditions: [...query.conditions, ...lost]
4698
- };
4699
- }
4700
- /** Whether `condition` is `link`, or has it within an `or` or a `whereNot`. */
4701
- function hasLink(condition, link) {
4702
- if (condition === link) return true;
4703
- if (condition instanceof Either) return [...condition.left, ...condition.right].some((each) => hasLink(each, link));
4704
- return condition instanceof Negated && hasLink(condition.condition, link);
4705
- }
4706
- /** Whether a condition is an object of attribute values, `where({ role: "admin" })`. */
4707
- function isAttributeValues(condition) {
4708
- return isPlainObject(condition);
4709
- }
4710
- /** What's left of `condition` once those on `dropped` attributes go: itself, part of it, or nothing. */
4711
- function remainderOf(condition, isDropped) {
4712
- if (isAttributeValues(condition)) {
4713
- const left = Object.entries(condition).filter(([name]) => !isDropped(name));
4714
- return left.length === 0 ? [] : [Object.fromEntries(left)];
4944
+ async function keysThatSigned(keys, data, signature) {
4945
+ let signer;
4946
+ for (const each of keys) {
4947
+ const key = await each;
4948
+ if (await crypto.subtle.verify("HMAC", key.signing, signature, data)) signer ??= key;
4715
4949
  }
4716
- const named = attributesNamed(condition);
4717
- return named !== void 0 && named.size > 0 && [...named].every(isDropped) ? [] : [condition];
4950
+ return signer;
4951
+ }
4952
+ /** A token's expiry, in whole Unix seconds; `TypeError` for one that isn't a time. */
4953
+ function secondsSinceEpoch(expiresAt) {
4954
+ const seconds = Math.floor(Number(expiresAt.getTime()) / 1e3);
4955
+ if (!Number.isSafeInteger(seconds)) throw new TypeError("A token's expiry must be a valid Date");
4956
+ return seconds;
4718
4957
  }
4719
4958
  /**
4720
- * The attributes a condition names, or undefined when that can't be known: a fragment's SQL, or
4721
- * a joined Model's conditions.
4959
+ * Each secret's keys, by feature. Module-level, but not request state (ADR-0003): derived only
4960
+ * from the secret, which every request shares.
4722
4961
  */
4723
- function attributesNamed(condition) {
4724
- if (isAttributeValues(condition)) return new Set(Object.keys(condition));
4725
- if (condition instanceof Negated) return attributesNamed(condition.condition);
4726
- if (condition instanceof LinkedTo) return /* @__PURE__ */ new Set([condition.attribute]);
4727
- if (condition instanceof Either) return namedByAll([...condition.left, ...condition.right]);
4728
- }
4729
- /** The attributes several conditions name together, or undefined when any's can't be known. */
4730
- function namedByAll(conditions) {
4731
- const names = /* @__PURE__ */ new Set();
4732
- for (const condition of conditions) {
4733
- const named = attributesNamed(condition);
4734
- if (named === void 0) return void 0;
4735
- for (const name of named) names.add(name);
4962
+ const derived = /* @__PURE__ */ new Map();
4963
+ function keysFor(secret, feature) {
4964
+ const cacheKey = `${feature}\n${secret}`;
4965
+ let keys = derived.get(cacheKey);
4966
+ if (keys === void 0) {
4967
+ keys = deriveKeys(secret, feature);
4968
+ derived.set(cacheKey, keys);
4736
4969
  }
4737
- return names;
4970
+ return keys;
4738
4971
  }
4739
- /** `query` without one part `unscope` was given: a part's name, or `{ where: attributes }`, which it keeps for `merge`. */
4740
- function unscoped(query, given) {
4741
- const part = unscopedPart(query, given);
4972
+ async function deriveKeys(secret, feature) {
4973
+ const material = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), "HKDF", false, ["deriveKey"]);
4974
+ const derive = (use) => crypto.subtle.deriveKey({
4975
+ name: "HKDF",
4976
+ hash: "SHA-256",
4977
+ salt: new TextEncoder().encode("@forestfuture/active-record"),
4978
+ info: new TextEncoder().encode(`${feature} ${use}`)
4979
+ }, material, {
4980
+ name: "HMAC",
4981
+ hash: "SHA-256",
4982
+ length: 256
4983
+ }, false, ["sign", "verify"]);
4984
+ const [signing, fingerprinting] = await Promise.all([derive("signing"), derive("fingerprint")]);
4742
4985
  return {
4743
- ...withoutUnscoped(query, part),
4744
- unscoped: [...query.unscoped ?? [], part]
4986
+ signing,
4987
+ fingerprinting
4745
4988
  };
4746
4989
  }
4747
- /** What `unscope` was given, checked, with `{ where }`'s attributes as a list. */
4748
- function unscopedPart(query, given) {
4749
- if (typeof given === "string") {
4750
- requirePart(given);
4751
- return given;
4752
- }
4753
- if (typeof given !== "object" || given === null || !("where" in given)) throw new TypeError(`unscope() takes a part's name, or { where: attributes }; got ${String(given)}`);
4754
- const attributes = typeof given.where === "string" ? [given.where] : [...given.where];
4755
- for (const name of attributes) columnOf(query.model, name);
4756
- return { where: attributes };
4757
- }
4758
- /** `query` without one part `unscope` dropped. */
4759
- function withoutUnscoped(query, part) {
4760
- return typeof part === "string" ? withoutPart(query, part) : withoutConditionsOn(query, part.where);
4990
+ /** What a token's signature covers: its purpose, quoted so no purpose runs into its payload. */
4991
+ function signedBytes(purpose, payload) {
4992
+ return new TextEncoder().encode(`${JSON.stringify(purpose)}.${payload}`);
4761
4993
  }
4762
4994
  /**
4763
- * `into` with the parts `other` was unscoped of dropped, before `other` merges into it,
4764
- * so an unscope carries over; only for a Relation of the same Model, whose parts they name.
4995
+ * A value's fingerprint for one record's token for one purpose: their JSON, signed with the
4996
+ * fingerprint key, cut short. Each record and purpose fingerprints a value apart, so equal
4997
+ * fingerprints never say two records share it.
4765
4998
  */
4766
- function withUnscopesOf(into, other) {
4767
- if (other.unscoped === void 0 || other.model !== into.model) return into;
4768
- return other.unscoped.reduce(withoutUnscoped, into);
4999
+ async function fingerprintOf(keys, purpose, id, value) {
5000
+ const json = new TextEncoder().encode(JSON.stringify([
5001
+ purpose,
5002
+ id,
5003
+ value ?? null
5004
+ ]));
5005
+ const signature = await crypto.subtle.sign("HMAC", keys.fingerprinting, json);
5006
+ return encode(new Uint8Array(signature).slice(0, FINGERPRINT_BYTES));
4769
5007
  }
4770
- /**
4771
- * `query` with `conditions` in place of those on their attributes (`rewhere`):
4772
- * conditions on other attributes, and fragments, are kept.
4773
- */
4774
- function withConditionsReplaced(query, conditions) {
4775
- requireAttributeConditions(conditions, "rewhere");
4776
- checkConditions(query.model, conditions, "rewhere");
4777
- const names = Object.keys(conditions);
4778
- if (names.length === 0) return query;
4779
- const rest = withoutConditionsOn(query, names);
4780
- const normalized = normalizedConditions(query.model, conditions);
4781
- return {
4782
- ...rest,
4783
- conditions: [...rest.conditions, normalized]
4784
- };
5008
+ /** A payload without the nulls at its end. */
5009
+ function trimmed(values) {
5010
+ let end = values.length;
5011
+ while (end > 1 && values[end - 1] === null) end -= 1;
5012
+ return values.slice(0, end);
4785
5013
  }
4786
- /** `query` without these records (`excluding`), by primary key: `NOT (id IN (…))`. */
4787
- function withoutRecords(query, records) {
4788
- const keys = excludedKeys(query.model, records);
4789
- if (keys.length === 0) return query;
4790
- const left = new Negated({ [query.model.primaryKey]: keys });
5014
+ /** Whether a payload's expiry has passed, or isn't a whole number of Unix seconds; never without one. */
5015
+ function hasExpired(expiry) {
5016
+ if (expiry === null) return false;
5017
+ if (typeof expiry !== "number" || !Number.isSafeInteger(expiry)) return true;
5018
+ return expiry * 1e3 <= Date.now();
5019
+ }
5020
+ /** The message in a signed payload, unless it's expired or isn't one this module made. */
5021
+ function messageIn(keys, purpose, payload) {
5022
+ const [id, expiry = null, fingerprint = null] = parsedPayload(payload) ?? [];
5023
+ if (!(typeof id === "string" || typeof id === "number" && Number.isSafeInteger(id)) || hasExpired(expiry)) return void 0;
4791
5024
  return {
4792
- ...query,
4793
- conditions: [...query.conditions, left]
5025
+ id,
5026
+ async isUnchanged(value) {
5027
+ if (typeof fingerprint !== "string") return false;
5028
+ return fingerprint === await fingerprintOf(keys, purpose, id, value);
5029
+ }
4794
5030
  };
4795
5031
  }
4796
- /**
4797
- * The primary keys of the records `excluding` leaves out, each a record of `model` (or a class
4798
- * extending it); a record without a key yet has no row to leave out.
4799
- */
4800
- function excludedKeys(model, records) {
4801
- return records.flat().flatMap((record) => {
4802
- if (!(record instanceof model)) throw new TypeError(`excluding() takes records of ${model.name}; got ${describedValue(record)}`);
4803
- const key = primaryKeyOf(record);
4804
- return key === null || key === void 0 ? [] : [key];
4805
- });
4806
- }
4807
- /** How a refusal names what it was given: a record's class, or its type. */
4808
- function describedValue(value) {
4809
- if (value instanceof Model) return `a ${value.constructor.name}`;
4810
- return value === null ? "null" : typeof value;
4811
- }
4812
- // src/record-creation.ts
4813
- /**
4814
- * @internal A new, unsaved record through `relation`, handed to `init`, which mustn't return a promise
4815
- * (`TypeError`): nothing awaits it. Through a hasMany, the record then joins the association,
4816
- * so a record whose `init` throws doesn't.
4817
- */
4818
- function buildThrough(relation, attributes, init) {
4819
- const record = recordToBuild(relation, attributes);
4820
- refuseInitPromise(relation.model, init?.(record));
4821
- runBuiltCallbacks(record);
4822
- relation.collection.built(record);
4823
- return record;
5032
+ /** A payload's values, or undefined when it isn't a JSON array. */
5033
+ function parsedPayload(payload) {
5034
+ const bytes = decode(payload);
5035
+ if (bytes === void 0) return void 0;
5036
+ try {
5037
+ const values = JSON.parse(new TextDecoder("utf-8", {
5038
+ fatal: true,
5039
+ ignoreBOM: false
5040
+ }).decode(bytes));
5041
+ return Array.isArray(values) ? values : void 0;
5042
+ } catch {
5043
+ return;
5044
+ }
4824
5045
  }
4825
- /** Throws `TypeError` if a `build` `init` returned a promise, which `build` can't await. */
4826
- function refuseInitPromise(model, result) {
4827
- refuseThenable(result, `${model.name}.build(): init returned a promise, which build can't await; findOrInitializeBy and create await it`);
5046
+ function encode(bytes) {
5047
+ let binary = "";
5048
+ for (const byte of bytes) binary += String.fromCharCode(byte);
5049
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
4828
5050
  }
4829
- /** @internal `buildThrough`, awaiting `init`: what `findOrInitializeBy` builds. */
4830
- async function initializeThrough(relation, attributes, init) {
4831
- const record = recordToBuild(relation, attributes);
4832
- await init?.(record);
4833
- runBuiltCallbacks(record);
4834
- relation.collection.built(record);
4835
- return record;
5051
+ /** base64url's bytes, or undefined for text that isn't base64url. */
5052
+ function decode(text) {
5053
+ try {
5054
+ const binary = atob(text.replaceAll("-", "+").replaceAll("_", "/"));
5055
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
5056
+ } catch {
5057
+ return;
5058
+ }
4836
5059
  }
4837
- /** @internal Builds and saves a record through `relation`; `orThrow` throws if it can't be saved. */
4838
- async function createThrough(relation, attributes, { init, orThrow }) {
4839
- const record = await recordToCreate(relation, attributes, init);
4840
- await saveCreated(relation, record, orThrow);
4841
- return record;
5060
+ // src/workers-env.ts
5061
+ /** Whether importing `cloudflare:workers` failed because this isn't a Worker (Node, scripts). */
5062
+ function isOutsideWorker(error) {
5063
+ const { code, message } = error;
5064
+ return code === "ERR_UNSUPPORTED_ESM_URL_SCHEME" || code === "ERR_MODULE_NOT_FOUND" || /cloudflare:workers/.test(String(message));
4842
5065
  }
4843
5066
  /**
4844
- * @internal Creates a record through `relation`, as `createThrough` does, or `find`s the row a unique
4845
- * index kept it from duplicating. It finds only for a record saved alone: when `init` gave it
4846
- * records to save with it, a refusal may be theirs, so any `RecordNotUnique` reaches the caller.
5067
+ * The Worker's `env`, from `load`, or undefined outside a Worker (Node, scripts). An adapter
5068
+ * passes `() => import("cloudflare:workers")` from its own module, with that literal specifier:
5069
+ * Wrangler only bundles those, and a test that mocks the module with the adapter inlined reaches it.
4847
5070
  */
4848
- async function createOrFindThrough(relation, attributes, options) {
4849
- const record = await recordToCreate(relation, attributes, options.init);
4850
- const isSavedAlone = record[state].autosaves.isEmpty();
5071
+ async function workersEnv(load) {
4851
5072
  try {
4852
- await saveCreated(relation, record, options.orThrow);
4853
- return record;
5073
+ return (await load()).env;
4854
5074
  } catch (error) {
4855
- if (!isSavedAlone || !(error instanceof RecordNotUnique)) throw error;
4856
- return options.find();
5075
+ if (isOutsideWorker(error)) return void 0;
5076
+ throw error;
4857
5077
  }
4858
5078
  }
4859
- async function recordToCreate(relation, attributes, init) {
4860
- requireSavedOwner$1(relation, "create");
4861
- const record = recordToBuild(relation, attributes);
4862
- await init?.(record);
4863
- runBuiltCallbacks(record);
4864
- return record;
5079
+ // src/signing-secret.ts
5080
+ /** The fewest bytes a secret has: HMAC-SHA256's own key length. */
5081
+ const MINIMUM_BYTES = 32;
5082
+ /**
5083
+ * The Worker's env, read once. Module-level, but not request state (ADR-0003): it's the
5084
+ * Worker's, the same for every request.
5085
+ */
5086
+ let workerEnv;
5087
+ /** The env secrets are read from: the Worker's, or else the process's (tests, scripts). */
5088
+ async function envForSecrets() {
5089
+ workerEnv ??= workersEnv(() => import("cloudflare:workers"));
5090
+ return await workerEnv ?? processEnv() ?? {};
4865
5091
  }
4866
- /** A new record through `relation`, pointing back at its owner if it has one. */
4867
- function recordToBuild(relation, attributes) {
4868
- const record = newRecord(relation, attributes);
4869
- relation.collection.pointBack(record);
4870
- return record;
5092
+ /** `process.env`, where there's one: Node, and Workers with Node.js compatibility. */
5093
+ function processEnv() {
5094
+ return globalThis.process?.env;
4871
5095
  }
4872
- async function saveCreated(relation, record, orThrow) {
4873
- const { collection } = relation;
4874
- if (await saveThrough(collection, record, orThrow)) collection.created(record);
5096
+ /** A signer for `model`'s `feature` tokens; `InvalidModel` when its secrets are unset or short. */
5097
+ async function signerOf(model, feature) {
5098
+ return signerFor(secretsOf(model, await envForSecrets()), feature);
4875
5099
  }
4876
- /** Saves a record created through `collection`, as its `saveCreated` says, or as the record saves. */
4877
- function saveThrough(collection, record, orThrow) {
4878
- return collection.saveCreated?.(record, orThrow) ?? (orThrow ? record.saveOrThrow() : record.save());
5100
+ function secretsOf(model, env) {
5101
+ const given = model.signingSecret(env);
5102
+ const secrets = (Array.isArray(given) ? given : [given]).filter((secret) => secret !== void 0 && secret !== null);
5103
+ if (secrets.length === 0) throw new InvalidModel(`${model.name} has no signing secret: set SECRET_KEY_BASE in the Worker's secrets (wrangler secret put SECRET_KEY_BASE), or override signingSecret`);
5104
+ for (const secret of secrets) if (typeof secret !== "string" || new TextEncoder().encode(secret).length < MINIMUM_BYTES) throw new InvalidModel(`${model.name}'s signing secret must be a string of at least ${MINIMUM_BYTES} bytes, such as openssl rand -hex 32 makes`);
5105
+ return secrets;
4879
5106
  }
4880
- function newRecord(relation, attributes) {
4881
- const { assigned, kept } = builtRecordValues(relation, attributes);
4882
- return buildRecord(relation.model, assigned, relation.executor, kept);
5107
+ // src/token-records.ts
5108
+ /** A saved record's primary key, which a token holds; `RecordNotSaved` for a new record. */
5109
+ function signableIdOf(record, method) {
5110
+ const model = record.constructor;
5111
+ if (record[state].isNew) throw new RecordNotSaved(`${model.name} record hasn't been saved, so ${method} has no id to sign`);
5112
+ return record[state].read(model.primaryKey);
4883
5113
  }
4884
- // src/find-or-create.ts
4885
- /** @internal `findOrCreateBy` and `findOrCreateByOrThrow`: the record found, or one created. */
4886
- async function findOrCreate(call, attributes, { init, orThrow }) {
4887
- const found = await findExisting(call, attributes);
4888
- if (found !== null) return found;
4889
- return orThrow ? call.relation.createOrThrow(attributes, init) : call.relation.create(attributes, init);
5114
+ /** What a Model's token is signed for: its table, then what else the token is for. */
5115
+ function signedPurposeOf(model, ...parts) {
5116
+ return JSON.stringify([model.table, ...parts]);
4890
5117
  }
4891
- /** @internal `findOrInitializeBy`: the record found, or one built, its `init` awaited. */
4892
- async function findOrInitialize(call, attributes, init) {
4893
- return await findExisting(call, attributes) ?? initializeThrough(call.state, attributes, init);
5118
+ /**
5119
+ * Looks up the record a token finds through `finder`, if `signer` signed it for `purpose` and it
5120
+ * hasn't expired, and `isStillFor` (when given) says the record is still the one it was for. A
5121
+ * value that isn't a string isn't a valid token.
5122
+ */
5123
+ async function lookUpToken(finder, { signer, purpose }, token, isStillFor) {
5124
+ const verified = typeof token === "string" ? await signer.verify(purpose, token) : void 0;
5125
+ if (verified === void 0) return {
5126
+ isValid: false,
5127
+ record: null
5128
+ };
5129
+ const record = await finder.findBy(asStored({ [finder.model.primaryKey]: verified.id }));
5130
+ return {
5131
+ isValid: true,
5132
+ record: record !== null && (isStillFor === void 0 || await isStillFor(record, verified)) ? record : null
5133
+ };
4894
5134
  }
4895
5135
  /**
4896
- * @internal `createOrFindBy` and `createOrFindByOrThrow`: a record created, or the one a unique
4897
- * index kept.
5136
+ * The record a lookup found; `InvalidToken` (naming `what`) for a token that isn't valid, and
5137
+ * `RecordNotFound` when a valid one found none.
4898
5138
  */
4899
- async function createOrFind(call, attributes, options) {
4900
- const { finder, conditions } = finderFor(call, attributes);
4901
- const find = () => finder.findByOrThrow(conditions);
4902
- return createOrFindThrough(call.state, attributes, {
4903
- ...options,
4904
- find
5139
+ function foundByTokenOrThrow(model, { isValid, record }, what) {
5140
+ if (!isValid) throw new InvalidToken(`The ${what} isn't valid: it's changed, expired, or for another purpose`);
5141
+ return foundOrThrow(model, record);
5142
+ }
5143
+ // src/signed-ids.ts
5144
+ /** What a signed id is signed for: its Model's table, and its purpose. */
5145
+ function signedIdPurpose(model, purpose) {
5146
+ return signedPurposeOf(model, purpose ?? null);
5147
+ }
5148
+ /** When a token expires: `expiresAt`, or `expiresIn` from now; `TypeError` for both. */
5149
+ function expiryOf({ expiresIn, expiresAt }, where) {
5150
+ if (expiresIn !== void 0 && expiresAt !== void 0) throw new TypeError(`${where} takes expiresIn or expiresAt, not both`);
5151
+ if (expiresIn !== void 0) return expiryAfter(expiresIn, `${where}'s expiresIn`);
5152
+ if (expiresAt !== void 0 && !(expiresAt instanceof Date && Number.isFinite(expiresAt.getTime()))) throw new TypeError(`${where}'s expiresAt must be a valid Date`);
5153
+ return expiresAt;
5154
+ }
5155
+ /** A record's signed id, made with its Model's newest secret. */
5156
+ async function signedIdOf(record, options = {}) {
5157
+ const model = record.constructor;
5158
+ const id = signableIdOf(record, "signedId");
5159
+ const expiresAt = expiryOf(options, "signedId");
5160
+ return (await signerOf(model, "signed id")).sign(signedIdPurpose(model, options.purpose), {
5161
+ id,
5162
+ ...expiresAt && { expiresAt }
4905
5163
  });
4906
5164
  }
4907
- /** The record with `attributes`, or null: what `findOrCreate` and `findOrInitialize` find. */
4908
- function findExisting(call, attributes) {
4909
- const { finder, conditions } = finderFor(call, attributes);
4910
- return finder.findBy(conditions);
5165
+ /** Looks up the record a signed id finds through `finder`, if its Model's secret signed it for `purpose`. */
5166
+ async function findSigned(finder, signedId, { purpose } = {}) {
5167
+ return lookUpToken(finder, {
5168
+ signer: await signerOf(finder.model, "signed id"),
5169
+ purpose: signedIdPurpose(finder.model, purpose)
5170
+ }, signedId);
4911
5171
  }
4912
- /**
4913
- * What finds the record with `attributes`, once they're checked: the Relation, narrowed by an
4914
- * array the attribute casts as one value, compared whole, as the new record holds it, where
4915
- * `findBy` would read it as a list; and the other attributes, as `findBy` reads them. They're
4916
- * copied as own keys, so a `__proto__` key from parsed JSON stays an attribute `findBy` refuses.
4917
- */
4918
- function finderFor(call, attributes) {
4919
- const entries = refuseConditionValues(call, attributes);
4920
- let finder = call.relation;
4921
- for (const [name, value] of entries) if (Array.isArray(value)) finder = finder.where(sql`${column(name)} = ${column(name).value(value)}`);
4922
- const conditions = Object.fromEntries(entries.filter(([, value]) => !Array.isArray(value)));
4923
- return {
4924
- finder,
4925
- conditions
4926
- };
5172
+ // src/tokens-for.ts
5173
+ const OPTION_NAMES = /* @__PURE__ */ new Set(["expiresIn", "dependsOn"]);
5174
+ /** Declares a purpose's tokens on `model`; `InvalidModel` for a declaration that isn't one. */
5175
+ function declareTokenFor(model, purpose, options = {}) {
5176
+ const where = `${model.name}.generatesTokenFor`;
5177
+ if (typeof purpose !== "string" || purpose === "") throw new InvalidModel(`${where} takes a purpose, such as "emailConfirmation"`);
5178
+ const unknown = Object.keys(options).filter((name) => !OPTION_NAMES.has(name));
5179
+ if (unknown.length > 0) throw new InvalidModel(`${where}("${purpose}") takes expiresIn and dependsOn, not ${unknown.join(", ")}`);
5180
+ if (options.dependsOn !== void 0 && typeof options.dependsOn !== "function") throw new InvalidModel(`${where}("${purpose}")'s dependsOn is a function of the record`);
5181
+ if (options.expiresIn !== void 0) secondsOf(options.expiresIn, `${where}("${purpose}")'s expiresIn`);
5182
+ declare(model, "tokenDefinitions", {
5183
+ purpose,
5184
+ ...options
5185
+ });
4927
5186
  }
4928
5187
  /**
4929
- * Throws `TypeError`, before anything is sent, for attributes a find would read as a condition
4930
- * but a new record can't take as its values: a list (except an array the attribute casts as one
4931
- * value), which `findBy` reads as `IN`, so input that skipped `permit` can't match another
4932
- * user's row; a comparison; a `sql` fragment, as the attributes or as one value; or anything
4933
- * but an object, whose missing attributes would find any record. The value isn't shown, as it
4934
- * may be filtered. Returns the attributes' entries, read once.
5188
+ * The declaration of `purpose` on `model`, the last when it's declared again, after its secure
5189
+ * passwords' reset tokens; `TypeError` when there's none.
4935
5190
  */
4936
- function refuseConditionValues({ state, method }, attributes) {
4937
- const named = `${state.model.name}.${method}()`;
4938
- if (attributes instanceof SafeSql) throw new TypeError(`${named} takes attribute values, not a sql fragment`);
4939
- if (typeof attributes !== "object" || attributes === null || Array.isArray(attributes)) throw new TypeError(`${named} takes an object of attribute values`);
4940
- const entries = Object.entries(attributes);
4941
- for (const [name, value] of entries) {
4942
- const kind = conditionKind(state.model, name, value);
4943
- if (kind === void 0) continue;
4944
- throw new TypeError(`${named}: "${name}" can't be ${kind}, since it becomes the new record's value`);
4945
- }
4946
- return entries;
5191
+ function definitionOf(model, purpose) {
5192
+ const resets = resetTokenDefinitions(model.attributeDefinitions);
5193
+ const declarations = declared(model, "tokenDefinitions");
5194
+ rejectResetPurposes(model, resets, declarations);
5195
+ const found = [...resets, ...declarations].findLast((definition) => definition.purpose === purpose);
5196
+ if (found === void 0) throw new TypeError(`${model.name} has no tokens for "${purpose}"; declare them with this.generatesTokenFor("${purpose}") in its static {} block`);
5197
+ return found;
4947
5198
  }
4948
5199
  /**
4949
- * What a condition `value` of the attribute `name` is, when it's one a new record can't take as
4950
- * its value. An array the attribute casts as one value is one: a json attribute's, or a custom
4951
- * type's whose values are arrays.
5200
+ * A declared purpose a reset token already uses is an `InvalidModel`: it would replace the reset
5201
+ * token, which stops working once the password changes, with one that doesn't.
4952
5202
  */
4953
- function conditionKind(model, name, value) {
4954
- if (Array.isArray(value)) return isOneValue(model, name, value) ? void 0 : "a list";
4955
- if (value instanceof Comparison) return "a comparison";
4956
- if (value instanceof SafeSql) return "a sql fragment";
5203
+ function rejectResetPurposes(model, resets, declarations) {
5204
+ const clash = resets.find(({ purpose }) => declarations.some((each) => each.purpose === purpose));
5205
+ if (clash === void 0) return;
5206
+ throw new InvalidModel(`${model.name}.generatesTokenFor("${clash.purpose}") would replace a secure password's reset token; change how long it lasts with securePassword: { resetToken: { expiresIn } }`);
4957
5207
  }
4958
- /** Whether the attribute `name` casts the array `value` as one value, not as a list of them. */
4959
- function isOneValue(model, name, value) {
4960
- return attributeFor(model, name).condition(value) !== noMatch;
5208
+ /** What a purpose's tokens are signed for: the Model's table, the purpose, and how long they last. */
5209
+ function tokenForPurpose(model, { purpose, expiresIn }) {
5210
+ return signedPurposeOf(model, purpose, expiresIn === void 0 ? null : secondsOf(expiresIn, "expiresIn"));
5211
+ }
5212
+ /** A token for `purpose`, for a saved record; `RecordNotSaved` for a new one. */
5213
+ async function tokenFor(record, purpose) {
5214
+ const model = record.constructor;
5215
+ const definition = definitionOf(model, purpose);
5216
+ const id = signableIdOf(record, "generateTokenFor");
5217
+ const { expiresIn, dependsOn } = definition;
5218
+ return (await signerOf(model, "token for")).sign(tokenForPurpose(model, definition), {
5219
+ id,
5220
+ ...expiresIn !== void 0 && { expiresAt: expiryAfter(expiresIn, "expiresIn") },
5221
+ ...dependsOn !== void 0 && { dependsOn: await dependsOn(record) }
5222
+ });
4961
5223
  }
4962
- // src/message-signing.ts
4963
- /** The bytes of a fingerprint kept in a token: enough that guessing one is hopeless. */
4964
- const FINGERPRINT_BYTES = 12;
4965
- const SIGNATURE_BYTES = 32;
4966
5224
  /**
4967
- * The longest token: room for an id of about 700 characters, its expiry and a fingerprint, far
4968
- * more than a key's id needs; signing a longer one throws. A longer token is
4969
- * refused before its signature is checked, so a huge one costs nothing.
5225
+ * Looks up the record a token for `purpose` finds through `finder`, while it hasn't expired and
5226
+ * what it depends on is unchanged.
4970
5227
  */
4971
- const MAX_TOKEN_LENGTH = 1024;
4972
- /** base64url without padding. */
4973
- const BASE64URL = /^[\w-]+$/;
4974
- /** A signer for `feature`'s tokens: the first secret signs, and each one verifies. */
4975
- function signerFor(secrets, feature) {
4976
- const keys = secrets.map((secret) => keysFor(secret, feature));
4977
- return {
4978
- async sign(purpose, message) {
4979
- const { id, expiresAt, dependsOn } = message;
4980
- const key = await keys[0];
4981
- const fingerprint = Object.hasOwn(message, "dependsOn") ? await fingerprintOf(key, purpose, id, dependsOn) : null;
4982
- const expiry = expiresAt === void 0 ? null : secondsSinceEpoch(expiresAt);
4983
- const payload = encode(new TextEncoder().encode(JSON.stringify(trimmed([
4984
- id,
4985
- expiry,
4986
- fingerprint
4987
- ]))));
4988
- const signature = await crypto.subtle.sign("HMAC", key.signing, signedBytes(purpose, payload));
4989
- const token = `${payload}.${encode(new Uint8Array(signature))}`;
4990
- if (token.length > MAX_TOKEN_LENGTH) throw new TypeError(`A token's id is too long to sign: at most ${MAX_TOKEN_LENGTH} characters in all`);
4991
- return token;
4992
- },
4993
- async verify(purpose, token) {
4994
- const parts = partsOf(token);
4995
- if (parts === void 0) return void 0;
4996
- const data = signedBytes(purpose, parts.payload);
4997
- const signedWith = await keysThatSigned(keys, data, parts.signature);
4998
- return signedWith === void 0 ? void 0 : messageIn(signedWith, purpose, parts.payload);
4999
- }
5228
+ async function findByTokenFor(finder, purpose, token) {
5229
+ const definition = definitionOf(finder.model, purpose);
5230
+ const signing = {
5231
+ signer: await signerOf(finder.model, "token for"),
5232
+ purpose: tokenForPurpose(finder.model, definition)
5000
5233
  };
5234
+ const { dependsOn } = definition;
5235
+ if (dependsOn === void 0) return lookUpToken(finder, signing, token);
5236
+ return lookUpToken(finder, signing, token, async (record, verified) => verified.isUnchanged(await dependsOn(record)));
5001
5237
  }
5002
- /** A token's payload and signature's bytes, or undefined when it isn't shaped as one, or spelled as `encode` doesn't. */
5003
- function partsOf(token) {
5004
- if (token.length > MAX_TOKEN_LENGTH) return void 0;
5005
- const [payload = "", signature = "", ...rest] = token.split(".");
5006
- if (rest.length > 0 || !BASE64URL.test(payload) || !BASE64URL.test(signature)) return void 0;
5007
- const bytes = decode(signature);
5008
- return bytes?.length === SIGNATURE_BYTES && encode(bytes) === signature ? {
5009
- payload,
5010
- signature: bytes
5011
- } : void 0;
5238
+ // src/token-finders.ts
5239
+ /** The finders by token every Relation has. */
5240
+ var TokenFinders = class {
5241
+ /**
5242
+ * The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for
5243
+ * the same `purpose` and it hasn't expired, and this Relation matches it; or null.
5244
+ */
5245
+ async findSigned(signedId, options) {
5246
+ return (await findSigned(this.#finder, signedId, options)).record;
5247
+ }
5248
+ /** Like `findSigned`, but throws `InvalidToken` for a signed id that isn't valid, and `RecordNotFound` when its record is gone. */
5249
+ async findSignedOrThrow(signedId, options) {
5250
+ const lookup = await findSigned(this.#finder, signedId, options);
5251
+ return foundByTokenOrThrow(this.#finder.model, lookup, "signed id");
5252
+ }
5253
+ /**
5254
+ * The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this
5255
+ * Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this
5256
+ * Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
5257
+ */
5258
+ async findByTokenFor(purpose, token) {
5259
+ return (await findByTokenFor(this.#finder, purpose, token)).record;
5260
+ }
5261
+ /**
5262
+ * Like `findByTokenFor`, but throws `InvalidToken` for a token that isn't valid, and
5263
+ * `RecordNotFound` when its record is gone or the value it depends on changed.
5264
+ */
5265
+ async findByTokenForOrThrow(purpose, token) {
5266
+ const lookup = await findByTokenFor(this.#finder, purpose, token);
5267
+ return foundByTokenOrThrow(this.#finder.model, lookup, "token");
5268
+ }
5269
+ /** This Relation, as a token's record is found through it. */
5270
+ get #finder() {
5271
+ return {
5272
+ model: this[queryOf].model,
5273
+ findBy: (conditions) => this.findBy(conditions)
5274
+ };
5275
+ }
5276
+ };
5277
+ // src/count-questions.ts
5278
+ /** @internal What a Relation's questions about how many records it has read. */
5279
+ const countSource = Symbol("countSource");
5280
+ /** The questions about how many records every Relation has. */
5281
+ var CountQuestions = class extends TokenFinders {
5282
+ /**
5283
+ * The number of records: a loaded association's (built records included) without a query;
5284
+ * otherwise a `COUNT(*)`, plus an association's unsaved built records.
5285
+ */
5286
+ async size() {
5287
+ return size(this[countSource]());
5288
+ }
5289
+ /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
5290
+ async isEmpty() {
5291
+ return isEmpty(this[countSource]());
5292
+ }
5293
+ /** Whether there are any records: the opposite of `isEmpty()`. */
5294
+ async hasAny() {
5295
+ return !await this.isEmpty();
5296
+ }
5297
+ /** Whether more than one record matches: one `COUNT` of at most two rows. */
5298
+ async hasMoreThanOne() {
5299
+ return await upToTwo(this[countSource]()) > 1;
5300
+ }
5301
+ /** Whether exactly one record matches: one `COUNT` of at most two rows. */
5302
+ async hasExactlyOne() {
5303
+ return await upToTwo(this[countSource]()) === 1;
5304
+ }
5305
+ };
5306
+ // src/query-rewrites.ts
5307
+ /** Each part `unscope` drops, as the query without it. */
5308
+ const WITHOUT = {
5309
+ where: (query) => ({
5310
+ ...query,
5311
+ conditions: []
5312
+ }),
5313
+ order: (query) => ({
5314
+ ...without(query, "reordered"),
5315
+ order: []
5316
+ }),
5317
+ limit: (query) => without(query, "limit"),
5318
+ offset: (query) => without(query, "offset"),
5319
+ select: (query) => without(query, "select"),
5320
+ distinct: (query) => without(query, "distinct"),
5321
+ includes: (query) => without(query, "includes"),
5322
+ joins: (query) => withoutJoins(query, "inner"),
5323
+ leftJoins: (query) => withoutJoins(query, "left"),
5324
+ createWith: (query) => without(query, "createWith")
5325
+ };
5326
+ /** A copy of `query` without the optional `key`. */
5327
+ function without(query, key) {
5328
+ const copy = { ...query };
5329
+ delete copy[key];
5330
+ return copy;
5012
5331
  }
5013
- /**
5014
- * The keys whose signature `data` has, if any's. Every key is tried, so the time taken doesn't
5015
- * say which signed it.
5016
- */
5017
- async function keysThatSigned(keys, data, signature) {
5018
- let signer;
5019
- for (const each of keys) {
5020
- const key = await each;
5021
- if (await crypto.subtle.verify("HMAC", key.signing, signature, data)) signer ??= key;
5332
+ /** `query` without `part`. */
5333
+ function withoutPart(query, part) {
5334
+ requirePart(part);
5335
+ return keepingOwnerLink(WITHOUT[part](query));
5336
+ }
5337
+ /** Refuses a part `unscope` and `only` don't know: `"group"`, or a misspelling. */
5338
+ function requirePart(part) {
5339
+ if (typeof part !== "string" || !Object.hasOwn(WITHOUT, part)) {
5340
+ const parts = Object.keys(WITHOUT).map((name) => `"${name}"`);
5341
+ throw new TypeError(`A query's parts are ${parts.join(", ")}; got ${String(part)}`);
5022
5342
  }
5023
- return signer;
5024
5343
  }
5025
- /** A token's expiry, in whole Unix seconds; `TypeError` for one that isn't a time. */
5026
- function secondsSinceEpoch(expiresAt) {
5027
- const seconds = Math.floor(Number(expiresAt.getTime()) / 1e3);
5028
- if (!Number.isSafeInteger(seconds)) throw new TypeError("A token's expiry must be a valid Date");
5029
- return seconds;
5344
+ /** `query` with only the parts named: every other part is dropped. */
5345
+ function withOnly(query, parts) {
5346
+ for (const part of parts) requirePart(part);
5347
+ return Object.keys(WITHOUT).filter((part) => !parts.includes(part)).reduce(withoutPart, query);
5348
+ }
5349
+ /** `query` without the associations it joins this way, and their joins in turn. */
5350
+ function withoutJoins(query, kind) {
5351
+ const joins = (query.joins ?? []).filter((join) => join.kind !== kind);
5352
+ const used = joinedPaths(query).find((path) => !joins.some((join) => join.association === path));
5353
+ if (used !== void 0) throw new IncompatibleRelation(`unscope() can't drop the join of "${used}": conditions or an order merged onto it use it`);
5354
+ return joins.length === 0 ? without(query, "joins") : {
5355
+ ...query,
5356
+ joins
5357
+ };
5358
+ }
5359
+ /** The associations joined at the top that a merged Relation's conditions or order are on. */
5360
+ function joinedPaths({ conditions, order }) {
5361
+ return [...conditions.flatMap(joinedPathsIn), ...order.flatMap((term) => term instanceof JoinedOrder ? [term.path] : [])].map((path) => path.split(".")[0]);
5362
+ }
5363
+ /** The join paths a condition's merged conditions are on, at any depth. */
5364
+ function joinedPathsIn(condition) {
5365
+ if (condition instanceof JoinedConditions) return [condition.path];
5366
+ if (condition instanceof Negated) return joinedPathsIn(condition.condition);
5367
+ if (condition instanceof Either) return [...condition.left, ...condition.right].flatMap(joinedPathsIn);
5368
+ return [];
5030
5369
  }
5031
5370
  /**
5032
- * Each secret's keys, by feature. Module-level, but not request state (ADR-0003): derived only
5033
- * from the secret, which every request shares.
5371
+ * `query` without its conditions on `attributes` (`unscope({ where })`): an object condition
5372
+ * loses those keys, and a `whereNot` or `or` condition goes when it names only them. A fragment,
5373
+ * a condition merged onto a join, and one naming other attributes too are kept.
5034
5374
  */
5035
- const derived = /* @__PURE__ */ new Map();
5036
- function keysFor(secret, feature) {
5037
- const cacheKey = `${feature}\n${secret}`;
5038
- let keys = derived.get(cacheKey);
5039
- if (keys === void 0) {
5040
- keys = deriveKeys(secret, feature);
5041
- derived.set(cacheKey, keys);
5042
- }
5043
- return keys;
5375
+ function withoutConditionsOn(query, attributes) {
5376
+ const resolved = new Set(attributes.map((name) => attributeName(query.model, name)));
5377
+ const isDropped = (name) => resolved.has(attributeName(query.model, name));
5378
+ const link = new Set(query.ownerLink);
5379
+ const conditions = query.conditions.flatMap((condition) => link.has(condition) ? [condition] : remainderOf(condition, isDropped));
5380
+ return keepingOwnerLink({
5381
+ ...query,
5382
+ conditions
5383
+ });
5044
5384
  }
5045
- async function deriveKeys(secret, feature) {
5046
- const material = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), "HKDF", false, ["deriveKey"]);
5047
- const derive = (use) => crypto.subtle.deriveKey({
5048
- name: "HKDF",
5049
- hash: "SHA-256",
5050
- salt: new TextEncoder().encode("@forestfuture/active-record"),
5051
- info: new TextEncoder().encode(`${feature} ${use}`)
5052
- }, material, {
5053
- name: "HMAC",
5054
- hash: "SHA-256",
5055
- length: 256
5056
- }, false, ["sign", "verify"]);
5057
- const [signing, fingerprinting] = await Promise.all([derive("signing"), derive("fingerprint")]);
5385
+ /** `query` with `condition` added as part of its link to an association's owner (#350). */
5386
+ function withOwnerLink(query, condition) {
5387
+ const ownerLink = [...query.ownerLink ?? [], condition];
5058
5388
  return {
5059
- signing,
5060
- fingerprinting
5389
+ ...query,
5390
+ conditions: [...query.conditions, condition],
5391
+ ownerLink
5392
+ };
5393
+ }
5394
+ /**
5395
+ * `query` with each condition of its owner link that a rewrite dropped added back (#350): within
5396
+ * an `or`, dropping the `or` drops the link with it, so the link is ANDed on again.
5397
+ */
5398
+ function keepingOwnerLink(query) {
5399
+ const lost = (query.ownerLink ?? []).filter((link) => !query.conditions.some((condition) => hasLink(condition, link)));
5400
+ return lost.length === 0 ? query : {
5401
+ ...query,
5402
+ conditions: [...query.conditions, ...lost]
5061
5403
  };
5062
5404
  }
5063
- /** What a token's signature covers: its purpose, quoted so no purpose runs into its payload. */
5064
- function signedBytes(purpose, payload) {
5065
- return new TextEncoder().encode(`${JSON.stringify(purpose)}.${payload}`);
5405
+ /** Whether `condition` is `link`, or has it within an `or` or a `whereNot`. */
5406
+ function hasLink(condition, link) {
5407
+ if (condition === link) return true;
5408
+ if (condition instanceof Either) return [...condition.left, ...condition.right].some((each) => hasLink(each, link));
5409
+ return condition instanceof Negated && hasLink(condition.condition, link);
5410
+ }
5411
+ /** Whether a condition is an object of attribute values, `where({ role: "admin" })`. */
5412
+ function isAttributeValues(condition) {
5413
+ return isPlainObject(condition);
5414
+ }
5415
+ /** What's left of `condition` once those on `dropped` attributes go: itself, part of it, or nothing. */
5416
+ function remainderOf(condition, isDropped) {
5417
+ if (isAttributeValues(condition)) {
5418
+ const left = Object.entries(condition).filter(([name]) => !isDropped(name));
5419
+ return left.length === 0 ? [] : [Object.fromEntries(left)];
5420
+ }
5421
+ const named = attributesNamed(condition);
5422
+ return named !== void 0 && named.size > 0 && [...named].every(isDropped) ? [] : [condition];
5066
5423
  }
5067
5424
  /**
5068
- * A value's fingerprint for one record's token for one purpose: their JSON, signed with the
5069
- * fingerprint key, cut short. Each record and purpose fingerprints a value apart, so equal
5070
- * fingerprints never say two records share it.
5425
+ * The attributes a condition names, or undefined when that can't be known: a fragment's SQL, or
5426
+ * a joined Model's conditions.
5071
5427
  */
5072
- async function fingerprintOf(keys, purpose, id, value) {
5073
- const json = new TextEncoder().encode(JSON.stringify([
5074
- purpose,
5075
- id,
5076
- value ?? null
5077
- ]));
5078
- const signature = await crypto.subtle.sign("HMAC", keys.fingerprinting, json);
5079
- return encode(new Uint8Array(signature).slice(0, FINGERPRINT_BYTES));
5080
- }
5081
- /** A payload without the nulls at its end. */
5082
- function trimmed(values) {
5083
- let end = values.length;
5084
- while (end > 1 && values[end - 1] === null) end -= 1;
5085
- return values.slice(0, end);
5428
+ function attributesNamed(condition) {
5429
+ if (isAttributeValues(condition)) return new Set(Object.keys(condition));
5430
+ if (condition instanceof Negated) return attributesNamed(condition.condition);
5431
+ if (condition instanceof LinkedTo) return /* @__PURE__ */ new Set([condition.attribute]);
5432
+ if (condition instanceof Either) return namedByAll([...condition.left, ...condition.right]);
5086
5433
  }
5087
- /** Whether a payload's expiry has passed, or isn't a whole number of Unix seconds; never without one. */
5088
- function hasExpired(expiry) {
5089
- if (expiry === null) return false;
5090
- if (typeof expiry !== "number" || !Number.isSafeInteger(expiry)) return true;
5091
- return expiry * 1e3 <= Date.now();
5434
+ /** The attributes several conditions name together, or undefined when any's can't be known. */
5435
+ function namedByAll(conditions) {
5436
+ const names = /* @__PURE__ */ new Set();
5437
+ for (const condition of conditions) {
5438
+ const named = attributesNamed(condition);
5439
+ if (named === void 0) return void 0;
5440
+ for (const name of named) names.add(name);
5441
+ }
5442
+ return names;
5092
5443
  }
5093
- /** The message in a signed payload, unless it's expired or isn't one this module made. */
5094
- function messageIn(keys, purpose, payload) {
5095
- const [id, expiry = null, fingerprint = null] = parsedPayload(payload) ?? [];
5096
- if (!(typeof id === "string" || typeof id === "number" && Number.isSafeInteger(id)) || hasExpired(expiry)) return void 0;
5444
+ /** `query` without one part `unscope` was given: a part's name, or `{ where: attributes }`, which it keeps for `merge`. */
5445
+ function unscoped(query, given) {
5446
+ const part = unscopedPart(query, given);
5097
5447
  return {
5098
- id,
5099
- async isUnchanged(value) {
5100
- if (typeof fingerprint !== "string") return false;
5101
- return fingerprint === await fingerprintOf(keys, purpose, id, value);
5102
- }
5448
+ ...withoutUnscoped(query, part),
5449
+ unscoped: [...query.unscoped ?? [], part]
5103
5450
  };
5104
5451
  }
5105
- /** A payload's values, or undefined when it isn't a JSON array. */
5106
- function parsedPayload(payload) {
5107
- const bytes = decode(payload);
5108
- if (bytes === void 0) return void 0;
5109
- try {
5110
- const values = JSON.parse(new TextDecoder("utf-8", {
5111
- fatal: true,
5112
- ignoreBOM: false
5113
- }).decode(bytes));
5114
- return Array.isArray(values) ? values : void 0;
5115
- } catch {
5116
- return;
5452
+ /** What `unscope` was given, checked, with `{ where }`'s attributes as a list. */
5453
+ function unscopedPart(query, given) {
5454
+ if (typeof given === "string") {
5455
+ requirePart(given);
5456
+ return given;
5117
5457
  }
5458
+ if (typeof given !== "object" || given === null || !("where" in given)) throw new TypeError(`unscope() takes a part's name, or { where: attributes }; got ${String(given)}`);
5459
+ const attributes = typeof given.where === "string" ? [given.where] : [...given.where];
5460
+ for (const name of attributes) columnOf(query.model, name);
5461
+ return { where: attributes };
5118
5462
  }
5119
- function encode(bytes) {
5120
- let binary = "";
5121
- for (const byte of bytes) binary += String.fromCharCode(byte);
5122
- return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
5123
- }
5124
- /** base64url's bytes, or undefined for text that isn't base64url. */
5125
- function decode(text) {
5126
- try {
5127
- const binary = atob(text.replaceAll("-", "+").replaceAll("_", "/"));
5128
- return Uint8Array.from(binary, (character) => character.charCodeAt(0));
5129
- } catch {
5130
- return;
5131
- }
5463
+ /** `query` without one part `unscope` dropped. */
5464
+ function withoutUnscoped(query, part) {
5465
+ return typeof part === "string" ? withoutPart(query, part) : withoutConditionsOn(query, part.where);
5132
5466
  }
5133
- // src/workers-env.ts
5134
- /** Whether importing `cloudflare:workers` failed because this isn't a Worker (Node, scripts). */
5135
- function isOutsideWorker(error) {
5136
- const { code, message } = error;
5137
- return code === "ERR_UNSUPPORTED_ESM_URL_SCHEME" || code === "ERR_MODULE_NOT_FOUND" || /cloudflare:workers/.test(String(message));
5467
+ /**
5468
+ * `into` with the parts `other` was unscoped of dropped, before `other` merges into it,
5469
+ * so an unscope carries over; only for a Relation of the same Model, whose parts they name.
5470
+ */
5471
+ function withUnscopesOf(into, other) {
5472
+ if (other.unscoped === void 0 || other.model !== into.model) return into;
5473
+ return other.unscoped.reduce(withoutUnscoped, into);
5138
5474
  }
5139
5475
  /**
5140
- * The Worker's `env`, from `load`, or undefined outside a Worker (Node, scripts). An adapter
5141
- * passes `() => import("cloudflare:workers")` from its own module, with that literal specifier:
5142
- * Wrangler only bundles those, and a test that mocks the module with the adapter inlined reaches it.
5476
+ * `query` with `conditions` in place of those on their attributes (`rewhere`):
5477
+ * conditions on other attributes, and fragments, are kept.
5143
5478
  */
5144
- async function workersEnv(load) {
5145
- try {
5146
- return (await load()).env;
5147
- } catch (error) {
5148
- if (isOutsideWorker(error)) return void 0;
5149
- throw error;
5150
- }
5479
+ function withConditionsReplaced(query, conditions) {
5480
+ requireAttributeConditions(conditions, "rewhere");
5481
+ checkConditions(query.model, conditions, "rewhere");
5482
+ const names = Object.keys(conditions);
5483
+ if (names.length === 0) return query;
5484
+ const rest = withoutConditionsOn(query, names);
5485
+ const normalized = normalizedConditions(query.model, conditions);
5486
+ return {
5487
+ ...rest,
5488
+ conditions: [...rest.conditions, normalized]
5489
+ };
5490
+ }
5491
+ /** `query` without these records (`excluding`), by primary key: `NOT (id IN (…))`. */
5492
+ function withoutRecords(query, records) {
5493
+ const keys = excludedKeys(query.model, records);
5494
+ if (keys.length === 0) return query;
5495
+ const left = new Negated({ [query.model.primaryKey]: keys });
5496
+ return {
5497
+ ...query,
5498
+ conditions: [...query.conditions, left]
5499
+ };
5151
5500
  }
5152
- // src/signing-secret.ts
5153
- /** The fewest bytes a secret has: HMAC-SHA256's own key length. */
5154
- const MINIMUM_BYTES = 32;
5155
5501
  /**
5156
- * The Worker's env, read once. Module-level, but not request state (ADR-0003): it's the
5157
- * Worker's, the same for every request.
5502
+ * The primary keys of the records `excluding` leaves out, each a record of `model` (or a class
5503
+ * extending it); a record without a key yet has no row to leave out.
5158
5504
  */
5159
- let workerEnv;
5160
- /** The env secrets are read from: the Worker's, or else the process's (tests, scripts). */
5161
- async function envForSecrets() {
5162
- workerEnv ??= workersEnv(() => import("cloudflare:workers"));
5163
- return await workerEnv ?? processEnv() ?? {};
5505
+ function excludedKeys(model, records) {
5506
+ return records.flat().flatMap((record) => {
5507
+ if (!(record instanceof model)) throw new TypeError(`excluding() takes records of ${model.name}; got ${describedValue(record)}`);
5508
+ const key = primaryKeyOf(record);
5509
+ return key === null || key === void 0 ? [] : [key];
5510
+ });
5164
5511
  }
5165
- /** `process.env`, where there's one: Node, and Workers with Node.js compatibility. */
5166
- function processEnv() {
5167
- return globalThis.process?.env;
5512
+ /** How a refusal names what it was given: a record's class, or its type. */
5513
+ function describedValue(value) {
5514
+ if (value instanceof Model) return `a ${value.constructor.name}`;
5515
+ return value === null ? "null" : typeof value;
5168
5516
  }
5169
- /** A signer for `model`'s `feature` tokens; `InvalidModel` when its secrets are unset or short. */
5170
- async function signerOf(model, feature) {
5171
- return signerFor(secretsOf(model, await envForSecrets()), feature);
5517
+ // src/record-creation.ts
5518
+ /**
5519
+ * @internal A new, unsaved record through `relation`, handed to `init`, which mustn't return a promise
5520
+ * (`TypeError`): nothing awaits it. Through a hasMany, the record then joins the association,
5521
+ * so a record whose `init` throws doesn't.
5522
+ */
5523
+ function buildThrough(relation, attributes, init) {
5524
+ const record = recordToBuild(relation, attributes);
5525
+ refuseInitPromise(relation.model, init?.(record));
5526
+ runBuiltCallbacks(record);
5527
+ relation.collection.built(record);
5528
+ return record;
5172
5529
  }
5173
- function secretsOf(model, env) {
5174
- const given = model.signingSecret(env);
5175
- const secrets = (Array.isArray(given) ? given : [given]).filter((secret) => secret !== void 0 && secret !== null);
5176
- if (secrets.length === 0) throw new InvalidModel(`${model.name} has no signing secret: set SECRET_KEY_BASE in the Worker's secrets (wrangler secret put SECRET_KEY_BASE), or override signingSecret`);
5177
- for (const secret of secrets) if (typeof secret !== "string" || new TextEncoder().encode(secret).length < MINIMUM_BYTES) throw new InvalidModel(`${model.name}'s signing secret must be a string of at least ${MINIMUM_BYTES} bytes, such as openssl rand -hex 32 makes`);
5178
- return secrets;
5530
+ /** Throws `TypeError` if a `build` `init` returned a promise, which `build` can't await. */
5531
+ function refuseInitPromise(model, result) {
5532
+ refuseThenable(result, `${model.name}.build(): init returned a promise, which build can't await; findOrInitializeBy and create await it`);
5179
5533
  }
5180
- // src/token-records.ts
5181
- /** A saved record's primary key, which a token holds; `RecordNotSaved` for a new record. */
5182
- function signableIdOf(record, method) {
5183
- const model = record.constructor;
5184
- if (record[state].isNew) throw new RecordNotSaved(`${model.name} record hasn't been saved, so ${method} has no id to sign`);
5185
- return record[state].read(model.primaryKey);
5534
+ /** @internal `buildThrough`, awaiting `init`: what `findOrInitializeBy` builds. */
5535
+ async function initializeThrough(relation, attributes, init) {
5536
+ const record = recordToBuild(relation, attributes);
5537
+ await init?.(record);
5538
+ runBuiltCallbacks(record);
5539
+ relation.collection.built(record);
5540
+ return record;
5186
5541
  }
5187
- /** What a Model's token is signed for: its table, then what else the token is for. */
5188
- function signedPurposeOf(model, ...parts) {
5189
- return JSON.stringify([model.table, ...parts]);
5542
+ /** @internal Builds and saves a record through `relation`; `orThrow` throws if it can't be saved. */
5543
+ async function createThrough(relation, attributes, { init, orThrow }) {
5544
+ const record = await recordToCreate(relation, attributes, init);
5545
+ await saveCreated(relation, record, orThrow);
5546
+ return record;
5190
5547
  }
5191
5548
  /**
5192
- * Looks up the record a token finds through `finder`, if `signer` signed it for `purpose` and it
5193
- * hasn't expired, and `isStillFor` (when given) says the record is still the one it was for. A
5194
- * value that isn't a string isn't a valid token.
5549
+ * @internal Creates a record through `relation`, as `createThrough` does, or `find`s the row a unique
5550
+ * index kept it from duplicating. It finds only for a record saved alone: when `init` gave it
5551
+ * records to save with it, a refusal may be theirs, so any `RecordNotUnique` reaches the caller.
5195
5552
  */
5196
- async function lookUpToken(finder, { signer, purpose }, token, isStillFor) {
5197
- const verified = typeof token === "string" ? await signer.verify(purpose, token) : void 0;
5198
- if (verified === void 0) return {
5199
- isValid: false,
5200
- record: null
5201
- };
5202
- const record = await finder.findBy(asStored({ [finder.model.primaryKey]: verified.id }));
5203
- return {
5204
- isValid: true,
5205
- record: record !== null && (isStillFor === void 0 || await isStillFor(record, verified)) ? record : null
5206
- };
5553
+ async function createOrFindThrough(relation, attributes, options) {
5554
+ const record = await recordToCreate(relation, attributes, options.init);
5555
+ const isSavedAlone = record[state].autosaves.isEmpty();
5556
+ try {
5557
+ await saveCreated(relation, record, options.orThrow);
5558
+ return record;
5559
+ } catch (error) {
5560
+ if (!isSavedAlone || !(error instanceof RecordNotUnique)) throw error;
5561
+ return options.find();
5562
+ }
5563
+ }
5564
+ async function recordToCreate(relation, attributes, init) {
5565
+ requireSavedOwner$1(relation, "create");
5566
+ const record = recordToBuild(relation, attributes);
5567
+ await init?.(record);
5568
+ runBuiltCallbacks(record);
5569
+ return record;
5207
5570
  }
5208
- /**
5209
- * The record a lookup found; `InvalidToken` (naming `what`) for a token that isn't valid, and
5210
- * `RecordNotFound` when a valid one found none.
5211
- */
5212
- function foundByTokenOrThrow(model, { isValid, record }, what) {
5213
- if (!isValid) throw new InvalidToken(`The ${what} isn't valid: it's changed, expired, or for another purpose`);
5214
- return foundOrThrow(model, record);
5571
+ /** A new record through `relation`, pointing back at its owner if it has one. */
5572
+ function recordToBuild(relation, attributes) {
5573
+ const record = newRecord(relation, attributes);
5574
+ relation.collection.pointBack(record);
5575
+ return record;
5215
5576
  }
5216
- // src/signed-ids.ts
5217
- /** What a signed id is signed for: its Model's table, and its purpose. */
5218
- function signedIdPurpose(model, purpose) {
5219
- return signedPurposeOf(model, purpose ?? null);
5577
+ async function saveCreated(relation, record, orThrow) {
5578
+ const { collection } = relation;
5579
+ if (await saveThrough(collection, record, orThrow)) collection.created(record);
5220
5580
  }
5221
- /** When a token expires: `expiresAt`, or `expiresIn` from now; `TypeError` for both. */
5222
- function expiryOf({ expiresIn, expiresAt }, where) {
5223
- if (expiresIn !== void 0 && expiresAt !== void 0) throw new TypeError(`${where} takes expiresIn or expiresAt, not both`);
5224
- if (expiresIn !== void 0) return expiryAfter(expiresIn, `${where}'s expiresIn`);
5225
- if (expiresAt !== void 0 && !(expiresAt instanceof Date && Number.isFinite(expiresAt.getTime()))) throw new TypeError(`${where}'s expiresAt must be a valid Date`);
5226
- return expiresAt;
5581
+ /** Saves a record created through `collection`, as its `saveCreated` says, or as the record saves. */
5582
+ function saveThrough(collection, record, orThrow) {
5583
+ return collection.saveCreated?.(record, orThrow) ?? (orThrow ? record.saveOrThrow() : record.save());
5227
5584
  }
5228
- /** A record's signed id, made with its Model's newest secret. */
5229
- async function signedIdOf(record, options = {}) {
5230
- const model = record.constructor;
5231
- const id = signableIdOf(record, "signedId");
5232
- const expiresAt = expiryOf(options, "signedId");
5233
- return (await signerOf(model, "signed id")).sign(signedIdPurpose(model, options.purpose), {
5234
- id,
5235
- ...expiresAt && { expiresAt }
5236
- });
5585
+ function newRecord(relation, attributes) {
5586
+ const { assigned, kept } = builtRecordValues(relation, attributes);
5587
+ return buildRecord(relation.model, assigned, relation.executor, kept);
5237
5588
  }
5238
- /** Looks up the record a signed id finds through `finder`, if its Model's secret signed it for `purpose`. */
5239
- async function findSigned(finder, signedId, { purpose } = {}) {
5240
- return lookUpToken(finder, {
5241
- signer: await signerOf(finder.model, "signed id"),
5242
- purpose: signedIdPurpose(finder.model, purpose)
5243
- }, signedId);
5589
+ // src/find-or-create.ts
5590
+ /** @internal `findOrCreateBy` and `findOrCreateByOrThrow`: the record found, or one created. */
5591
+ async function findOrCreate(call, attributes, { init, orThrow }) {
5592
+ const found = await findExisting(call, attributes);
5593
+ if (found !== null) return found;
5594
+ return orThrow ? call.relation.createOrThrow(attributes, init) : call.relation.create(attributes, init);
5244
5595
  }
5245
- // src/tokens-for.ts
5246
- const OPTION_NAMES = /* @__PURE__ */ new Set(["expiresIn", "dependsOn"]);
5247
- /** Declares a purpose's tokens on `model`; `InvalidModel` for a declaration that isn't one. */
5248
- function declareTokenFor(model, purpose, options = {}) {
5249
- const where = `${model.name}.generatesTokenFor`;
5250
- if (typeof purpose !== "string" || purpose === "") throw new InvalidModel(`${where} takes a purpose, such as "emailConfirmation"`);
5251
- const unknown = Object.keys(options).filter((name) => !OPTION_NAMES.has(name));
5252
- if (unknown.length > 0) throw new InvalidModel(`${where}("${purpose}") takes expiresIn and dependsOn, not ${unknown.join(", ")}`);
5253
- if (options.dependsOn !== void 0 && typeof options.dependsOn !== "function") throw new InvalidModel(`${where}("${purpose}")'s dependsOn is a function of the record`);
5254
- if (options.expiresIn !== void 0) secondsOf(options.expiresIn, `${where}("${purpose}")'s expiresIn`);
5255
- declare(model, "tokenDefinitions", {
5256
- purpose,
5257
- ...options
5258
- });
5596
+ /** @internal `findOrInitializeBy`: the record found, or one built, its `init` awaited. */
5597
+ async function findOrInitialize(call, attributes, init) {
5598
+ return await findExisting(call, attributes) ?? initializeThrough(call.state, attributes, init);
5259
5599
  }
5260
5600
  /**
5261
- * The declaration of `purpose` on `model`, the last when it's declared again, after its secure
5262
- * passwords' reset tokens; `TypeError` when there's none.
5601
+ * @internal `createOrFindBy` and `createOrFindByOrThrow`: a record created, or the one a unique
5602
+ * index kept.
5263
5603
  */
5264
- function definitionOf(model, purpose) {
5265
- const resets = resetTokenDefinitions(model.attributeDefinitions);
5266
- const declarations = declared(model, "tokenDefinitions");
5267
- rejectResetPurposes(model, resets, declarations);
5268
- const found = [...resets, ...declarations].findLast((definition) => definition.purpose === purpose);
5269
- if (found === void 0) throw new TypeError(`${model.name} has no tokens for "${purpose}"; declare them with this.generatesTokenFor("${purpose}") in its static {} block`);
5270
- return found;
5604
+ async function createOrFind(call, attributes, options) {
5605
+ const { finder, conditions } = finderFor(call, attributes);
5606
+ const find = () => finder.findByOrThrow(conditions);
5607
+ return createOrFindThrough(call.state, attributes, {
5608
+ ...options,
5609
+ find
5610
+ });
5611
+ }
5612
+ /** The record with `attributes`, or null: what `findOrCreate` and `findOrInitialize` find. */
5613
+ function findExisting(call, attributes) {
5614
+ const { finder, conditions } = finderFor(call, attributes);
5615
+ return finder.findBy(conditions);
5271
5616
  }
5272
5617
  /**
5273
- * A declared purpose a reset token already uses is an `InvalidModel`: it would replace the reset
5274
- * token, which stops working once the password changes, with one that doesn't.
5618
+ * What finds the record with `attributes`, once they're checked: the Relation, narrowed by an
5619
+ * array the attribute casts as one value, compared whole, as the new record holds it, where
5620
+ * `findBy` would read it as a list; and the other attributes, as `findBy` reads them. They're
5621
+ * copied as own keys, so a `__proto__` key from parsed JSON stays an attribute `findBy` refuses.
5275
5622
  */
5276
- function rejectResetPurposes(model, resets, declarations) {
5277
- const clash = resets.find(({ purpose }) => declarations.some((each) => each.purpose === purpose));
5278
- if (clash === void 0) return;
5279
- throw new InvalidModel(`${model.name}.generatesTokenFor("${clash.purpose}") would replace a secure password's reset token; change how long it lasts with securePassword: { resetToken: { expiresIn } }`);
5280
- }
5281
- /** What a purpose's tokens are signed for: the Model's table, the purpose, and how long they last. */
5282
- function tokenForPurpose(model, { purpose, expiresIn }) {
5283
- return signedPurposeOf(model, purpose, expiresIn === void 0 ? null : secondsOf(expiresIn, "expiresIn"));
5623
+ function finderFor(call, attributes) {
5624
+ const entries = refuseConditionValues(call, attributes);
5625
+ let finder = call.relation;
5626
+ for (const [name, value] of entries) if (Array.isArray(value)) finder = finder.where(sql`${column(name)} = ${column(name).value(value)}`);
5627
+ const conditions = Object.fromEntries(entries.filter(([, value]) => !Array.isArray(value)));
5628
+ return {
5629
+ finder,
5630
+ conditions
5631
+ };
5284
5632
  }
5285
- /** A token for `purpose`, for a saved record; `RecordNotSaved` for a new one. */
5286
- async function tokenFor(record, purpose) {
5287
- const model = record.constructor;
5288
- const definition = definitionOf(model, purpose);
5289
- const id = signableIdOf(record, "generateTokenFor");
5290
- const { expiresIn, dependsOn } = definition;
5291
- return (await signerOf(model, "token for")).sign(tokenForPurpose(model, definition), {
5292
- id,
5293
- ...expiresIn !== void 0 && { expiresAt: expiryAfter(expiresIn, "expiresIn") },
5294
- ...dependsOn !== void 0 && { dependsOn: await dependsOn(record) }
5295
- });
5633
+ /**
5634
+ * Throws `TypeError`, before anything is sent, for attributes a find would read as a condition
5635
+ * but a new record can't take as its values: a list (except an array the attribute casts as one
5636
+ * value), which `findBy` reads as `IN`, so input that skipped `permit` can't match another
5637
+ * user's row; a comparison; a `sql` fragment, as the attributes or as one value; or anything
5638
+ * but an object, whose missing attributes would find any record. The value isn't shown, as it
5639
+ * may be filtered. Returns the attributes' entries, read once.
5640
+ */
5641
+ function refuseConditionValues({ state, method }, attributes) {
5642
+ const named = `${state.model.name}.${method}()`;
5643
+ if (attributes instanceof SafeSql) throw new TypeError(`${named} takes attribute values, not a sql fragment`);
5644
+ if (typeof attributes !== "object" || attributes === null || Array.isArray(attributes)) throw new TypeError(`${named} takes an object of attribute values`);
5645
+ const entries = Object.entries(attributes);
5646
+ for (const [name, value] of entries) {
5647
+ const kind = conditionKind(state.model, name, value);
5648
+ if (kind === void 0) continue;
5649
+ throw new TypeError(`${named}: "${name}" can't be ${kind}, since it becomes the new record's value`);
5650
+ }
5651
+ return entries;
5296
5652
  }
5297
5653
  /**
5298
- * Looks up the record a token for `purpose` finds through `finder`, while it hasn't expired and
5299
- * what it depends on is unchanged.
5654
+ * What a condition `value` of the attribute `name` is, when it's one a new record can't take as
5655
+ * its value. An array the attribute casts as one value is one: a json attribute's, or a custom
5656
+ * type's whose values are arrays.
5300
5657
  */
5301
- async function findByTokenFor(finder, purpose, token) {
5302
- const definition = definitionOf(finder.model, purpose);
5303
- const signing = {
5304
- signer: await signerOf(finder.model, "token for"),
5305
- purpose: tokenForPurpose(finder.model, definition)
5306
- };
5307
- const { dependsOn } = definition;
5308
- if (dependsOn === void 0) return lookUpToken(finder, signing, token);
5309
- return lookUpToken(finder, signing, token, async (record, verified) => verified.isUnchanged(await dependsOn(record)));
5658
+ function conditionKind(model, name, value) {
5659
+ if (Array.isArray(value)) return isOneValue(model, name, value) ? void 0 : "a list";
5660
+ if (value instanceof Comparison) return "a comparison";
5661
+ if (value instanceof SafeSql) return "a sql fragment";
5662
+ }
5663
+ /** Whether the attribute `name` casts the array `value` as one value, not as a list of them. */
5664
+ function isOneValue(model, name, value) {
5665
+ return attributeFor(model, name).condition(value) !== noMatch;
5310
5666
  }
5311
- // src/token-finders.ts
5312
- /** The finders by token every Relation has. */
5313
- var TokenFinders = class {
5314
- /**
5315
- * The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for
5316
- * the same `purpose` and it hasn't expired, and this Relation matches it; or null.
5317
- */
5318
- async findSigned(signedId, options) {
5319
- return (await findSigned(this.#finder, signedId, options)).record;
5320
- }
5321
- /** Like `findSigned`, but throws `InvalidToken` for a signed id that isn't valid, and `RecordNotFound` when its record is gone. */
5322
- async findSignedOrThrow(signedId, options) {
5323
- const lookup = await findSigned(this.#finder, signedId, options);
5324
- return foundByTokenOrThrow(this.#finder.model, lookup, "signed id");
5325
- }
5326
- /**
5327
- * The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this
5328
- * Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this
5329
- * Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
5330
- */
5331
- async findByTokenFor(purpose, token) {
5332
- return (await findByTokenFor(this.#finder, purpose, token)).record;
5333
- }
5334
- /**
5335
- * Like `findByTokenFor`, but throws `InvalidToken` for a token that isn't valid, and
5336
- * `RecordNotFound` when its record is gone or the value it depends on changed.
5337
- */
5338
- async findByTokenForOrThrow(purpose, token) {
5339
- const lookup = await findByTokenFor(this.#finder, purpose, token);
5340
- return foundByTokenOrThrow(this.#finder.model, lookup, "token");
5341
- }
5342
- /** This Relation, as a token's record is found through it. */
5343
- get #finder() {
5344
- return {
5345
- model: this[queryOf].model,
5346
- findBy: (conditions) => this.findBy(conditions)
5347
- };
5348
- }
5349
- };
5350
5667
  // src/grouping.ts
5351
5668
  /**
5352
5669
  * A Relation grouped by `group(...)`: its calculations resolve to a Map from each group's key to
@@ -5793,13 +6110,15 @@ function isTouchable(record, claimed) {
5793
6110
  /**
5794
6111
  * `target`'s touch write, setting what the association's `touch` names, then those it makes in
5795
6112
  * turn; nothing if this write has touched it already, or `noTouching` turned its Model's touches
5796
- * off (#496).
6113
+ * off (#496). A read-only target throws `ReadonlyRecord` (#358).
5797
6114
  */
5798
6115
  async function touchOne(target, { touch }, claimed) {
5799
6116
  const session = sessionOf(claimed);
5800
6117
  const model = modelOf(target);
5801
6118
  const key = touchKey(target);
5802
6119
  if (session.touched.has(key) || isCoveredByNoTouching(model)) return [];
6120
+ requireWritable(target, "touch");
6121
+ requireWritableColumns(model, touchAssignments(model, touch, "touch").map(([name]) => name));
5803
6122
  session.touched.add(key);
5804
6123
  let values;
5805
6124
  const valuesOf = () => values ??= Object.fromEntries(touchAssignments(model, touch, "touch", timeOf(session)));
@@ -5957,6 +6276,7 @@ async function touchRecord(record, args) {
5957
6276
  const model = modelOf(record);
5958
6277
  const values = touchValues(model, args, "touch");
5959
6278
  if (isCoveredByNoTouching(model)) return false;
6279
+ requireWritableColumns(model, Object.keys(values));
5960
6280
  const time = Object.values(values)[0];
5961
6281
  const writes = [touchWrite(record, () => values, { version: lockOf(record, "touch") }), ...await touchesOfTouch(record, time)];
5962
6282
  const [result] = await writeAll(record[state].executor, writes);
@@ -6094,7 +6414,7 @@ async function* batchesOf({ model, query, runner }, { batchSize, direction, boun
6094
6414
  let pastLast = [];
6095
6415
  while (left > 0) {
6096
6416
  const limit = Math.min(batchSize, left);
6097
- const rows = await runner.load({
6417
+ const rows = await withoutRequestCache(() => runner.load({
6098
6418
  ...query,
6099
6419
  conditions: [
6100
6420
  ...query.conditions,
@@ -6106,7 +6426,7 @@ async function* batchesOf({ model, query, runner }, { batchSize, direction, boun
6106
6426
  direction
6107
6427
  }],
6108
6428
  limit
6109
- });
6429
+ }));
6110
6430
  const records = eachOnce(rows);
6111
6431
  if (records.length > 0) yield records;
6112
6432
  if (rows.length < limit) return;
@@ -6183,7 +6503,7 @@ const ofOwner = Symbol("ofOwner");
6183
6503
  /** @internal The library's key for running a scope on a Relation. */
6184
6504
  const applyScope = Symbol("applyScope");
6185
6505
  /** A lazy, immutable description of a query against one Model. */
6186
- var Relation = class Relation extends TokenFinders {
6506
+ var Relation = class Relation extends CountQuestions {
6187
6507
  #executor;
6188
6508
  #model;
6189
6509
  #query;
@@ -6301,6 +6621,14 @@ var Relation = class Relation extends TokenFinders {
6301
6621
  return this.#with({ distinct: true });
6302
6622
  }
6303
6623
  /**
6624
+ * Makes the records this Relation loads read-only (#358): saving or destroying one throws
6625
+ * `ReadonlyRecord`. Records it preloads, builds or creates aren't, and its bulk writes ignore it.
6626
+ * `readonly(false)` undoes it.
6627
+ */
6628
+ readonly(flag = true) {
6629
+ return this.#with({ readonly: flag });
6630
+ }
6631
+ /**
6304
6632
  * Preloads associations for every record this Relation loads, so reading them afterwards
6305
6633
  * sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
6306
6634
  */
@@ -6387,7 +6715,8 @@ var Relation = class Relation extends TokenFinders {
6387
6715
  /**
6388
6716
  * Inserts a row now, or updates it when it clashes with the unique index on `uniqueBy` (the
6389
6717
  * primary key by default): every given attribute and every value this Relation writes into the
6390
- * row (#475), except the `uniqueBy` ones and `createdAt`, with `updatedAt` set.
6718
+ * row (#475), except the `uniqueBy` ones and `createdAt`, or only those `updateOnly` names
6719
+ * (#36), with `updatedAt` set when one of them changes.
6391
6720
  * Resolves as `insert` does, returning inserted and updated rows.
6392
6721
  */
6393
6722
  async upsert(attributes, options = {}) {
@@ -6625,31 +6954,8 @@ var Relation = class Relation extends TokenFinders {
6625
6954
  cached: () => this.#cached()
6626
6955
  };
6627
6956
  }
6628
- /**
6629
- * The number of records: a loaded association's (built records included) without a query;
6630
- * otherwise a `COUNT(*)`, plus an association's unsaved built records.
6631
- */
6632
- async size() {
6633
- return size(this.#countSource());
6634
- }
6635
- /** Whether there are no records: a loaded association answers itself, else `!exists()`. */
6636
- async isEmpty() {
6637
- return isEmpty(this.#countSource());
6638
- }
6639
- /** Whether there are any records: the opposite of `isEmpty()`. */
6640
- async hasAny() {
6641
- return !await this.isEmpty();
6642
- }
6643
- /** Whether more than one record matches: one `COUNT` of at most two rows. */
6644
- async hasMoreThanOne() {
6645
- return await upToTwo(this.#countSource()) > 1;
6646
- }
6647
- /** Whether exactly one record matches: one `COUNT` of at most two rows. */
6648
- async hasExactlyOne() {
6649
- return await upToTwo(this.#countSource()) === 1;
6650
- }
6651
- /** What `size` and the questions about how many records there are read. */
6652
- #countSource() {
6957
+ /** @internal What `size` and the questions about how many records there are read. */
6958
+ [countSource]() {
6653
6959
  return countSourceOf(this.#valueSource(), this.#collection);
6654
6960
  }
6655
6961
  /** Whether any record matches, optionally with extra conditions. */
@@ -7341,6 +7647,7 @@ async function prepareRemoval(old, association, claimed) {
7341
7647
  * nothing is written; one refused before writing keeps its key.
7342
7648
  */
7343
7649
  async function nullify(old, association, claimed) {
7650
+ requireWritable(old, "save");
7344
7651
  const restore = unlinkInMemory(old, association);
7345
7652
  const plan = await prepareSave(old, claimed);
7346
7653
  if (plan.status === "ready") return undoneOnFailure(plan, old, association, restore);
@@ -8086,7 +8393,8 @@ function rejectBadSpecs(model) {
8086
8393
  column,
8087
8394
  type: definition.customType ?? definition.type
8088
8395
  };
8089
- const problem = specProblem(`${model.name}.${name}`, declared);
8396
+ const where = `${model.name}.${name}`;
8397
+ const problem = specProblem(where, declared) ?? readonlyProblem(where, name, definition.readonly);
8090
8398
  if (problem !== void 0) throw new InvalidModel(problem);
8091
8399
  }
8092
8400
  }
@@ -8495,6 +8803,14 @@ var AnyDatabase = class {
8495
8803
  return Object.fromEntries(Object.entries(models).map(([name, model]) => [name, this.model(model)]));
8496
8804
  }
8497
8805
  /**
8806
+ * Empties the request cache of the running `withDatabase` call, every database's in it, so each
8807
+ * read after it is sent. Call it after a write the library didn't send, such as SQL sent on the
8808
+ * binding or client yourself, which it can't see. Outside `withDatabase` it does nothing.
8809
+ */
8810
+ clearRequestCache() {
8811
+ clearRequestCaches();
8812
+ }
8813
+ /**
8498
8814
  * Runs the writes `build` prepares atomically, on this Database: all of them are written, or
8499
8815
  * none. `db.batch((b) => [b.insert(Post, { title }), b.save(user)])`. The callback can't await,
8500
8816
  * since the batch is sent as one. Saves and destroys (`b.save(user)`, `b.destroy(post)`) run
@@ -8507,6 +8823,66 @@ var AnyDatabase = class {
8507
8823
  return runBatch(batchEntries(build, (model) => relationFor(this.#executor, model)), "db.batch() needs its statements and records", [this.#executor]);
8508
8824
  }
8509
8825
  };
8826
+ // src/request-cache.ts
8827
+ /**
8828
+ * Whether a bound value keys a read exactly as written as JSON: text, a finite number, a boolean,
8829
+ * null, bytes, or a list of those. Anything else (an ArrayBuffer, NaN, a BigInt, an object) would
8830
+ * share its JSON with another value, or have none.
8831
+ */
8832
+ function isKeyable(value) {
8833
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
8834
+ if (typeof value === "number") return Number.isFinite(value);
8835
+ if (value instanceof Uint8Array) return true;
8836
+ return Array.isArray(value) && value.every(isKeyable);
8837
+ }
8838
+ /** Bytes as an object no other bound value can be, so they never share a key with a list. */
8839
+ function tagBytes(_, value) {
8840
+ return value instanceof Uint8Array ? { bytes: [...value] } : value;
8841
+ }
8842
+ /**
8843
+ * A read's key: its SQL and the values it binds (a filtered one's real value), which only match
8844
+ * a read that's the same. A read binding a value that can't key it has none, so it's sent, and
8845
+ * the database answers it.
8846
+ */
8847
+ function keyOf({ sql, params }) {
8848
+ const bound = params.map(boundValue);
8849
+ return bound.every(isKeyable) ? JSON.stringify([sql, bound], tagBytes) : void 0;
8850
+ }
8851
+ /** How many answers a request cache keeps: enough for a request, bounded for a long one. */
8852
+ const CAPACITY = 100;
8853
+ /**
8854
+ * The answers one scope's database gave to its reads, each kept from when it's sent, so an
8855
+ * identical read sent meanwhile waits for it. Clearing forgets those in flight too. It keeps the
8856
+ * 100 used last: a Map iterates in insertion order, so each answer used is moved to its end.
8857
+ */
8858
+ var RequestCache = class {
8859
+ #answers = /* @__PURE__ */ new Map();
8860
+ /** The answer `read` has, or will have, if it was sent before, which it marks used last. */
8861
+ get(read) {
8862
+ const key = keyOf(read);
8863
+ if (key === void 0) return void 0;
8864
+ const answer = this.#answers.get(key);
8865
+ if (answer !== void 0) {
8866
+ this.#answers.delete(key);
8867
+ this.#answers.set(key, answer);
8868
+ }
8869
+ return answer;
8870
+ }
8871
+ /** Forgets every answer: its database was written to (or may have been, by a write that failed). */
8872
+ clear() {
8873
+ this.#answers.clear();
8874
+ }
8875
+ /** Keeps `answer` as `read`'s, unless it fails, or `read` has no key. Its failure is the caller's. */
8876
+ set(read, answer) {
8877
+ const key = keyOf(read);
8878
+ answer.catch(() => {
8879
+ if (key !== void 0 && this.#answers.get(key) === answer) this.#answers.delete(key);
8880
+ });
8881
+ if (key === void 0) return;
8882
+ this.#answers.set(key, answer);
8883
+ if (this.#answers.size > CAPACITY) this.#answers.delete(this.#answers.keys().next().value);
8884
+ }
8885
+ };
8510
8886
  // src/current-database.ts
8511
8887
  /**
8512
8888
  * Runs `fn` with `databases` as the request's own: queries started from a Model inside it (and
@@ -8523,16 +8899,20 @@ async function withDatabase(databases, fn) {
8523
8899
  const outer = requestStore();
8524
8900
  const inner = Array.isArray(databases) ? databases : [databases];
8525
8901
  const scopes = new Map(outer?.scopes);
8902
+ const caches = outer?.caches ?? /* @__PURE__ */ new Set();
8526
8903
  const opened = [];
8527
8904
  try {
8528
8905
  openScopes(inner, scopes, opened);
8906
+ for (const { scope } of opened) caches.add(scope.cache);
8529
8907
  return await runWithStore({
8530
8908
  databases: [.../* @__PURE__ */ new Set([...inner, ...outer?.databases ?? []])],
8531
- scopes
8909
+ scopes,
8910
+ caches
8532
8911
  }, fn);
8533
8912
  } finally {
8534
8913
  await Promise.all(opened.map(({ executor, scope }) => {
8535
8914
  scope.hasEnded = true;
8915
+ caches.delete(scope.cache);
8536
8916
  return executor.closeScope(scope.held);
8537
8917
  }));
8538
8918
  }
@@ -8548,7 +8928,8 @@ function openScopes(databases, scopes, opened) {
8548
8928
  if (scopes.get(executor)?.hasEnded === false) continue;
8549
8929
  const scope = {
8550
8930
  held: executor.openScope(),
8551
- hasEnded: false
8931
+ hasEnded: false,
8932
+ cache: new RequestCache()
8552
8933
  };
8553
8934
  scopes.set(executor, scope);
8554
8935
  opened.push({
@@ -9703,7 +10084,9 @@ function aborted(record) {
9703
10084
  async function saveLifecycle(record, context) {
9704
10085
  requireKnownContexts(record, context);
9705
10086
  const needs = "save() needs its records";
9706
- for (const { records } of savingGroups(record)) await pinBefore(linksOf(records), needs);
10087
+ const groups = savingGroups(record);
10088
+ requireSavesWritable(groups.flatMap(({ records }) => records));
10089
+ for (const { records } of groups) await pinBefore(linksOf(records), needs);
9707
10090
  return withClaimedRecords(async (claimed) => {
9708
10091
  const plan = await prepareSave(record, claimed, context);
9709
10092
  if (plan.status !== "ready") return plan;
@@ -9718,6 +10101,7 @@ async function saveLifecycle(record, context) {
9718
10101
  async function prepareSave(record, claimed, context) {
9719
10102
  if (claimed.has(record)) return nothing;
9720
10103
  record[state].requireLive("be saved");
10104
+ requireWritable(record, "save");
9721
10105
  const validity = await validation(record, claimed, newPass(context), context);
9722
10106
  if (validity === "invalid") return { status: "invalid" };
9723
10107
  if (validity === "aborted") return aborted(record);
@@ -9729,6 +10113,7 @@ async function prepareSave(record, claimed, context) {
9729
10113
  * it, they follow in the next one, once the owner is written.
9730
10114
  */
9731
10115
  async function prepareWrites(record, claimed) {
10116
+ requireWritable(record, "save");
9732
10117
  claimed.add(record);
9733
10118
  const before = await prepareBefore(record, claimed);
9734
10119
  if ("status" in before) return before;
@@ -9858,6 +10243,7 @@ async function destroyLifecycle(record) {
9858
10243
  /** Everything a destroy does before writing: beforeDestroy, then its dependents' plans. */
9859
10244
  async function prepareDestroy(record, claimed) {
9860
10245
  if (claimed.has(record)) return nothing;
10246
+ requireWritable(record, "destroy");
9861
10247
  claimed.add(record);
9862
10248
  const recordState = record[state];
9863
10249
  recordState.requireLive("be destroyed");
@@ -9912,7 +10298,7 @@ function destroyWrite(record, wrapped) {
9912
10298
  }
9913
10299
  /**
9914
10300
  * Loads the record's row again by its stored primary key, discarding unsaved changes, then runs its
9915
- * `afterFind` and `afterInitialize` (#49).
10301
+ * `afterFind` and `afterInitialize` (#49). It clears the request caches first, so it reads the database.
9916
10302
  */
9917
10303
  async function reloadRecord(record) {
9918
10304
  const recordState = record[state];
@@ -9927,6 +10313,7 @@ async function reloadRecord(record) {
9927
10313
  order: [],
9928
10314
  limit: 1
9929
10315
  };
10316
+ clearRequestCaches();
9930
10317
  const [row] = await executor.all(compileSelect(executor.dialect, query));
9931
10318
  if (row === void 0) throw new RecordNotFound(`${model.name} with ${model.primaryKey} ${shownKey(model, key)} not found`);
9932
10319
  recordState.clearAssociations();
@@ -9991,6 +10378,7 @@ const relationMethods = [
9991
10378
  "offset",
9992
10379
  "select",
9993
10380
  "distinct",
10381
+ "readonly",
9994
10382
  "includes",
9995
10383
  "joins",
9996
10384
  "leftJoins",
@@ -10270,7 +10658,7 @@ var AttributeWrites = class extends RecordTokens {
10270
10658
  * its Model's `noTouching` block, it writes nothing (#496).
10271
10659
  */
10272
10660
  async touch(...args) {
10273
- requireSaved(this, "touch");
10661
+ requireWritableRow(this, "touch");
10274
10662
  return touchRecord(this, args);
10275
10663
  }
10276
10664
  /**
@@ -10278,7 +10666,7 @@ var AttributeWrites = class extends RecordTokens {
10278
10666
  * validation or callback. Flip the attribute and `save()` to run the save callbacks.
10279
10667
  */
10280
10668
  async toggleColumn(name) {
10281
- requireSaved(this, "toggleColumn");
10669
+ requireWritableRow(this, "toggleColumn");
10282
10670
  return writeColumns(this, { [name]: isTrueOnceToggled(this, name, "toggleColumn") }, "toggleColumn");
10283
10671
  }
10284
10672
  };
@@ -10293,10 +10681,11 @@ function isTrueOnceToggled(record, name, method) {
10293
10681
  */
10294
10682
  async function addToColumn(record, name, by, { method, touch }) {
10295
10683
  const recordState = record[state];
10296
- requireSaved(record, method);
10684
+ requireWritableRow(record, method);
10297
10685
  const model = modelOf$1(record);
10298
10686
  const touched = touchAssignments(model, touch, method);
10299
10687
  const touchedNames = touched.map(([each]) => each);
10688
+ requireWritableColumns(model, touchedNames);
10300
10689
  const after = (numberValue(record, name, method) ?? 0) + by;
10301
10690
  const delta = after - (recordState.valueInDatabase(name) ?? 0);
10302
10691
  recordState.write(name, after);
@@ -10308,7 +10697,7 @@ async function addToColumn(record, name, by, { method, touch }) {
10308
10697
  /** Assigns `attributes`, then UPDATEs only them by the stored key, and marks them saved. */
10309
10698
  async function writeColumns(record, given, method) {
10310
10699
  const recordState = record[state];
10311
- requireSaved(record, method);
10700
+ requireWritableRow(record, method);
10312
10701
  const attributes = withAttributeNames(modelOf$1(record), given);
10313
10702
  const names = Object.keys(attributes);
10314
10703
  if (names.length === 0) throw new TypeError(`${method} needs at least one attribute to write`);
@@ -10319,10 +10708,14 @@ async function writeColumns(record, given, method) {
10319
10708
  recordState.commitColumns(names);
10320
10709
  return result?.rowsAffected === 1;
10321
10710
  }
10322
- /** A write straight to the row needs one: a new record has none, and a destroyed one is read-only. */
10323
- function requireSaved(record, method) {
10711
+ /**
10712
+ * A write straight to the row needs one: a new record has none, a destroyed one is a snapshot, and
10713
+ * a read-only one refuses it (#358).
10714
+ */
10715
+ function requireWritableRow(record, method) {
10324
10716
  const recordState = record[state];
10325
10717
  recordState.requireLive("be written");
10718
+ requireWritable(record, method);
10326
10719
  if (recordState.isNew) throw new RecordNotSaved(`${modelOf$1(record).name} record hasn't been saved, so ${method} has no row to write`);
10327
10720
  }
10328
10721
  const modelOf$1 = (record) => record.constructor;
@@ -10331,13 +10724,29 @@ function numberValue(record, name, method) {
10331
10724
  requireAttributeType(modelOf$1(record), name, method, "integer", "real");
10332
10725
  return record[state].read(name);
10333
10726
  }
10727
+ // src/readonly-marks.ts
10728
+ /** The read-only mark Model's records have. */
10729
+ var ReadonlyMarks = class extends AttributeWrites {
10730
+ /**
10731
+ * Marks the record read-only: saving, destroying, touching it or writing its columns throws
10732
+ * `ReadonlyRecord`, sending nothing. It can still be changed in memory and reloaded.
10733
+ */
10734
+ markReadonly() {
10735
+ this[state].isReadonly = true;
10736
+ return this;
10737
+ }
10738
+ /** Whether it's read-only: marked by `markReadonly()`, or loaded through a `readonly()` Relation. */
10739
+ isReadonly() {
10740
+ return this[state].isReadonly;
10741
+ }
10742
+ };
10334
10743
  // src/model.ts
10335
10744
  /**
10336
10745
  * The library's base class: an app's base class extends it, and
10337
10746
  * methods, statics, callbacks and scopes declared there are shared by every Model built on it.
10338
10747
  * It has no table, so it's never used as a Model itself.
10339
10748
  */
10340
- var Model = class extends AttributeWrites {
10749
+ var Model = class extends ReadonlyMarks {
10341
10750
  /**
10342
10751
  * An app-wide query listener, as `connect(env.DB, { onQuery })` is a database's: called for
10343
10752
  * every statement of this Model (and those extending it), whichever database runs it, after
@@ -10650,11 +11059,13 @@ var Model = class extends AttributeWrites {
10650
11059
  /** `assign` then `save`. */
10651
11060
  async update(attributes) {
10652
11061
  this[state].requireLive("be updated");
11062
+ requireWritable(this, "save");
10653
11063
  return this.assign(attributes).save();
10654
11064
  }
10655
11065
  /** `assign` then `saveOrThrow`. */
10656
11066
  async updateOrThrow(attributes) {
10657
11067
  this[state].requireLive("be updated");
11068
+ requireWritable(this, "save");
10658
11069
  return this.assign(attributes).saveOrThrow();
10659
11070
  }
10660
11071
  /**
@@ -10999,6 +11410,13 @@ function recordsOf(entry) {
10999
11410
  const { record, kind } = entry[recordStatementParts];
11000
11411
  return kind === "save" ? savingGroups(record)[0].records : [record];
11001
11412
  }
11413
+ /** Refuses an entry that would write a read-only record (#358), before any entry's callbacks run. */
11414
+ function refuseReadonly(entry) {
11415
+ if (!(entry instanceof RecordStatement)) return;
11416
+ const { record, kind } = entry[recordStatementParts];
11417
+ if (kind === "destroy") requireWritable(record, "destroy");
11418
+ else requireSavesWritable(savingGroups(record).flatMap(({ records }) => records));
11419
+ }
11002
11420
  /**
11003
11421
  * Refuses an entry whose record would also write on another database (#228), before anything
11004
11422
  * runs, since a batch writes one: a save whose autosave reaches one, or a destroy whose
@@ -11032,6 +11450,7 @@ async function runBatch(entries, needs, handles = []) {
11032
11450
  const statements = entries.filter((entry) => !(entry instanceof RecordStatement));
11033
11451
  const all = [...handles, ...statements.map(executorOf)];
11034
11452
  for (const entry of entries) refuseElsewhere(entry, needs);
11453
+ for (const entry of entries) refuseReadonly(entry);
11035
11454
  const records = entries.flatMap(recordsOf);
11036
11455
  if (all.length === 0 && records.length === 0) return [];
11037
11456
  const database = await pinBefore(linksOf(records), needs, all);
@@ -11091,4 +11510,4 @@ async function recordEntry(statement, claimed, needs) {
11091
11510
  result: () => record
11092
11511
  };
11093
11512
  }
11094
- export { lt as _, databaseExecutor as a, hasMany as b, Relation as c, column as d, sql as f, gte as g, gt as h, AnyDatabase as i, workersEnv as l, between as m, Model as n, readyModel as o, valueMark as p, withDatabase as r, isReservedScopeName as s, batch as t, DatabaseExecutor as u, lte as v, hasOne as x, belongsTo as y };
11513
+ export { belongsTo as _, databaseExecutor as a, Relation as c, valueMark as d, between as f, lte as g, lt as h, AnyDatabase as i, workersEnv as l, gte as m, Model as n, readyModel as o, gt as p, withDatabase as r, isReservedScopeName as s, batch as t, DatabaseExecutor as u, hasMany as v, hasOne as y };