@forestfuture/active-record 0.9.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter.d.mts +2 -2
- package/dist/adapter.mjs +4 -4
- package/dist/{batch-Ca1JtVcK.mjs → batch-DpMoy3-7.mjs} +830 -698
- package/dist/cli.d.mts +1 -1
- package/dist/cli.mjs +3 -3
- package/dist/command.mjs +5 -5
- package/dist/d1.d.mts +2 -2
- package/dist/d1.mjs +4 -4
- package/dist/{for-adapters-D35a5x3t.mjs → for-adapters-DSVRZL3n.mjs} +2 -2
- package/dist/{for-adapters-DoyXc8Dq.d.mts → for-adapters-GQfwyuMl.d.mts} +1 -1
- package/dist/{for-adapters-Bl6BCiR1.mjs → for-adapters-unqbZQM7.mjs} +1 -1
- package/dist/{generated-model-L4WAqgOZ.mjs → generated-model-CKIciUat.mjs} +37 -3
- package/dist/{identifiers-CzqYL_nC.mjs → identifiers-BP6aRwew.mjs} +38 -1
- package/dist/{index-Fq4gT3c8.d.mts → index-DkWlkGy2.d.mts} +26 -2
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +5 -5
- package/dist/{metadata-BIUbGJlS.d.mts → metadata-nKZ_6DzA.d.mts} +17 -2
- package/dist/{plugin-BHUP4ssD.mjs → plugin-A93qwqAh.mjs} +3 -3
- package/dist/{plugin-BMAJKgj6.mjs → plugin-CsOOLZkx.mjs} +3 -3
- package/dist/postgresql.d.mts +1 -1
- package/dist/postgresql.mjs +4 -4
- package/dist/{src-fYq-nVHE.mjs → src-CB2AUq70.mjs} +2 -2
- package/dist/{storage-override-yF2NT5ST.mjs → storage-override-B7WTiA_U.mjs} +1 -1
- package/dist/{validations-CKPJoSj4.d.mts → validations-C2-HKi1V.d.mts} +80 -60
- package/llms-full.txt +220 -11
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +1 -0
|
@@ -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-
|
|
2
|
-
import { $ as
|
|
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-CKIciUat.mjs";
|
|
2
|
+
import { $ as StaleRecord, A as AssociationNotLoaded, C as pluralize, D as underscore, F as IncompatibleRelation, G as ReadonlyRecord, H as NotNullViolation, I as InvalidForeignKey, J as RecordNotDestroyed, L as InvalidModel, M as CheckViolation, O as AbortAfterPersistence, P as DeleteRestriction, Q as SoleRecordExceeded, R as InvalidToken, T as camelize, U as ReadonlyAssociation, V as NoDatabase, W as ReadonlyAttribute, X as RecordNotSaved, Y as RecordNotFound, Z as RecordNotUnique, b as enumValuesOf, c as castValue, d as uncastable, et as StrictValidationFailed, f as writeUntypedValue, g as orderDecimal, i as hexOf, it as abort, j as CallbackAbort, k as ActiveRecordError, m as zonelessDateTime, q as RecordInvalid, rt as UnknownModelName, tt as UnknownAssociation, w as singularize, y as enumValidations, z as IrreversibleOrder } from "./identifiers-BP6aRwew.mjs";
|
|
3
3
|
// src/foreign-keys.ts
|
|
4
4
|
/**
|
|
5
5
|
* Gives each declaration its foreign key: the one passed, or else inferred from
|
|
@@ -816,13 +816,15 @@ const SHAPE_CLAUSES = [
|
|
|
816
816
|
"order",
|
|
817
817
|
"limit",
|
|
818
818
|
"offset",
|
|
819
|
-
"distinct"
|
|
819
|
+
"distinct",
|
|
820
|
+
"readonly"
|
|
820
821
|
];
|
|
821
822
|
/** Whether two descriptions agree on one shape clause, by that clause's own rule. */
|
|
822
823
|
function isSameClause(clause, a, b) {
|
|
823
824
|
switch (clause) {
|
|
824
825
|
case "select": return isSameList(a.select, b.select, (x, y) => x === y);
|
|
825
826
|
case "order": return isSameList(a.order, b.order, isSameOrderTerm);
|
|
827
|
+
case "readonly": return (a.readonly ?? false) === (b.readonly ?? false);
|
|
826
828
|
default: return Object.is(a[clause], b[clause]);
|
|
827
829
|
}
|
|
828
830
|
}
|
|
@@ -907,6 +909,7 @@ function merged(a, b) {
|
|
|
907
909
|
};
|
|
908
910
|
for (const clause of SHAPE_CLAUSES) if (isSet(b, clause)) Object.assign(result, { [clause]: b[clause] });
|
|
909
911
|
if (b.reordered) result.reordered = true;
|
|
912
|
+
if (b.readonly !== void 0) result.readonly = b.readonly;
|
|
910
913
|
return result;
|
|
911
914
|
}
|
|
912
915
|
/** What `merge()` unions of `b`'s with `a`'s: includes, joins, `createWith`, and owner links. */
|
|
@@ -1790,6 +1793,61 @@ function normalizedValue(attribute, value) {
|
|
|
1790
1793
|
function assignedValues(model, values) {
|
|
1791
1794
|
return Object.fromEntries(Object.entries(values).map(([name, value]) => [name, attributeFor(model, name).assigned(value)]));
|
|
1792
1795
|
}
|
|
1796
|
+
// src/readonly-records.ts
|
|
1797
|
+
/**
|
|
1798
|
+
* Refuses `action` on a read-only record, before its validation, callbacks or statements; and a
|
|
1799
|
+
* save of a persisted record whose read-only attribute changed without being assigned, in place.
|
|
1800
|
+
*/
|
|
1801
|
+
function requireWritable(record, action) {
|
|
1802
|
+
if (record[state].isReadonly) throw new ReadonlyRecord(record, action);
|
|
1803
|
+
if (action === "save") requireReadonlyAttributesKept(record);
|
|
1804
|
+
}
|
|
1805
|
+
/** The attributes every save writes, which can't be read-only: its timestamp and lock version. */
|
|
1806
|
+
const writtenBySaves = ["updatedAt", lockVersion];
|
|
1807
|
+
/** A read-only attribute every save writes anyway, as a message, or undefined. */
|
|
1808
|
+
function readonlyProblem(where, name, readonly) {
|
|
1809
|
+
if (readonly !== true || !writtenBySaves.includes(name)) return void 0;
|
|
1810
|
+
return `${where} is written by every save, so it can't be readonly`;
|
|
1811
|
+
}
|
|
1812
|
+
/** Refuses a write straight to a row that sets a read-only attribute, `names`, before it's sent. */
|
|
1813
|
+
function requireWritableColumns(model, names) {
|
|
1814
|
+
for (const given of names) {
|
|
1815
|
+
const name = attributeName(model, given);
|
|
1816
|
+
if (model.attributeDefinitions.get(name)?.readonly === true) throw new ReadonlyAttribute(model.name, name);
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
/** A persisted record's read-only attributes, as it was loaded or created, or `ReadonlyAttribute`. */
|
|
1820
|
+
function requireReadonlyAttributesKept(record) {
|
|
1821
|
+
const recordState = record[state];
|
|
1822
|
+
if (!recordState.isPersisted) return;
|
|
1823
|
+
requireWritableColumns(record.constructor, recordState.changedNames());
|
|
1824
|
+
}
|
|
1825
|
+
/**
|
|
1826
|
+
* Refuses a save that would write a read-only record through its owner's associations: saving or
|
|
1827
|
+
* destroying one marked for destruction. Checked before the owner's validation and callbacks.
|
|
1828
|
+
*/
|
|
1829
|
+
function requireSavesWritable(records) {
|
|
1830
|
+
for (const record of records) {
|
|
1831
|
+
requireWritable(record, record[state].isMarkedForDestruction ? "destroy" : "save");
|
|
1832
|
+
requireLinksWritable(record);
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
/**
|
|
1836
|
+
* The read-only foreign keys a save would fill once a new record is inserted, refused before:
|
|
1837
|
+
* a persisted record's, pointed at a new one, and a persisted record's its new owner would fill.
|
|
1838
|
+
*/
|
|
1839
|
+
function requireLinksWritable(record) {
|
|
1840
|
+
const model = record.constructor;
|
|
1841
|
+
if (record[state].isPersisted) for (const [name, target] of record[state].autosaves.allBelongsTo()) {
|
|
1842
|
+
if (!target[state].isNew) continue;
|
|
1843
|
+
requireWritableColumns(model, [resolveAssociation(model, name).ownerAttribute]);
|
|
1844
|
+
}
|
|
1845
|
+
if (!record[state].isNew) return;
|
|
1846
|
+
for (const { association, record: linked, keepsKey, destroys } of autosavedAfter(record, /* @__PURE__ */ new Set())) {
|
|
1847
|
+
if (keepsKey || destroys || !linked[state].isPersisted) continue;
|
|
1848
|
+
requireWritableColumns(modelOf(linked), [association.definition.foreignKey]);
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1793
1851
|
// src/constraints.ts
|
|
1794
1852
|
/** Each kind's class, and a readable label, since bundlers may rename the error classes. */
|
|
1795
1853
|
const VIOLATIONS = {
|
|
@@ -2333,8 +2391,7 @@ function addToCount(record, attribute, by) {
|
|
|
2333
2391
|
const recordState = record[state];
|
|
2334
2392
|
if (recordState.isDestroyed || !(attribute in recordState.attributes())) return;
|
|
2335
2393
|
const count = recordState.read(attribute);
|
|
2336
|
-
recordState.
|
|
2337
|
-
recordState.commitColumns([attribute]);
|
|
2394
|
+
recordState.takeStored(attribute, (typeof count === "number" ? count : 0) + by);
|
|
2338
2395
|
}
|
|
2339
2396
|
/**
|
|
2340
2397
|
* `counter`'s change by `by` on the target the record's row points at, found by the row's key
|
|
@@ -2560,9 +2617,10 @@ function insertStatement(executor, model, rows, { conflict, method, landed, retu
|
|
|
2560
2617
|
throw new TypeError(`${method}(): nothing to insert; give each row at least one attribute`);
|
|
2561
2618
|
}
|
|
2562
2619
|
const values = assigned.map((row) => names.map((name) => row.get(name)));
|
|
2620
|
+
const updated = given.filter((name) => model.attributeDefinitions.get(name)?.readonly !== true);
|
|
2563
2621
|
const resolved = conflict?.kind === "update" ? {
|
|
2564
2622
|
...conflict,
|
|
2565
|
-
update: [...
|
|
2623
|
+
update: [...updated, ...names.includes("updatedAt") ? ["updatedAt"] : []]
|
|
2566
2624
|
} : conflict;
|
|
2567
2625
|
return new Statement(executor, compileInsertRows(executor.dialect, model, {
|
|
2568
2626
|
names,
|
|
@@ -3178,6 +3236,7 @@ function whoseIs(association, linked, otherType) {
|
|
|
3178
3236
|
*/
|
|
3179
3237
|
async function pinForSaving(records, needs) {
|
|
3180
3238
|
const groups = records.map((record) => savingGroups(record));
|
|
3239
|
+
requireSavesWritable(groups.flat().flatMap((group) => group.records));
|
|
3181
3240
|
await pinBefore(linksOf(groups.flatMap(([own]) => own?.records ?? [])), needs);
|
|
3182
3241
|
for (const [, ...elsewhere] of groups) for (const group of elsewhere) await pinBefore(linksOf(group.records), needs);
|
|
3183
3242
|
}
|
|
@@ -3548,6 +3607,7 @@ async function loadWith(executor, model, load) {
|
|
|
3548
3607
|
const results = await sendTogether(executor, [...own, ...plan?.statements ?? []]);
|
|
3549
3608
|
const database = await databaseNow(executor);
|
|
3550
3609
|
const records = (load.rowsOf(results) ?? []).map((row) => hydrate(model, row, database));
|
|
3610
|
+
if (query.readonly === true) for (const record of records) record[state].isReadonly = true;
|
|
3551
3611
|
await plan?.attach([records], results.slice(own.length), database);
|
|
3552
3612
|
return {
|
|
3553
3613
|
records,
|
|
@@ -3807,11 +3867,7 @@ function planBranch(planning, start, level, { name, association }) {
|
|
|
3807
3867
|
leaveForAfterwards(planning, deferred);
|
|
3808
3868
|
return;
|
|
3809
3869
|
}
|
|
3810
|
-
const step =
|
|
3811
|
-
association,
|
|
3812
|
-
ownersAt,
|
|
3813
|
-
select: targets?.select
|
|
3814
|
-
};
|
|
3870
|
+
const step = stepFor(association, ownersAt, targets);
|
|
3815
3871
|
const position = planning.offset + planning.steps.push(step) - 1;
|
|
3816
3872
|
if (query === void 0 || targets === void 0) return;
|
|
3817
3873
|
const { target } = association;
|
|
@@ -4004,8 +4060,9 @@ async function attachSteps({ steps, gathers, afterwards }, records, rows, execut
|
|
|
4004
4060
|
function recordsAtEachPosition(steps, records, rows, executor) {
|
|
4005
4061
|
const owners = [...records];
|
|
4006
4062
|
const results = rows.values();
|
|
4007
|
-
for (const { association, ownersAt, select, isHop } of steps) {
|
|
4063
|
+
for (const { association, ownersAt, select, isHop, readonly } of steps) {
|
|
4008
4064
|
const targets = (select === void 0 ? [] : results.next().value ?? []).map((row) => hydrate(association.target, row, executor));
|
|
4065
|
+
if (readonly === true) for (const target of targets) target[state].isReadonly = true;
|
|
4009
4066
|
if (isHop === void 0) attach(owners[ownersAt] ?? [], association, targets);
|
|
4010
4067
|
owners.push(targets);
|
|
4011
4068
|
}
|
|
@@ -4022,7 +4079,24 @@ async function preloadStarts(starts, executor) {
|
|
|
4022
4079
|
const records = starts.map(({ owners }) => "records" in owners ? owners.records : []);
|
|
4023
4080
|
await plan.attach(records, rows, database);
|
|
4024
4081
|
}
|
|
4025
|
-
/**
|
|
4082
|
+
/** A step loading an association's targets, if they can match. */
|
|
4083
|
+
function stepFor(association, ownersAt, targets) {
|
|
4084
|
+
if (targets === void 0) return {
|
|
4085
|
+
association,
|
|
4086
|
+
ownersAt,
|
|
4087
|
+
select: void 0
|
|
4088
|
+
};
|
|
4089
|
+
return {
|
|
4090
|
+
association,
|
|
4091
|
+
ownersAt,
|
|
4092
|
+
select: targets.select,
|
|
4093
|
+
readonly: targets.readonly
|
|
4094
|
+
};
|
|
4095
|
+
}
|
|
4096
|
+
/**
|
|
4097
|
+
* The SELECT for an association's targets, `query`, what to preload for them, and whether its
|
|
4098
|
+
* scope makes them read-only (#358).
|
|
4099
|
+
*/
|
|
4026
4100
|
function targetsOf(dialect, association, query, { nested, needed = [] }) {
|
|
4027
4101
|
const includes = mergeTrees(query.includes ?? {}, nested);
|
|
4028
4102
|
const columns = query.select && [
|
|
@@ -4036,7 +4110,8 @@ function targetsOf(dialect, association, query, { nested, needed = [] }) {
|
|
|
4036
4110
|
select: columns,
|
|
4037
4111
|
includes
|
|
4038
4112
|
}),
|
|
4039
|
-
includes
|
|
4113
|
+
includes,
|
|
4114
|
+
readonly: query.readonly
|
|
4040
4115
|
};
|
|
4041
4116
|
}
|
|
4042
4117
|
/**
|
|
@@ -4271,18 +4346,19 @@ function inspectRelation(modelName, { sql, params }, args) {
|
|
|
4271
4346
|
}
|
|
4272
4347
|
// src/find.ts
|
|
4273
4348
|
/**
|
|
4274
|
-
* The finder rules: `query`'s conditions (plus `extra`), joins and
|
|
4275
|
-
* order.
|
|
4349
|
+
* The finder rules: `query`'s conditions (plus `extra`), joins, includes and read-only mark (#358),
|
|
4350
|
+
* full rows, no order.
|
|
4276
4351
|
*/
|
|
4277
4352
|
function finderQuery(query, extra) {
|
|
4278
4353
|
const conditions = extra === void 0 ? query.conditions : [...query.conditions, extra];
|
|
4279
|
-
const { model, joins, includes } = query;
|
|
4354
|
+
const { model, joins, includes, readonly } = query;
|
|
4280
4355
|
return {
|
|
4281
4356
|
model,
|
|
4282
4357
|
conditions,
|
|
4283
4358
|
order: [],
|
|
4284
4359
|
includes,
|
|
4285
|
-
...joins !== void 0 && { joins }
|
|
4360
|
+
...joins !== void 0 && { joins },
|
|
4361
|
+
...readonly !== void 0 && { readonly }
|
|
4286
4362
|
};
|
|
4287
4363
|
}
|
|
4288
4364
|
/** One row `query` matches by the finder rules (plus `extra`), or null. */
|
|
@@ -4598,755 +4674,784 @@ async function upToTwo(source) {
|
|
|
4598
4674
|
}
|
|
4599
4675
|
}) + source.unsavedCount();
|
|
4600
4676
|
}
|
|
4601
|
-
// src/
|
|
4602
|
-
/**
|
|
4603
|
-
const
|
|
4604
|
-
|
|
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
|
-
}
|
|
4677
|
+
// src/message-signing.ts
|
|
4678
|
+
/** The bytes of a fingerprint kept in a token: enough that guessing one is hopeless. */
|
|
4679
|
+
const FINGERPRINT_BYTES = 12;
|
|
4680
|
+
const SIGNATURE_BYTES = 32;
|
|
4665
4681
|
/**
|
|
4666
|
-
*
|
|
4667
|
-
*
|
|
4668
|
-
*
|
|
4682
|
+
* The longest token: room for an id of about 700 characters, its expiry and a fingerprint, far
|
|
4683
|
+
* more than a key's id needs; signing a longer one throws. A longer token is
|
|
4684
|
+
* refused before its signature is checked, so a huge one costs nothing.
|
|
4669
4685
|
*/
|
|
4670
|
-
|
|
4671
|
-
|
|
4672
|
-
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
|
|
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];
|
|
4686
|
+
const MAX_TOKEN_LENGTH = 1024;
|
|
4687
|
+
/** base64url without padding. */
|
|
4688
|
+
const BASE64URL = /^[\w-]+$/;
|
|
4689
|
+
/** A signer for `feature`'s tokens: the first secret signs, and each one verifies. */
|
|
4690
|
+
function signerFor(secrets, feature) {
|
|
4691
|
+
const keys = secrets.map((secret) => keysFor(secret, feature));
|
|
4683
4692
|
return {
|
|
4684
|
-
|
|
4685
|
-
|
|
4686
|
-
|
|
4693
|
+
async sign(purpose, message) {
|
|
4694
|
+
const { id, expiresAt, dependsOn } = message;
|
|
4695
|
+
const key = await keys[0];
|
|
4696
|
+
const fingerprint = Object.hasOwn(message, "dependsOn") ? await fingerprintOf(key, purpose, id, dependsOn) : null;
|
|
4697
|
+
const expiry = expiresAt === void 0 ? null : secondsSinceEpoch(expiresAt);
|
|
4698
|
+
const payload = encode(new TextEncoder().encode(JSON.stringify(trimmed([
|
|
4699
|
+
id,
|
|
4700
|
+
expiry,
|
|
4701
|
+
fingerprint
|
|
4702
|
+
]))));
|
|
4703
|
+
const signature = await crypto.subtle.sign("HMAC", key.signing, signedBytes(purpose, payload));
|
|
4704
|
+
const token = `${payload}.${encode(new Uint8Array(signature))}`;
|
|
4705
|
+
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`);
|
|
4706
|
+
return token;
|
|
4707
|
+
},
|
|
4708
|
+
async verify(purpose, token) {
|
|
4709
|
+
const parts = partsOf(token);
|
|
4710
|
+
if (parts === void 0) return void 0;
|
|
4711
|
+
const data = signedBytes(purpose, parts.payload);
|
|
4712
|
+
const signedWith = await keysThatSigned(keys, data, parts.signature);
|
|
4713
|
+
return signedWith === void 0 ? void 0 : messageIn(signedWith, purpose, parts.payload);
|
|
4714
|
+
}
|
|
4687
4715
|
};
|
|
4688
4716
|
}
|
|
4717
|
+
/** A token's payload and signature's bytes, or undefined when it isn't shaped as one, or spelled as `encode` doesn't. */
|
|
4718
|
+
function partsOf(token) {
|
|
4719
|
+
if (token.length > MAX_TOKEN_LENGTH) return void 0;
|
|
4720
|
+
const [payload = "", signature = "", ...rest] = token.split(".");
|
|
4721
|
+
if (rest.length > 0 || !BASE64URL.test(payload) || !BASE64URL.test(signature)) return void 0;
|
|
4722
|
+
const bytes = decode(signature);
|
|
4723
|
+
return bytes?.length === SIGNATURE_BYTES && encode(bytes) === signature ? {
|
|
4724
|
+
payload,
|
|
4725
|
+
signature: bytes
|
|
4726
|
+
} : void 0;
|
|
4727
|
+
}
|
|
4689
4728
|
/**
|
|
4690
|
-
*
|
|
4691
|
-
*
|
|
4729
|
+
* The keys whose signature `data` has, if any's. Every key is tried, so the time taken doesn't
|
|
4730
|
+
* say which signed it.
|
|
4692
4731
|
*/
|
|
4693
|
-
function
|
|
4694
|
-
|
|
4695
|
-
|
|
4696
|
-
|
|
4697
|
-
|
|
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)];
|
|
4732
|
+
async function keysThatSigned(keys, data, signature) {
|
|
4733
|
+
let signer;
|
|
4734
|
+
for (const each of keys) {
|
|
4735
|
+
const key = await each;
|
|
4736
|
+
if (await crypto.subtle.verify("HMAC", key.signing, signature, data)) signer ??= key;
|
|
4715
4737
|
}
|
|
4716
|
-
|
|
4717
|
-
|
|
4738
|
+
return signer;
|
|
4739
|
+
}
|
|
4740
|
+
/** A token's expiry, in whole Unix seconds; `TypeError` for one that isn't a time. */
|
|
4741
|
+
function secondsSinceEpoch(expiresAt) {
|
|
4742
|
+
const seconds = Math.floor(Number(expiresAt.getTime()) / 1e3);
|
|
4743
|
+
if (!Number.isSafeInteger(seconds)) throw new TypeError("A token's expiry must be a valid Date");
|
|
4744
|
+
return seconds;
|
|
4718
4745
|
}
|
|
4719
4746
|
/**
|
|
4720
|
-
*
|
|
4721
|
-
*
|
|
4747
|
+
* Each secret's keys, by feature. Module-level, but not request state (ADR-0003): derived only
|
|
4748
|
+
* from the secret, which every request shares.
|
|
4722
4749
|
*/
|
|
4723
|
-
|
|
4724
|
-
|
|
4725
|
-
|
|
4726
|
-
|
|
4727
|
-
if (
|
|
4728
|
-
|
|
4729
|
-
|
|
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);
|
|
4750
|
+
const derived = /* @__PURE__ */ new Map();
|
|
4751
|
+
function keysFor(secret, feature) {
|
|
4752
|
+
const cacheKey = `${feature}\n${secret}`;
|
|
4753
|
+
let keys = derived.get(cacheKey);
|
|
4754
|
+
if (keys === void 0) {
|
|
4755
|
+
keys = deriveKeys(secret, feature);
|
|
4756
|
+
derived.set(cacheKey, keys);
|
|
4736
4757
|
}
|
|
4737
|
-
return
|
|
4758
|
+
return keys;
|
|
4738
4759
|
}
|
|
4739
|
-
|
|
4740
|
-
|
|
4741
|
-
const
|
|
4760
|
+
async function deriveKeys(secret, feature) {
|
|
4761
|
+
const material = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), "HKDF", false, ["deriveKey"]);
|
|
4762
|
+
const derive = (use) => crypto.subtle.deriveKey({
|
|
4763
|
+
name: "HKDF",
|
|
4764
|
+
hash: "SHA-256",
|
|
4765
|
+
salt: new TextEncoder().encode("@forestfuture/active-record"),
|
|
4766
|
+
info: new TextEncoder().encode(`${feature} ${use}`)
|
|
4767
|
+
}, material, {
|
|
4768
|
+
name: "HMAC",
|
|
4769
|
+
hash: "SHA-256",
|
|
4770
|
+
length: 256
|
|
4771
|
+
}, false, ["sign", "verify"]);
|
|
4772
|
+
const [signing, fingerprinting] = await Promise.all([derive("signing"), derive("fingerprint")]);
|
|
4742
4773
|
return {
|
|
4743
|
-
|
|
4744
|
-
|
|
4774
|
+
signing,
|
|
4775
|
+
fingerprinting
|
|
4745
4776
|
};
|
|
4746
4777
|
}
|
|
4747
|
-
/** What
|
|
4748
|
-
function
|
|
4749
|
-
|
|
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);
|
|
4778
|
+
/** What a token's signature covers: its purpose, quoted so no purpose runs into its payload. */
|
|
4779
|
+
function signedBytes(purpose, payload) {
|
|
4780
|
+
return new TextEncoder().encode(`${JSON.stringify(purpose)}.${payload}`);
|
|
4761
4781
|
}
|
|
4762
4782
|
/**
|
|
4763
|
-
*
|
|
4764
|
-
*
|
|
4783
|
+
* A value's fingerprint for one record's token for one purpose: their JSON, signed with the
|
|
4784
|
+
* fingerprint key, cut short. Each record and purpose fingerprints a value apart, so equal
|
|
4785
|
+
* fingerprints never say two records share it.
|
|
4765
4786
|
*/
|
|
4766
|
-
function
|
|
4767
|
-
|
|
4768
|
-
|
|
4787
|
+
async function fingerprintOf(keys, purpose, id, value) {
|
|
4788
|
+
const json = new TextEncoder().encode(JSON.stringify([
|
|
4789
|
+
purpose,
|
|
4790
|
+
id,
|
|
4791
|
+
value ?? null
|
|
4792
|
+
]));
|
|
4793
|
+
const signature = await crypto.subtle.sign("HMAC", keys.fingerprinting, json);
|
|
4794
|
+
return encode(new Uint8Array(signature).slice(0, FINGERPRINT_BYTES));
|
|
4769
4795
|
}
|
|
4770
|
-
/**
|
|
4771
|
-
|
|
4772
|
-
|
|
4773
|
-
|
|
4774
|
-
|
|
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
|
-
};
|
|
4796
|
+
/** A payload without the nulls at its end. */
|
|
4797
|
+
function trimmed(values) {
|
|
4798
|
+
let end = values.length;
|
|
4799
|
+
while (end > 1 && values[end - 1] === null) end -= 1;
|
|
4800
|
+
return values.slice(0, end);
|
|
4785
4801
|
}
|
|
4786
|
-
/**
|
|
4787
|
-
function
|
|
4788
|
-
|
|
4789
|
-
if (
|
|
4790
|
-
|
|
4802
|
+
/** Whether a payload's expiry has passed, or isn't a whole number of Unix seconds; never without one. */
|
|
4803
|
+
function hasExpired(expiry) {
|
|
4804
|
+
if (expiry === null) return false;
|
|
4805
|
+
if (typeof expiry !== "number" || !Number.isSafeInteger(expiry)) return true;
|
|
4806
|
+
return expiry * 1e3 <= Date.now();
|
|
4807
|
+
}
|
|
4808
|
+
/** The message in a signed payload, unless it's expired or isn't one this module made. */
|
|
4809
|
+
function messageIn(keys, purpose, payload) {
|
|
4810
|
+
const [id, expiry = null, fingerprint = null] = parsedPayload(payload) ?? [];
|
|
4811
|
+
if (!(typeof id === "string" || typeof id === "number" && Number.isSafeInteger(id)) || hasExpired(expiry)) return void 0;
|
|
4791
4812
|
return {
|
|
4792
|
-
|
|
4793
|
-
|
|
4813
|
+
id,
|
|
4814
|
+
async isUnchanged(value) {
|
|
4815
|
+
if (typeof fingerprint !== "string") return false;
|
|
4816
|
+
return fingerprint === await fingerprintOf(keys, purpose, id, value);
|
|
4817
|
+
}
|
|
4794
4818
|
};
|
|
4795
4819
|
}
|
|
4796
|
-
/**
|
|
4797
|
-
|
|
4798
|
-
|
|
4799
|
-
|
|
4800
|
-
|
|
4801
|
-
|
|
4802
|
-
|
|
4803
|
-
|
|
4804
|
-
|
|
4805
|
-
|
|
4806
|
-
}
|
|
4807
|
-
|
|
4808
|
-
|
|
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;
|
|
4820
|
+
/** A payload's values, or undefined when it isn't a JSON array. */
|
|
4821
|
+
function parsedPayload(payload) {
|
|
4822
|
+
const bytes = decode(payload);
|
|
4823
|
+
if (bytes === void 0) return void 0;
|
|
4824
|
+
try {
|
|
4825
|
+
const values = JSON.parse(new TextDecoder("utf-8", {
|
|
4826
|
+
fatal: true,
|
|
4827
|
+
ignoreBOM: false
|
|
4828
|
+
}).decode(bytes));
|
|
4829
|
+
return Array.isArray(values) ? values : void 0;
|
|
4830
|
+
} catch {
|
|
4831
|
+
return;
|
|
4832
|
+
}
|
|
4824
4833
|
}
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
4834
|
+
function encode(bytes) {
|
|
4835
|
+
let binary = "";
|
|
4836
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
4837
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
|
|
4828
4838
|
}
|
|
4829
|
-
/**
|
|
4830
|
-
|
|
4831
|
-
|
|
4832
|
-
|
|
4833
|
-
|
|
4834
|
-
|
|
4835
|
-
|
|
4839
|
+
/** base64url's bytes, or undefined for text that isn't base64url. */
|
|
4840
|
+
function decode(text) {
|
|
4841
|
+
try {
|
|
4842
|
+
const binary = atob(text.replaceAll("-", "+").replaceAll("_", "/"));
|
|
4843
|
+
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
4844
|
+
} catch {
|
|
4845
|
+
return;
|
|
4846
|
+
}
|
|
4836
4847
|
}
|
|
4837
|
-
|
|
4838
|
-
|
|
4839
|
-
|
|
4840
|
-
|
|
4841
|
-
return
|
|
4848
|
+
// src/workers-env.ts
|
|
4849
|
+
/** Whether importing `cloudflare:workers` failed because this isn't a Worker (Node, scripts). */
|
|
4850
|
+
function isOutsideWorker(error) {
|
|
4851
|
+
const { code, message } = error;
|
|
4852
|
+
return code === "ERR_UNSUPPORTED_ESM_URL_SCHEME" || code === "ERR_MODULE_NOT_FOUND" || /cloudflare:workers/.test(String(message));
|
|
4842
4853
|
}
|
|
4843
4854
|
/**
|
|
4844
|
-
*
|
|
4845
|
-
*
|
|
4846
|
-
*
|
|
4855
|
+
* The Worker's `env`, from `load`, or undefined outside a Worker (Node, scripts). An adapter
|
|
4856
|
+
* passes `() => import("cloudflare:workers")` from its own module, with that literal specifier:
|
|
4857
|
+
* Wrangler only bundles those, and a test that mocks the module with the adapter inlined reaches it.
|
|
4847
4858
|
*/
|
|
4848
|
-
async function
|
|
4849
|
-
const record = await recordToCreate(relation, attributes, options.init);
|
|
4850
|
-
const isSavedAlone = record[state].autosaves.isEmpty();
|
|
4859
|
+
async function workersEnv(load) {
|
|
4851
4860
|
try {
|
|
4852
|
-
await
|
|
4853
|
-
return record;
|
|
4861
|
+
return (await load()).env;
|
|
4854
4862
|
} catch (error) {
|
|
4855
|
-
if (
|
|
4856
|
-
|
|
4863
|
+
if (isOutsideWorker(error)) return void 0;
|
|
4864
|
+
throw error;
|
|
4857
4865
|
}
|
|
4858
4866
|
}
|
|
4859
|
-
|
|
4860
|
-
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
|
|
4867
|
-
|
|
4868
|
-
|
|
4869
|
-
|
|
4870
|
-
return
|
|
4867
|
+
// src/signing-secret.ts
|
|
4868
|
+
/** The fewest bytes a secret has: HMAC-SHA256's own key length. */
|
|
4869
|
+
const MINIMUM_BYTES = 32;
|
|
4870
|
+
/**
|
|
4871
|
+
* The Worker's env, read once. Module-level, but not request state (ADR-0003): it's the
|
|
4872
|
+
* Worker's, the same for every request.
|
|
4873
|
+
*/
|
|
4874
|
+
let workerEnv;
|
|
4875
|
+
/** The env secrets are read from: the Worker's, or else the process's (tests, scripts). */
|
|
4876
|
+
async function envForSecrets() {
|
|
4877
|
+
workerEnv ??= workersEnv(() => import("cloudflare:workers"));
|
|
4878
|
+
return await workerEnv ?? processEnv() ?? {};
|
|
4871
4879
|
}
|
|
4872
|
-
|
|
4873
|
-
|
|
4874
|
-
|
|
4880
|
+
/** `process.env`, where there's one: Node, and Workers with Node.js compatibility. */
|
|
4881
|
+
function processEnv() {
|
|
4882
|
+
return globalThis.process?.env;
|
|
4875
4883
|
}
|
|
4876
|
-
/**
|
|
4877
|
-
function
|
|
4878
|
-
return
|
|
4884
|
+
/** A signer for `model`'s `feature` tokens; `InvalidModel` when its secrets are unset or short. */
|
|
4885
|
+
async function signerOf(model, feature) {
|
|
4886
|
+
return signerFor(secretsOf(model, await envForSecrets()), feature);
|
|
4879
4887
|
}
|
|
4880
|
-
function
|
|
4881
|
-
const
|
|
4882
|
-
|
|
4888
|
+
function secretsOf(model, env) {
|
|
4889
|
+
const given = model.signingSecret(env);
|
|
4890
|
+
const secrets = (Array.isArray(given) ? given : [given]).filter((secret) => secret !== void 0 && secret !== null);
|
|
4891
|
+
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`);
|
|
4892
|
+
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`);
|
|
4893
|
+
return secrets;
|
|
4883
4894
|
}
|
|
4884
|
-
// src/
|
|
4885
|
-
/**
|
|
4886
|
-
|
|
4887
|
-
const
|
|
4888
|
-
if (
|
|
4889
|
-
return
|
|
4895
|
+
// src/token-records.ts
|
|
4896
|
+
/** A saved record's primary key, which a token holds; `RecordNotSaved` for a new record. */
|
|
4897
|
+
function signableIdOf(record, method) {
|
|
4898
|
+
const model = record.constructor;
|
|
4899
|
+
if (record[state].isNew) throw new RecordNotSaved(`${model.name} record hasn't been saved, so ${method} has no id to sign`);
|
|
4900
|
+
return record[state].read(model.primaryKey);
|
|
4890
4901
|
}
|
|
4891
|
-
/**
|
|
4892
|
-
|
|
4893
|
-
return
|
|
4902
|
+
/** What a Model's token is signed for: its table, then what else the token is for. */
|
|
4903
|
+
function signedPurposeOf(model, ...parts) {
|
|
4904
|
+
return JSON.stringify([model.table, ...parts]);
|
|
4894
4905
|
}
|
|
4895
4906
|
/**
|
|
4896
|
-
*
|
|
4897
|
-
*
|
|
4907
|
+
* Looks up the record a token finds through `finder`, if `signer` signed it for `purpose` and it
|
|
4908
|
+
* hasn't expired, and `isStillFor` (when given) says the record is still the one it was for. A
|
|
4909
|
+
* value that isn't a string isn't a valid token.
|
|
4898
4910
|
*/
|
|
4899
|
-
async function
|
|
4900
|
-
const
|
|
4901
|
-
|
|
4902
|
-
|
|
4903
|
-
|
|
4904
|
-
|
|
4905
|
-
});
|
|
4906
|
-
|
|
4907
|
-
|
|
4908
|
-
|
|
4909
|
-
|
|
4910
|
-
return finder.findBy(conditions);
|
|
4911
|
+
async function lookUpToken(finder, { signer, purpose }, token, isStillFor) {
|
|
4912
|
+
const verified = typeof token === "string" ? await signer.verify(purpose, token) : void 0;
|
|
4913
|
+
if (verified === void 0) return {
|
|
4914
|
+
isValid: false,
|
|
4915
|
+
record: null
|
|
4916
|
+
};
|
|
4917
|
+
const record = await finder.findBy(asStored({ [finder.model.primaryKey]: verified.id }));
|
|
4918
|
+
return {
|
|
4919
|
+
isValid: true,
|
|
4920
|
+
record: record !== null && (isStillFor === void 0 || await isStillFor(record, verified)) ? record : null
|
|
4921
|
+
};
|
|
4911
4922
|
}
|
|
4912
4923
|
/**
|
|
4913
|
-
*
|
|
4914
|
-
*
|
|
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.
|
|
4924
|
+
* The record a lookup found; `InvalidToken` (naming `what`) for a token that isn't valid, and
|
|
4925
|
+
* `RecordNotFound` when a valid one found none.
|
|
4917
4926
|
*/
|
|
4918
|
-
function
|
|
4919
|
-
|
|
4920
|
-
|
|
4921
|
-
|
|
4922
|
-
|
|
4923
|
-
|
|
4924
|
-
|
|
4925
|
-
|
|
4926
|
-
|
|
4927
|
+
function foundByTokenOrThrow(model, { isValid, record }, what) {
|
|
4928
|
+
if (!isValid) throw new InvalidToken(`The ${what} isn't valid: it's changed, expired, or for another purpose`);
|
|
4929
|
+
return foundOrThrow(model, record);
|
|
4930
|
+
}
|
|
4931
|
+
// src/signed-ids.ts
|
|
4932
|
+
/** What a signed id is signed for: its Model's table, and its purpose. */
|
|
4933
|
+
function signedIdPurpose(model, purpose) {
|
|
4934
|
+
return signedPurposeOf(model, purpose ?? null);
|
|
4935
|
+
}
|
|
4936
|
+
/** When a token expires: `expiresAt`, or `expiresIn` from now; `TypeError` for both. */
|
|
4937
|
+
function expiryOf({ expiresIn, expiresAt }, where) {
|
|
4938
|
+
if (expiresIn !== void 0 && expiresAt !== void 0) throw new TypeError(`${where} takes expiresIn or expiresAt, not both`);
|
|
4939
|
+
if (expiresIn !== void 0) return expiryAfter(expiresIn, `${where}'s expiresIn`);
|
|
4940
|
+
if (expiresAt !== void 0 && !(expiresAt instanceof Date && Number.isFinite(expiresAt.getTime()))) throw new TypeError(`${where}'s expiresAt must be a valid Date`);
|
|
4941
|
+
return expiresAt;
|
|
4942
|
+
}
|
|
4943
|
+
/** A record's signed id, made with its Model's newest secret. */
|
|
4944
|
+
async function signedIdOf(record, options = {}) {
|
|
4945
|
+
const model = record.constructor;
|
|
4946
|
+
const id = signableIdOf(record, "signedId");
|
|
4947
|
+
const expiresAt = expiryOf(options, "signedId");
|
|
4948
|
+
return (await signerOf(model, "signed id")).sign(signedIdPurpose(model, options.purpose), {
|
|
4949
|
+
id,
|
|
4950
|
+
...expiresAt && { expiresAt }
|
|
4951
|
+
});
|
|
4952
|
+
}
|
|
4953
|
+
/** Looks up the record a signed id finds through `finder`, if its Model's secret signed it for `purpose`. */
|
|
4954
|
+
async function findSigned(finder, signedId, { purpose } = {}) {
|
|
4955
|
+
return lookUpToken(finder, {
|
|
4956
|
+
signer: await signerOf(finder.model, "signed id"),
|
|
4957
|
+
purpose: signedIdPurpose(finder.model, purpose)
|
|
4958
|
+
}, signedId);
|
|
4959
|
+
}
|
|
4960
|
+
// src/tokens-for.ts
|
|
4961
|
+
const OPTION_NAMES = /* @__PURE__ */ new Set(["expiresIn", "dependsOn"]);
|
|
4962
|
+
/** Declares a purpose's tokens on `model`; `InvalidModel` for a declaration that isn't one. */
|
|
4963
|
+
function declareTokenFor(model, purpose, options = {}) {
|
|
4964
|
+
const where = `${model.name}.generatesTokenFor`;
|
|
4965
|
+
if (typeof purpose !== "string" || purpose === "") throw new InvalidModel(`${where} takes a purpose, such as "emailConfirmation"`);
|
|
4966
|
+
const unknown = Object.keys(options).filter((name) => !OPTION_NAMES.has(name));
|
|
4967
|
+
if (unknown.length > 0) throw new InvalidModel(`${where}("${purpose}") takes expiresIn and dependsOn, not ${unknown.join(", ")}`);
|
|
4968
|
+
if (options.dependsOn !== void 0 && typeof options.dependsOn !== "function") throw new InvalidModel(`${where}("${purpose}")'s dependsOn is a function of the record`);
|
|
4969
|
+
if (options.expiresIn !== void 0) secondsOf(options.expiresIn, `${where}("${purpose}")'s expiresIn`);
|
|
4970
|
+
declare(model, "tokenDefinitions", {
|
|
4971
|
+
purpose,
|
|
4972
|
+
...options
|
|
4973
|
+
});
|
|
4927
4974
|
}
|
|
4928
4975
|
/**
|
|
4929
|
-
*
|
|
4930
|
-
*
|
|
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.
|
|
4976
|
+
* The declaration of `purpose` on `model`, the last when it's declared again, after its secure
|
|
4977
|
+
* passwords' reset tokens; `TypeError` when there's none.
|
|
4935
4978
|
*/
|
|
4936
|
-
function
|
|
4937
|
-
const
|
|
4938
|
-
|
|
4939
|
-
|
|
4940
|
-
const
|
|
4941
|
-
|
|
4942
|
-
|
|
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;
|
|
4979
|
+
function definitionOf(model, purpose) {
|
|
4980
|
+
const resets = resetTokenDefinitions(model.attributeDefinitions);
|
|
4981
|
+
const declarations = declared(model, "tokenDefinitions");
|
|
4982
|
+
rejectResetPurposes(model, resets, declarations);
|
|
4983
|
+
const found = [...resets, ...declarations].findLast((definition) => definition.purpose === purpose);
|
|
4984
|
+
if (found === void 0) throw new TypeError(`${model.name} has no tokens for "${purpose}"; declare them with this.generatesTokenFor("${purpose}") in its static {} block`);
|
|
4985
|
+
return found;
|
|
4947
4986
|
}
|
|
4948
4987
|
/**
|
|
4949
|
-
*
|
|
4950
|
-
*
|
|
4951
|
-
* type's whose values are arrays.
|
|
4988
|
+
* A declared purpose a reset token already uses is an `InvalidModel`: it would replace the reset
|
|
4989
|
+
* token, which stops working once the password changes, with one that doesn't.
|
|
4952
4990
|
*/
|
|
4953
|
-
function
|
|
4954
|
-
|
|
4955
|
-
if (
|
|
4956
|
-
|
|
4991
|
+
function rejectResetPurposes(model, resets, declarations) {
|
|
4992
|
+
const clash = resets.find(({ purpose }) => declarations.some((each) => each.purpose === purpose));
|
|
4993
|
+
if (clash === void 0) return;
|
|
4994
|
+
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
4995
|
}
|
|
4958
|
-
/**
|
|
4959
|
-
function
|
|
4960
|
-
return
|
|
4996
|
+
/** What a purpose's tokens are signed for: the Model's table, the purpose, and how long they last. */
|
|
4997
|
+
function tokenForPurpose(model, { purpose, expiresIn }) {
|
|
4998
|
+
return signedPurposeOf(model, purpose, expiresIn === void 0 ? null : secondsOf(expiresIn, "expiresIn"));
|
|
4999
|
+
}
|
|
5000
|
+
/** A token for `purpose`, for a saved record; `RecordNotSaved` for a new one. */
|
|
5001
|
+
async function tokenFor(record, purpose) {
|
|
5002
|
+
const model = record.constructor;
|
|
5003
|
+
const definition = definitionOf(model, purpose);
|
|
5004
|
+
const id = signableIdOf(record, "generateTokenFor");
|
|
5005
|
+
const { expiresIn, dependsOn } = definition;
|
|
5006
|
+
return (await signerOf(model, "token for")).sign(tokenForPurpose(model, definition), {
|
|
5007
|
+
id,
|
|
5008
|
+
...expiresIn !== void 0 && { expiresAt: expiryAfter(expiresIn, "expiresIn") },
|
|
5009
|
+
...dependsOn !== void 0 && { dependsOn: await dependsOn(record) }
|
|
5010
|
+
});
|
|
4961
5011
|
}
|
|
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
5012
|
/**
|
|
4967
|
-
*
|
|
4968
|
-
*
|
|
4969
|
-
* refused before its signature is checked, so a huge one costs nothing.
|
|
5013
|
+
* Looks up the record a token for `purpose` finds through `finder`, while it hasn't expired and
|
|
5014
|
+
* what it depends on is unchanged.
|
|
4970
5015
|
*/
|
|
4971
|
-
|
|
4972
|
-
|
|
4973
|
-
const
|
|
4974
|
-
|
|
4975
|
-
|
|
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
|
-
}
|
|
5016
|
+
async function findByTokenFor(finder, purpose, token) {
|
|
5017
|
+
const definition = definitionOf(finder.model, purpose);
|
|
5018
|
+
const signing = {
|
|
5019
|
+
signer: await signerOf(finder.model, "token for"),
|
|
5020
|
+
purpose: tokenForPurpose(finder.model, definition)
|
|
5000
5021
|
};
|
|
5022
|
+
const { dependsOn } = definition;
|
|
5023
|
+
if (dependsOn === void 0) return lookUpToken(finder, signing, token);
|
|
5024
|
+
return lookUpToken(finder, signing, token, async (record, verified) => verified.isUnchanged(await dependsOn(record)));
|
|
5001
5025
|
}
|
|
5002
|
-
|
|
5003
|
-
|
|
5004
|
-
|
|
5005
|
-
|
|
5006
|
-
|
|
5007
|
-
|
|
5008
|
-
|
|
5009
|
-
|
|
5010
|
-
|
|
5011
|
-
}
|
|
5026
|
+
// src/token-finders.ts
|
|
5027
|
+
/** The finders by token every Relation has. */
|
|
5028
|
+
var TokenFinders = class {
|
|
5029
|
+
/**
|
|
5030
|
+
* The record a signed id finds (`await user.signedId()`), if this Model's secret signed it for
|
|
5031
|
+
* the same `purpose` and it hasn't expired, and this Relation matches it; or null.
|
|
5032
|
+
*/
|
|
5033
|
+
async findSigned(signedId, options) {
|
|
5034
|
+
return (await findSigned(this.#finder, signedId, options)).record;
|
|
5035
|
+
}
|
|
5036
|
+
/** Like `findSigned`, but throws `InvalidToken` for a signed id that isn't valid, and `RecordNotFound` when its record is gone. */
|
|
5037
|
+
async findSignedOrThrow(signedId, options) {
|
|
5038
|
+
const lookup = await findSigned(this.#finder, signedId, options);
|
|
5039
|
+
return foundByTokenOrThrow(this.#finder.model, lookup, "signed id");
|
|
5040
|
+
}
|
|
5041
|
+
/**
|
|
5042
|
+
* The record a token for `purpose` finds (`await user.generateTokenFor(purpose)`), if this
|
|
5043
|
+
* Model's secret signed it, it hasn't expired, the value it depends on is unchanged, and this
|
|
5044
|
+
* Relation matches it; or null. `TypeError` for a purpose the Model doesn't declare.
|
|
5045
|
+
*/
|
|
5046
|
+
async findByTokenFor(purpose, token) {
|
|
5047
|
+
return (await findByTokenFor(this.#finder, purpose, token)).record;
|
|
5048
|
+
}
|
|
5049
|
+
/**
|
|
5050
|
+
* Like `findByTokenFor`, but throws `InvalidToken` for a token that isn't valid, and
|
|
5051
|
+
* `RecordNotFound` when its record is gone or the value it depends on changed.
|
|
5052
|
+
*/
|
|
5053
|
+
async findByTokenForOrThrow(purpose, token) {
|
|
5054
|
+
const lookup = await findByTokenFor(this.#finder, purpose, token);
|
|
5055
|
+
return foundByTokenOrThrow(this.#finder.model, lookup, "token");
|
|
5056
|
+
}
|
|
5057
|
+
/** This Relation, as a token's record is found through it. */
|
|
5058
|
+
get #finder() {
|
|
5059
|
+
return {
|
|
5060
|
+
model: this[queryOf].model,
|
|
5061
|
+
findBy: (conditions) => this.findBy(conditions)
|
|
5062
|
+
};
|
|
5063
|
+
}
|
|
5064
|
+
};
|
|
5065
|
+
// src/count-questions.ts
|
|
5066
|
+
/** @internal What a Relation's questions about how many records it has read. */
|
|
5067
|
+
const countSource = Symbol("countSource");
|
|
5068
|
+
/** The questions about how many records every Relation has. */
|
|
5069
|
+
var CountQuestions = class extends TokenFinders {
|
|
5070
|
+
/**
|
|
5071
|
+
* The number of records: a loaded association's (built records included) without a query;
|
|
5072
|
+
* otherwise a `COUNT(*)`, plus an association's unsaved built records.
|
|
5073
|
+
*/
|
|
5074
|
+
async size() {
|
|
5075
|
+
return size(this[countSource]());
|
|
5076
|
+
}
|
|
5077
|
+
/** Whether there are no records: a loaded association answers itself, else `!exists()`. */
|
|
5078
|
+
async isEmpty() {
|
|
5079
|
+
return isEmpty(this[countSource]());
|
|
5080
|
+
}
|
|
5081
|
+
/** Whether there are any records: the opposite of `isEmpty()`. */
|
|
5082
|
+
async hasAny() {
|
|
5083
|
+
return !await this.isEmpty();
|
|
5084
|
+
}
|
|
5085
|
+
/** Whether more than one record matches: one `COUNT` of at most two rows. */
|
|
5086
|
+
async hasMoreThanOne() {
|
|
5087
|
+
return await upToTwo(this[countSource]()) > 1;
|
|
5088
|
+
}
|
|
5089
|
+
/** Whether exactly one record matches: one `COUNT` of at most two rows. */
|
|
5090
|
+
async hasExactlyOne() {
|
|
5091
|
+
return await upToTwo(this[countSource]()) === 1;
|
|
5092
|
+
}
|
|
5093
|
+
};
|
|
5094
|
+
// src/query-rewrites.ts
|
|
5095
|
+
/** Each part `unscope` drops, as the query without it. */
|
|
5096
|
+
const WITHOUT = {
|
|
5097
|
+
where: (query) => ({
|
|
5098
|
+
...query,
|
|
5099
|
+
conditions: []
|
|
5100
|
+
}),
|
|
5101
|
+
order: (query) => ({
|
|
5102
|
+
...without(query, "reordered"),
|
|
5103
|
+
order: []
|
|
5104
|
+
}),
|
|
5105
|
+
limit: (query) => without(query, "limit"),
|
|
5106
|
+
offset: (query) => without(query, "offset"),
|
|
5107
|
+
select: (query) => without(query, "select"),
|
|
5108
|
+
distinct: (query) => without(query, "distinct"),
|
|
5109
|
+
includes: (query) => without(query, "includes"),
|
|
5110
|
+
joins: (query) => withoutJoins(query, "inner"),
|
|
5111
|
+
leftJoins: (query) => withoutJoins(query, "left"),
|
|
5112
|
+
createWith: (query) => without(query, "createWith")
|
|
5113
|
+
};
|
|
5114
|
+
/** A copy of `query` without the optional `key`. */
|
|
5115
|
+
function without(query, key) {
|
|
5116
|
+
const copy = { ...query };
|
|
5117
|
+
delete copy[key];
|
|
5118
|
+
return copy;
|
|
5119
|
+
}
|
|
5120
|
+
/** `query` without `part`. */
|
|
5121
|
+
function withoutPart(query, part) {
|
|
5122
|
+
requirePart(part);
|
|
5123
|
+
return keepingOwnerLink(WITHOUT[part](query));
|
|
5124
|
+
}
|
|
5125
|
+
/** Refuses a part `unscope` and `only` don't know: `"group"`, or a misspelling. */
|
|
5126
|
+
function requirePart(part) {
|
|
5127
|
+
if (typeof part !== "string" || !Object.hasOwn(WITHOUT, part)) {
|
|
5128
|
+
const parts = Object.keys(WITHOUT).map((name) => `"${name}"`);
|
|
5129
|
+
throw new TypeError(`A query's parts are ${parts.join(", ")}; got ${String(part)}`);
|
|
5130
|
+
}
|
|
5131
|
+
}
|
|
5132
|
+
/** `query` with only the parts named: every other part is dropped. */
|
|
5133
|
+
function withOnly(query, parts) {
|
|
5134
|
+
for (const part of parts) requirePart(part);
|
|
5135
|
+
return Object.keys(WITHOUT).filter((part) => !parts.includes(part)).reduce(withoutPart, query);
|
|
5136
|
+
}
|
|
5137
|
+
/** `query` without the associations it joins this way, and their joins in turn. */
|
|
5138
|
+
function withoutJoins(query, kind) {
|
|
5139
|
+
const joins = (query.joins ?? []).filter((join) => join.kind !== kind);
|
|
5140
|
+
const used = joinedPaths(query).find((path) => !joins.some((join) => join.association === path));
|
|
5141
|
+
if (used !== void 0) throw new IncompatibleRelation(`unscope() can't drop the join of "${used}": conditions or an order merged onto it use it`);
|
|
5142
|
+
return joins.length === 0 ? without(query, "joins") : {
|
|
5143
|
+
...query,
|
|
5144
|
+
joins
|
|
5145
|
+
};
|
|
5146
|
+
}
|
|
5147
|
+
/** The associations joined at the top that a merged Relation's conditions or order are on. */
|
|
5148
|
+
function joinedPaths({ conditions, order }) {
|
|
5149
|
+
return [...conditions.flatMap(joinedPathsIn), ...order.flatMap((term) => term instanceof JoinedOrder ? [term.path] : [])].map((path) => path.split(".")[0]);
|
|
5150
|
+
}
|
|
5151
|
+
/** The join paths a condition's merged conditions are on, at any depth. */
|
|
5152
|
+
function joinedPathsIn(condition) {
|
|
5153
|
+
if (condition instanceof JoinedConditions) return [condition.path];
|
|
5154
|
+
if (condition instanceof Negated) return joinedPathsIn(condition.condition);
|
|
5155
|
+
if (condition instanceof Either) return [...condition.left, ...condition.right].flatMap(joinedPathsIn);
|
|
5156
|
+
return [];
|
|
5012
5157
|
}
|
|
5013
5158
|
/**
|
|
5014
|
-
*
|
|
5015
|
-
*
|
|
5159
|
+
* `query` without its conditions on `attributes` (`unscope({ where })`): an object condition
|
|
5160
|
+
* loses those keys, and a `whereNot` or `or` condition goes when it names only them. A fragment,
|
|
5161
|
+
* a condition merged onto a join, and one naming other attributes too are kept.
|
|
5016
5162
|
*/
|
|
5017
|
-
|
|
5018
|
-
|
|
5019
|
-
|
|
5020
|
-
|
|
5021
|
-
|
|
5022
|
-
|
|
5023
|
-
|
|
5163
|
+
function withoutConditionsOn(query, attributes) {
|
|
5164
|
+
const resolved = new Set(attributes.map((name) => attributeName(query.model, name)));
|
|
5165
|
+
const isDropped = (name) => resolved.has(attributeName(query.model, name));
|
|
5166
|
+
const link = new Set(query.ownerLink);
|
|
5167
|
+
const conditions = query.conditions.flatMap((condition) => link.has(condition) ? [condition] : remainderOf(condition, isDropped));
|
|
5168
|
+
return keepingOwnerLink({
|
|
5169
|
+
...query,
|
|
5170
|
+
conditions
|
|
5171
|
+
});
|
|
5024
5172
|
}
|
|
5025
|
-
/**
|
|
5026
|
-
function
|
|
5027
|
-
const
|
|
5028
|
-
|
|
5029
|
-
|
|
5173
|
+
/** `query` with `condition` added as part of its link to an association's owner (#350). */
|
|
5174
|
+
function withOwnerLink(query, condition) {
|
|
5175
|
+
const ownerLink = [...query.ownerLink ?? [], condition];
|
|
5176
|
+
return {
|
|
5177
|
+
...query,
|
|
5178
|
+
conditions: [...query.conditions, condition],
|
|
5179
|
+
ownerLink
|
|
5180
|
+
};
|
|
5181
|
+
}
|
|
5182
|
+
/**
|
|
5183
|
+
* `query` with each condition of its owner link that a rewrite dropped added back (#350): within
|
|
5184
|
+
* an `or`, dropping the `or` drops the link with it, so the link is ANDed on again.
|
|
5185
|
+
*/
|
|
5186
|
+
function keepingOwnerLink(query) {
|
|
5187
|
+
const lost = (query.ownerLink ?? []).filter((link) => !query.conditions.some((condition) => hasLink(condition, link)));
|
|
5188
|
+
return lost.length === 0 ? query : {
|
|
5189
|
+
...query,
|
|
5190
|
+
conditions: [...query.conditions, ...lost]
|
|
5191
|
+
};
|
|
5192
|
+
}
|
|
5193
|
+
/** Whether `condition` is `link`, or has it within an `or` or a `whereNot`. */
|
|
5194
|
+
function hasLink(condition, link) {
|
|
5195
|
+
if (condition === link) return true;
|
|
5196
|
+
if (condition instanceof Either) return [...condition.left, ...condition.right].some((each) => hasLink(each, link));
|
|
5197
|
+
return condition instanceof Negated && hasLink(condition.condition, link);
|
|
5198
|
+
}
|
|
5199
|
+
/** Whether a condition is an object of attribute values, `where({ role: "admin" })`. */
|
|
5200
|
+
function isAttributeValues(condition) {
|
|
5201
|
+
return isPlainObject(condition);
|
|
5202
|
+
}
|
|
5203
|
+
/** What's left of `condition` once those on `dropped` attributes go: itself, part of it, or nothing. */
|
|
5204
|
+
function remainderOf(condition, isDropped) {
|
|
5205
|
+
if (isAttributeValues(condition)) {
|
|
5206
|
+
const left = Object.entries(condition).filter(([name]) => !isDropped(name));
|
|
5207
|
+
return left.length === 0 ? [] : [Object.fromEntries(left)];
|
|
5208
|
+
}
|
|
5209
|
+
const named = attributesNamed(condition);
|
|
5210
|
+
return named !== void 0 && named.size > 0 && [...named].every(isDropped) ? [] : [condition];
|
|
5030
5211
|
}
|
|
5031
5212
|
/**
|
|
5032
|
-
*
|
|
5033
|
-
*
|
|
5213
|
+
* The attributes a condition names, or undefined when that can't be known: a fragment's SQL, or
|
|
5214
|
+
* a joined Model's conditions.
|
|
5034
5215
|
*/
|
|
5035
|
-
|
|
5036
|
-
|
|
5037
|
-
|
|
5038
|
-
|
|
5039
|
-
if (
|
|
5040
|
-
|
|
5041
|
-
|
|
5216
|
+
function attributesNamed(condition) {
|
|
5217
|
+
if (isAttributeValues(condition)) return new Set(Object.keys(condition));
|
|
5218
|
+
if (condition instanceof Negated) return attributesNamed(condition.condition);
|
|
5219
|
+
if (condition instanceof LinkedTo) return /* @__PURE__ */ new Set([condition.attribute]);
|
|
5220
|
+
if (condition instanceof Either) return namedByAll([...condition.left, ...condition.right]);
|
|
5221
|
+
}
|
|
5222
|
+
/** The attributes several conditions name together, or undefined when any's can't be known. */
|
|
5223
|
+
function namedByAll(conditions) {
|
|
5224
|
+
const names = /* @__PURE__ */ new Set();
|
|
5225
|
+
for (const condition of conditions) {
|
|
5226
|
+
const named = attributesNamed(condition);
|
|
5227
|
+
if (named === void 0) return void 0;
|
|
5228
|
+
for (const name of named) names.add(name);
|
|
5042
5229
|
}
|
|
5043
|
-
return
|
|
5230
|
+
return names;
|
|
5044
5231
|
}
|
|
5045
|
-
|
|
5046
|
-
|
|
5047
|
-
const
|
|
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")]);
|
|
5232
|
+
/** `query` without one part `unscope` was given: a part's name, or `{ where: attributes }`, which it keeps for `merge`. */
|
|
5233
|
+
function unscoped(query, given) {
|
|
5234
|
+
const part = unscopedPart(query, given);
|
|
5058
5235
|
return {
|
|
5059
|
-
|
|
5060
|
-
|
|
5236
|
+
...withoutUnscoped(query, part),
|
|
5237
|
+
unscoped: [...query.unscoped ?? [], part]
|
|
5061
5238
|
};
|
|
5062
5239
|
}
|
|
5063
|
-
/** What
|
|
5064
|
-
function
|
|
5065
|
-
|
|
5240
|
+
/** What `unscope` was given, checked, with `{ where }`'s attributes as a list. */
|
|
5241
|
+
function unscopedPart(query, given) {
|
|
5242
|
+
if (typeof given === "string") {
|
|
5243
|
+
requirePart(given);
|
|
5244
|
+
return given;
|
|
5245
|
+
}
|
|
5246
|
+
if (typeof given !== "object" || given === null || !("where" in given)) throw new TypeError(`unscope() takes a part's name, or { where: attributes }; got ${String(given)}`);
|
|
5247
|
+
const attributes = typeof given.where === "string" ? [given.where] : [...given.where];
|
|
5248
|
+
for (const name of attributes) columnOf(query.model, name);
|
|
5249
|
+
return { where: attributes };
|
|
5250
|
+
}
|
|
5251
|
+
/** `query` without one part `unscope` dropped. */
|
|
5252
|
+
function withoutUnscoped(query, part) {
|
|
5253
|
+
return typeof part === "string" ? withoutPart(query, part) : withoutConditionsOn(query, part.where);
|
|
5066
5254
|
}
|
|
5067
5255
|
/**
|
|
5068
|
-
*
|
|
5069
|
-
*
|
|
5070
|
-
* fingerprints never say two records share it.
|
|
5256
|
+
* `into` with the parts `other` was unscoped of dropped, before `other` merges into it,
|
|
5257
|
+
* so an unscope carries over; only for a Relation of the same Model, whose parts they name.
|
|
5071
5258
|
*/
|
|
5072
|
-
|
|
5073
|
-
|
|
5074
|
-
|
|
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);
|
|
5086
|
-
}
|
|
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();
|
|
5259
|
+
function withUnscopesOf(into, other) {
|
|
5260
|
+
if (other.unscoped === void 0 || other.model !== into.model) return into;
|
|
5261
|
+
return other.unscoped.reduce(withoutUnscoped, into);
|
|
5092
5262
|
}
|
|
5093
|
-
/**
|
|
5094
|
-
|
|
5095
|
-
|
|
5096
|
-
|
|
5263
|
+
/**
|
|
5264
|
+
* `query` with `conditions` in place of those on their attributes (`rewhere`):
|
|
5265
|
+
* conditions on other attributes, and fragments, are kept.
|
|
5266
|
+
*/
|
|
5267
|
+
function withConditionsReplaced(query, conditions) {
|
|
5268
|
+
requireAttributeConditions(conditions, "rewhere");
|
|
5269
|
+
checkConditions(query.model, conditions, "rewhere");
|
|
5270
|
+
const names = Object.keys(conditions);
|
|
5271
|
+
if (names.length === 0) return query;
|
|
5272
|
+
const rest = withoutConditionsOn(query, names);
|
|
5273
|
+
const normalized = normalizedConditions(query.model, conditions);
|
|
5097
5274
|
return {
|
|
5098
|
-
|
|
5099
|
-
|
|
5100
|
-
if (typeof fingerprint !== "string") return false;
|
|
5101
|
-
return fingerprint === await fingerprintOf(keys, purpose, id, value);
|
|
5102
|
-
}
|
|
5275
|
+
...rest,
|
|
5276
|
+
conditions: [...rest.conditions, normalized]
|
|
5103
5277
|
};
|
|
5104
5278
|
}
|
|
5105
|
-
/**
|
|
5106
|
-
function
|
|
5107
|
-
const
|
|
5108
|
-
if (
|
|
5109
|
-
|
|
5110
|
-
|
|
5111
|
-
|
|
5112
|
-
|
|
5113
|
-
|
|
5114
|
-
return Array.isArray(values) ? values : void 0;
|
|
5115
|
-
} catch {
|
|
5116
|
-
return;
|
|
5117
|
-
}
|
|
5118
|
-
}
|
|
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
|
-
}
|
|
5132
|
-
}
|
|
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));
|
|
5279
|
+
/** `query` without these records (`excluding`), by primary key: `NOT (id IN (…))`. */
|
|
5280
|
+
function withoutRecords(query, records) {
|
|
5281
|
+
const keys = excludedKeys(query.model, records);
|
|
5282
|
+
if (keys.length === 0) return query;
|
|
5283
|
+
const left = new Negated({ [query.model.primaryKey]: keys });
|
|
5284
|
+
return {
|
|
5285
|
+
...query,
|
|
5286
|
+
conditions: [...query.conditions, left]
|
|
5287
|
+
};
|
|
5138
5288
|
}
|
|
5139
5289
|
/**
|
|
5140
|
-
* The
|
|
5141
|
-
*
|
|
5142
|
-
* Wrangler only bundles those, and a test that mocks the module with the adapter inlined reaches it.
|
|
5290
|
+
* The primary keys of the records `excluding` leaves out, each a record of `model` (or a class
|
|
5291
|
+
* extending it); a record without a key yet has no row to leave out.
|
|
5143
5292
|
*/
|
|
5144
|
-
|
|
5145
|
-
|
|
5146
|
-
|
|
5147
|
-
|
|
5148
|
-
|
|
5149
|
-
|
|
5150
|
-
}
|
|
5293
|
+
function excludedKeys(model, records) {
|
|
5294
|
+
return records.flat().flatMap((record) => {
|
|
5295
|
+
if (!(record instanceof model)) throw new TypeError(`excluding() takes records of ${model.name}; got ${describedValue(record)}`);
|
|
5296
|
+
const key = primaryKeyOf(record);
|
|
5297
|
+
return key === null || key === void 0 ? [] : [key];
|
|
5298
|
+
});
|
|
5151
5299
|
}
|
|
5152
|
-
|
|
5153
|
-
|
|
5154
|
-
|
|
5300
|
+
/** How a refusal names what it was given: a record's class, or its type. */
|
|
5301
|
+
function describedValue(value) {
|
|
5302
|
+
if (value instanceof Model) return `a ${value.constructor.name}`;
|
|
5303
|
+
return value === null ? "null" : typeof value;
|
|
5304
|
+
}
|
|
5305
|
+
// src/record-creation.ts
|
|
5155
5306
|
/**
|
|
5156
|
-
*
|
|
5157
|
-
*
|
|
5307
|
+
* @internal A new, unsaved record through `relation`, handed to `init`, which mustn't return a promise
|
|
5308
|
+
* (`TypeError`): nothing awaits it. Through a hasMany, the record then joins the association,
|
|
5309
|
+
* so a record whose `init` throws doesn't.
|
|
5158
5310
|
*/
|
|
5159
|
-
|
|
5160
|
-
|
|
5161
|
-
|
|
5162
|
-
|
|
5163
|
-
|
|
5311
|
+
function buildThrough(relation, attributes, init) {
|
|
5312
|
+
const record = recordToBuild(relation, attributes);
|
|
5313
|
+
refuseInitPromise(relation.model, init?.(record));
|
|
5314
|
+
runBuiltCallbacks(record);
|
|
5315
|
+
relation.collection.built(record);
|
|
5316
|
+
return record;
|
|
5164
5317
|
}
|
|
5165
|
-
/** `
|
|
5166
|
-
function
|
|
5167
|
-
|
|
5318
|
+
/** Throws `TypeError` if a `build` `init` returned a promise, which `build` can't await. */
|
|
5319
|
+
function refuseInitPromise(model, result) {
|
|
5320
|
+
refuseThenable(result, `${model.name}.build(): init returned a promise, which build can't await; findOrInitializeBy and create await it`);
|
|
5168
5321
|
}
|
|
5169
|
-
/**
|
|
5170
|
-
async function
|
|
5171
|
-
|
|
5322
|
+
/** @internal `buildThrough`, awaiting `init`: what `findOrInitializeBy` builds. */
|
|
5323
|
+
async function initializeThrough(relation, attributes, init) {
|
|
5324
|
+
const record = recordToBuild(relation, attributes);
|
|
5325
|
+
await init?.(record);
|
|
5326
|
+
runBuiltCallbacks(record);
|
|
5327
|
+
relation.collection.built(record);
|
|
5328
|
+
return record;
|
|
5172
5329
|
}
|
|
5173
|
-
|
|
5174
|
-
|
|
5175
|
-
const
|
|
5176
|
-
|
|
5177
|
-
|
|
5178
|
-
return secrets;
|
|
5330
|
+
/** @internal Builds and saves a record through `relation`; `orThrow` throws if it can't be saved. */
|
|
5331
|
+
async function createThrough(relation, attributes, { init, orThrow }) {
|
|
5332
|
+
const record = await recordToCreate(relation, attributes, init);
|
|
5333
|
+
await saveCreated(relation, record, orThrow);
|
|
5334
|
+
return record;
|
|
5179
5335
|
}
|
|
5180
|
-
|
|
5181
|
-
|
|
5182
|
-
|
|
5183
|
-
|
|
5184
|
-
|
|
5185
|
-
|
|
5336
|
+
/**
|
|
5337
|
+
* @internal Creates a record through `relation`, as `createThrough` does, or `find`s the row a unique
|
|
5338
|
+
* index kept it from duplicating. It finds only for a record saved alone: when `init` gave it
|
|
5339
|
+
* records to save with it, a refusal may be theirs, so any `RecordNotUnique` reaches the caller.
|
|
5340
|
+
*/
|
|
5341
|
+
async function createOrFindThrough(relation, attributes, options) {
|
|
5342
|
+
const record = await recordToCreate(relation, attributes, options.init);
|
|
5343
|
+
const isSavedAlone = record[state].autosaves.isEmpty();
|
|
5344
|
+
try {
|
|
5345
|
+
await saveCreated(relation, record, options.orThrow);
|
|
5346
|
+
return record;
|
|
5347
|
+
} catch (error) {
|
|
5348
|
+
if (!isSavedAlone || !(error instanceof RecordNotUnique)) throw error;
|
|
5349
|
+
return options.find();
|
|
5350
|
+
}
|
|
5186
5351
|
}
|
|
5187
|
-
|
|
5188
|
-
|
|
5189
|
-
|
|
5352
|
+
async function recordToCreate(relation, attributes, init) {
|
|
5353
|
+
requireSavedOwner$1(relation, "create");
|
|
5354
|
+
const record = recordToBuild(relation, attributes);
|
|
5355
|
+
await init?.(record);
|
|
5356
|
+
runBuiltCallbacks(record);
|
|
5357
|
+
return record;
|
|
5190
5358
|
}
|
|
5191
|
-
/**
|
|
5192
|
-
|
|
5193
|
-
|
|
5194
|
-
|
|
5195
|
-
|
|
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
|
-
};
|
|
5359
|
+
/** A new record through `relation`, pointing back at its owner if it has one. */
|
|
5360
|
+
function recordToBuild(relation, attributes) {
|
|
5361
|
+
const record = newRecord(relation, attributes);
|
|
5362
|
+
relation.collection.pointBack(record);
|
|
5363
|
+
return record;
|
|
5207
5364
|
}
|
|
5208
|
-
|
|
5209
|
-
|
|
5210
|
-
|
|
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);
|
|
5365
|
+
async function saveCreated(relation, record, orThrow) {
|
|
5366
|
+
const { collection } = relation;
|
|
5367
|
+
if (await saveThrough(collection, record, orThrow)) collection.created(record);
|
|
5215
5368
|
}
|
|
5216
|
-
|
|
5217
|
-
|
|
5218
|
-
|
|
5219
|
-
return signedPurposeOf(model, purpose ?? null);
|
|
5369
|
+
/** Saves a record created through `collection`, as its `saveCreated` says, or as the record saves. */
|
|
5370
|
+
function saveThrough(collection, record, orThrow) {
|
|
5371
|
+
return collection.saveCreated?.(record, orThrow) ?? (orThrow ? record.saveOrThrow() : record.save());
|
|
5220
5372
|
}
|
|
5221
|
-
|
|
5222
|
-
|
|
5223
|
-
|
|
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;
|
|
5373
|
+
function newRecord(relation, attributes) {
|
|
5374
|
+
const { assigned, kept } = builtRecordValues(relation, attributes);
|
|
5375
|
+
return buildRecord(relation.model, assigned, relation.executor, kept);
|
|
5227
5376
|
}
|
|
5228
|
-
|
|
5229
|
-
|
|
5230
|
-
|
|
5231
|
-
const
|
|
5232
|
-
|
|
5233
|
-
return
|
|
5234
|
-
id,
|
|
5235
|
-
...expiresAt && { expiresAt }
|
|
5236
|
-
});
|
|
5377
|
+
// src/find-or-create.ts
|
|
5378
|
+
/** @internal `findOrCreateBy` and `findOrCreateByOrThrow`: the record found, or one created. */
|
|
5379
|
+
async function findOrCreate(call, attributes, { init, orThrow }) {
|
|
5380
|
+
const found = await findExisting(call, attributes);
|
|
5381
|
+
if (found !== null) return found;
|
|
5382
|
+
return orThrow ? call.relation.createOrThrow(attributes, init) : call.relation.create(attributes, init);
|
|
5237
5383
|
}
|
|
5238
|
-
/**
|
|
5239
|
-
async function
|
|
5240
|
-
return
|
|
5241
|
-
signer: await signerOf(finder.model, "signed id"),
|
|
5242
|
-
purpose: signedIdPurpose(finder.model, purpose)
|
|
5243
|
-
}, signedId);
|
|
5384
|
+
/** @internal `findOrInitializeBy`: the record found, or one built, its `init` awaited. */
|
|
5385
|
+
async function findOrInitialize(call, attributes, init) {
|
|
5386
|
+
return await findExisting(call, attributes) ?? initializeThrough(call.state, attributes, init);
|
|
5244
5387
|
}
|
|
5245
|
-
|
|
5246
|
-
|
|
5247
|
-
|
|
5248
|
-
|
|
5249
|
-
|
|
5250
|
-
|
|
5251
|
-
const
|
|
5252
|
-
|
|
5253
|
-
|
|
5254
|
-
|
|
5255
|
-
declare(model, "tokenDefinitions", {
|
|
5256
|
-
purpose,
|
|
5257
|
-
...options
|
|
5388
|
+
/**
|
|
5389
|
+
* @internal `createOrFindBy` and `createOrFindByOrThrow`: a record created, or the one a unique
|
|
5390
|
+
* index kept.
|
|
5391
|
+
*/
|
|
5392
|
+
async function createOrFind(call, attributes, options) {
|
|
5393
|
+
const { finder, conditions } = finderFor(call, attributes);
|
|
5394
|
+
const find = () => finder.findByOrThrow(conditions);
|
|
5395
|
+
return createOrFindThrough(call.state, attributes, {
|
|
5396
|
+
...options,
|
|
5397
|
+
find
|
|
5258
5398
|
});
|
|
5259
5399
|
}
|
|
5400
|
+
/** The record with `attributes`, or null: what `findOrCreate` and `findOrInitialize` find. */
|
|
5401
|
+
function findExisting(call, attributes) {
|
|
5402
|
+
const { finder, conditions } = finderFor(call, attributes);
|
|
5403
|
+
return finder.findBy(conditions);
|
|
5404
|
+
}
|
|
5260
5405
|
/**
|
|
5261
|
-
*
|
|
5262
|
-
*
|
|
5406
|
+
* What finds the record with `attributes`, once they're checked: the Relation, narrowed by an
|
|
5407
|
+
* array the attribute casts as one value, compared whole, as the new record holds it, where
|
|
5408
|
+
* `findBy` would read it as a list; and the other attributes, as `findBy` reads them. They're
|
|
5409
|
+
* copied as own keys, so a `__proto__` key from parsed JSON stays an attribute `findBy` refuses.
|
|
5263
5410
|
*/
|
|
5264
|
-
function
|
|
5265
|
-
const
|
|
5266
|
-
|
|
5267
|
-
|
|
5268
|
-
const
|
|
5269
|
-
|
|
5270
|
-
|
|
5411
|
+
function finderFor(call, attributes) {
|
|
5412
|
+
const entries = refuseConditionValues(call, attributes);
|
|
5413
|
+
let finder = call.relation;
|
|
5414
|
+
for (const [name, value] of entries) if (Array.isArray(value)) finder = finder.where(sql`${column(name)} = ${column(name).value(value)}`);
|
|
5415
|
+
const conditions = Object.fromEntries(entries.filter(([, value]) => !Array.isArray(value)));
|
|
5416
|
+
return {
|
|
5417
|
+
finder,
|
|
5418
|
+
conditions
|
|
5419
|
+
};
|
|
5271
5420
|
}
|
|
5272
5421
|
/**
|
|
5273
|
-
*
|
|
5274
|
-
*
|
|
5422
|
+
* Throws `TypeError`, before anything is sent, for attributes a find would read as a condition
|
|
5423
|
+
* but a new record can't take as its values: a list (except an array the attribute casts as one
|
|
5424
|
+
* value), which `findBy` reads as `IN`, so input that skipped `permit` can't match another
|
|
5425
|
+
* user's row; a comparison; a `sql` fragment, as the attributes or as one value; or anything
|
|
5426
|
+
* but an object, whose missing attributes would find any record. The value isn't shown, as it
|
|
5427
|
+
* may be filtered. Returns the attributes' entries, read once.
|
|
5275
5428
|
*/
|
|
5276
|
-
function
|
|
5277
|
-
const
|
|
5278
|
-
if (
|
|
5279
|
-
|
|
5280
|
-
|
|
5281
|
-
|
|
5282
|
-
|
|
5283
|
-
|
|
5284
|
-
}
|
|
5285
|
-
|
|
5286
|
-
|
|
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
|
-
});
|
|
5429
|
+
function refuseConditionValues({ state, method }, attributes) {
|
|
5430
|
+
const named = `${state.model.name}.${method}()`;
|
|
5431
|
+
if (attributes instanceof SafeSql) throw new TypeError(`${named} takes attribute values, not a sql fragment`);
|
|
5432
|
+
if (typeof attributes !== "object" || attributes === null || Array.isArray(attributes)) throw new TypeError(`${named} takes an object of attribute values`);
|
|
5433
|
+
const entries = Object.entries(attributes);
|
|
5434
|
+
for (const [name, value] of entries) {
|
|
5435
|
+
const kind = conditionKind(state.model, name, value);
|
|
5436
|
+
if (kind === void 0) continue;
|
|
5437
|
+
throw new TypeError(`${named}: "${name}" can't be ${kind}, since it becomes the new record's value`);
|
|
5438
|
+
}
|
|
5439
|
+
return entries;
|
|
5296
5440
|
}
|
|
5297
5441
|
/**
|
|
5298
|
-
*
|
|
5299
|
-
*
|
|
5442
|
+
* What a condition `value` of the attribute `name` is, when it's one a new record can't take as
|
|
5443
|
+
* its value. An array the attribute casts as one value is one: a json attribute's, or a custom
|
|
5444
|
+
* type's whose values are arrays.
|
|
5300
5445
|
*/
|
|
5301
|
-
|
|
5302
|
-
|
|
5303
|
-
|
|
5304
|
-
|
|
5305
|
-
|
|
5306
|
-
|
|
5307
|
-
|
|
5308
|
-
|
|
5309
|
-
return lookUpToken(finder, signing, token, async (record, verified) => verified.isUnchanged(await dependsOn(record)));
|
|
5446
|
+
function conditionKind(model, name, value) {
|
|
5447
|
+
if (Array.isArray(value)) return isOneValue(model, name, value) ? void 0 : "a list";
|
|
5448
|
+
if (value instanceof Comparison) return "a comparison";
|
|
5449
|
+
if (value instanceof SafeSql) return "a sql fragment";
|
|
5450
|
+
}
|
|
5451
|
+
/** Whether the attribute `name` casts the array `value` as one value, not as a list of them. */
|
|
5452
|
+
function isOneValue(model, name, value) {
|
|
5453
|
+
return attributeFor(model, name).condition(value) !== noMatch;
|
|
5310
5454
|
}
|
|
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
5455
|
// src/grouping.ts
|
|
5351
5456
|
/**
|
|
5352
5457
|
* A Relation grouped by `group(...)`: its calculations resolve to a Map from each group's key to
|
|
@@ -5793,13 +5898,15 @@ function isTouchable(record, claimed) {
|
|
|
5793
5898
|
/**
|
|
5794
5899
|
* `target`'s touch write, setting what the association's `touch` names, then those it makes in
|
|
5795
5900
|
* turn; nothing if this write has touched it already, or `noTouching` turned its Model's touches
|
|
5796
|
-
* off (#496).
|
|
5901
|
+
* off (#496). A read-only target throws `ReadonlyRecord` (#358).
|
|
5797
5902
|
*/
|
|
5798
5903
|
async function touchOne(target, { touch }, claimed) {
|
|
5799
5904
|
const session = sessionOf(claimed);
|
|
5800
5905
|
const model = modelOf(target);
|
|
5801
5906
|
const key = touchKey(target);
|
|
5802
5907
|
if (session.touched.has(key) || isCoveredByNoTouching(model)) return [];
|
|
5908
|
+
requireWritable(target, "touch");
|
|
5909
|
+
requireWritableColumns(model, touchAssignments(model, touch, "touch").map(([name]) => name));
|
|
5803
5910
|
session.touched.add(key);
|
|
5804
5911
|
let values;
|
|
5805
5912
|
const valuesOf = () => values ??= Object.fromEntries(touchAssignments(model, touch, "touch", timeOf(session)));
|
|
@@ -5957,6 +6064,7 @@ async function touchRecord(record, args) {
|
|
|
5957
6064
|
const model = modelOf(record);
|
|
5958
6065
|
const values = touchValues(model, args, "touch");
|
|
5959
6066
|
if (isCoveredByNoTouching(model)) return false;
|
|
6067
|
+
requireWritableColumns(model, Object.keys(values));
|
|
5960
6068
|
const time = Object.values(values)[0];
|
|
5961
6069
|
const writes = [touchWrite(record, () => values, { version: lockOf(record, "touch") }), ...await touchesOfTouch(record, time)];
|
|
5962
6070
|
const [result] = await writeAll(record[state].executor, writes);
|
|
@@ -6183,7 +6291,7 @@ const ofOwner = Symbol("ofOwner");
|
|
|
6183
6291
|
/** @internal The library's key for running a scope on a Relation. */
|
|
6184
6292
|
const applyScope = Symbol("applyScope");
|
|
6185
6293
|
/** A lazy, immutable description of a query against one Model. */
|
|
6186
|
-
var Relation = class Relation extends
|
|
6294
|
+
var Relation = class Relation extends CountQuestions {
|
|
6187
6295
|
#executor;
|
|
6188
6296
|
#model;
|
|
6189
6297
|
#query;
|
|
@@ -6301,6 +6409,14 @@ var Relation = class Relation extends TokenFinders {
|
|
|
6301
6409
|
return this.#with({ distinct: true });
|
|
6302
6410
|
}
|
|
6303
6411
|
/**
|
|
6412
|
+
* Makes the records this Relation loads read-only (#358): saving or destroying one throws
|
|
6413
|
+
* `ReadonlyRecord`. Records it preloads, builds or creates aren't, and its bulk writes ignore it.
|
|
6414
|
+
* `readonly(false)` undoes it.
|
|
6415
|
+
*/
|
|
6416
|
+
readonly(flag = true) {
|
|
6417
|
+
return this.#with({ readonly: flag });
|
|
6418
|
+
}
|
|
6419
|
+
/**
|
|
6304
6420
|
* Preloads associations for every record this Relation loads, so reading them afterwards
|
|
6305
6421
|
* sends no query: `includes("posts", "profile")`, nested `includes({ posts: "comments" })`.
|
|
6306
6422
|
*/
|
|
@@ -6625,31 +6741,8 @@ var Relation = class Relation extends TokenFinders {
|
|
|
6625
6741
|
cached: () => this.#cached()
|
|
6626
6742
|
};
|
|
6627
6743
|
}
|
|
6628
|
-
/**
|
|
6629
|
-
|
|
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() {
|
|
6744
|
+
/** @internal What `size` and the questions about how many records there are read. */
|
|
6745
|
+
[countSource]() {
|
|
6653
6746
|
return countSourceOf(this.#valueSource(), this.#collection);
|
|
6654
6747
|
}
|
|
6655
6748
|
/** Whether any record matches, optionally with extra conditions. */
|
|
@@ -7341,6 +7434,7 @@ async function prepareRemoval(old, association, claimed) {
|
|
|
7341
7434
|
* nothing is written; one refused before writing keeps its key.
|
|
7342
7435
|
*/
|
|
7343
7436
|
async function nullify(old, association, claimed) {
|
|
7437
|
+
requireWritable(old, "save");
|
|
7344
7438
|
const restore = unlinkInMemory(old, association);
|
|
7345
7439
|
const plan = await prepareSave(old, claimed);
|
|
7346
7440
|
if (plan.status === "ready") return undoneOnFailure(plan, old, association, restore);
|
|
@@ -8086,7 +8180,8 @@ function rejectBadSpecs(model) {
|
|
|
8086
8180
|
column,
|
|
8087
8181
|
type: definition.customType ?? definition.type
|
|
8088
8182
|
};
|
|
8089
|
-
const
|
|
8183
|
+
const where = `${model.name}.${name}`;
|
|
8184
|
+
const problem = specProblem(where, declared) ?? readonlyProblem(where, name, definition.readonly);
|
|
8090
8185
|
if (problem !== void 0) throw new InvalidModel(problem);
|
|
8091
8186
|
}
|
|
8092
8187
|
}
|
|
@@ -9703,7 +9798,9 @@ function aborted(record) {
|
|
|
9703
9798
|
async function saveLifecycle(record, context) {
|
|
9704
9799
|
requireKnownContexts(record, context);
|
|
9705
9800
|
const needs = "save() needs its records";
|
|
9706
|
-
|
|
9801
|
+
const groups = savingGroups(record);
|
|
9802
|
+
requireSavesWritable(groups.flatMap(({ records }) => records));
|
|
9803
|
+
for (const { records } of groups) await pinBefore(linksOf(records), needs);
|
|
9707
9804
|
return withClaimedRecords(async (claimed) => {
|
|
9708
9805
|
const plan = await prepareSave(record, claimed, context);
|
|
9709
9806
|
if (plan.status !== "ready") return plan;
|
|
@@ -9718,6 +9815,7 @@ async function saveLifecycle(record, context) {
|
|
|
9718
9815
|
async function prepareSave(record, claimed, context) {
|
|
9719
9816
|
if (claimed.has(record)) return nothing;
|
|
9720
9817
|
record[state].requireLive("be saved");
|
|
9818
|
+
requireWritable(record, "save");
|
|
9721
9819
|
const validity = await validation(record, claimed, newPass(context), context);
|
|
9722
9820
|
if (validity === "invalid") return { status: "invalid" };
|
|
9723
9821
|
if (validity === "aborted") return aborted(record);
|
|
@@ -9729,6 +9827,7 @@ async function prepareSave(record, claimed, context) {
|
|
|
9729
9827
|
* it, they follow in the next one, once the owner is written.
|
|
9730
9828
|
*/
|
|
9731
9829
|
async function prepareWrites(record, claimed) {
|
|
9830
|
+
requireWritable(record, "save");
|
|
9732
9831
|
claimed.add(record);
|
|
9733
9832
|
const before = await prepareBefore(record, claimed);
|
|
9734
9833
|
if ("status" in before) return before;
|
|
@@ -9858,6 +9957,7 @@ async function destroyLifecycle(record) {
|
|
|
9858
9957
|
/** Everything a destroy does before writing: beforeDestroy, then its dependents' plans. */
|
|
9859
9958
|
async function prepareDestroy(record, claimed) {
|
|
9860
9959
|
if (claimed.has(record)) return nothing;
|
|
9960
|
+
requireWritable(record, "destroy");
|
|
9861
9961
|
claimed.add(record);
|
|
9862
9962
|
const recordState = record[state];
|
|
9863
9963
|
recordState.requireLive("be destroyed");
|
|
@@ -9991,6 +10091,7 @@ const relationMethods = [
|
|
|
9991
10091
|
"offset",
|
|
9992
10092
|
"select",
|
|
9993
10093
|
"distinct",
|
|
10094
|
+
"readonly",
|
|
9994
10095
|
"includes",
|
|
9995
10096
|
"joins",
|
|
9996
10097
|
"leftJoins",
|
|
@@ -10270,7 +10371,7 @@ var AttributeWrites = class extends RecordTokens {
|
|
|
10270
10371
|
* its Model's `noTouching` block, it writes nothing (#496).
|
|
10271
10372
|
*/
|
|
10272
10373
|
async touch(...args) {
|
|
10273
|
-
|
|
10374
|
+
requireWritableRow(this, "touch");
|
|
10274
10375
|
return touchRecord(this, args);
|
|
10275
10376
|
}
|
|
10276
10377
|
/**
|
|
@@ -10278,7 +10379,7 @@ var AttributeWrites = class extends RecordTokens {
|
|
|
10278
10379
|
* validation or callback. Flip the attribute and `save()` to run the save callbacks.
|
|
10279
10380
|
*/
|
|
10280
10381
|
async toggleColumn(name) {
|
|
10281
|
-
|
|
10382
|
+
requireWritableRow(this, "toggleColumn");
|
|
10282
10383
|
return writeColumns(this, { [name]: isTrueOnceToggled(this, name, "toggleColumn") }, "toggleColumn");
|
|
10283
10384
|
}
|
|
10284
10385
|
};
|
|
@@ -10293,10 +10394,11 @@ function isTrueOnceToggled(record, name, method) {
|
|
|
10293
10394
|
*/
|
|
10294
10395
|
async function addToColumn(record, name, by, { method, touch }) {
|
|
10295
10396
|
const recordState = record[state];
|
|
10296
|
-
|
|
10397
|
+
requireWritableRow(record, method);
|
|
10297
10398
|
const model = modelOf$1(record);
|
|
10298
10399
|
const touched = touchAssignments(model, touch, method);
|
|
10299
10400
|
const touchedNames = touched.map(([each]) => each);
|
|
10401
|
+
requireWritableColumns(model, touchedNames);
|
|
10300
10402
|
const after = (numberValue(record, name, method) ?? 0) + by;
|
|
10301
10403
|
const delta = after - (recordState.valueInDatabase(name) ?? 0);
|
|
10302
10404
|
recordState.write(name, after);
|
|
@@ -10308,7 +10410,7 @@ async function addToColumn(record, name, by, { method, touch }) {
|
|
|
10308
10410
|
/** Assigns `attributes`, then UPDATEs only them by the stored key, and marks them saved. */
|
|
10309
10411
|
async function writeColumns(record, given, method) {
|
|
10310
10412
|
const recordState = record[state];
|
|
10311
|
-
|
|
10413
|
+
requireWritableRow(record, method);
|
|
10312
10414
|
const attributes = withAttributeNames(modelOf$1(record), given);
|
|
10313
10415
|
const names = Object.keys(attributes);
|
|
10314
10416
|
if (names.length === 0) throw new TypeError(`${method} needs at least one attribute to write`);
|
|
@@ -10319,10 +10421,14 @@ async function writeColumns(record, given, method) {
|
|
|
10319
10421
|
recordState.commitColumns(names);
|
|
10320
10422
|
return result?.rowsAffected === 1;
|
|
10321
10423
|
}
|
|
10322
|
-
/**
|
|
10323
|
-
|
|
10424
|
+
/**
|
|
10425
|
+
* A write straight to the row needs one: a new record has none, a destroyed one is a snapshot, and
|
|
10426
|
+
* a read-only one refuses it (#358).
|
|
10427
|
+
*/
|
|
10428
|
+
function requireWritableRow(record, method) {
|
|
10324
10429
|
const recordState = record[state];
|
|
10325
10430
|
recordState.requireLive("be written");
|
|
10431
|
+
requireWritable(record, method);
|
|
10326
10432
|
if (recordState.isNew) throw new RecordNotSaved(`${modelOf$1(record).name} record hasn't been saved, so ${method} has no row to write`);
|
|
10327
10433
|
}
|
|
10328
10434
|
const modelOf$1 = (record) => record.constructor;
|
|
@@ -10331,13 +10437,29 @@ function numberValue(record, name, method) {
|
|
|
10331
10437
|
requireAttributeType(modelOf$1(record), name, method, "integer", "real");
|
|
10332
10438
|
return record[state].read(name);
|
|
10333
10439
|
}
|
|
10440
|
+
// src/readonly-marks.ts
|
|
10441
|
+
/** The read-only mark Model's records have. */
|
|
10442
|
+
var ReadonlyMarks = class extends AttributeWrites {
|
|
10443
|
+
/**
|
|
10444
|
+
* Marks the record read-only: saving, destroying, touching it or writing its columns throws
|
|
10445
|
+
* `ReadonlyRecord`, sending nothing. It can still be changed in memory and reloaded.
|
|
10446
|
+
*/
|
|
10447
|
+
markReadonly() {
|
|
10448
|
+
this[state].isReadonly = true;
|
|
10449
|
+
return this;
|
|
10450
|
+
}
|
|
10451
|
+
/** Whether it's read-only: marked by `markReadonly()`, or loaded through a `readonly()` Relation. */
|
|
10452
|
+
isReadonly() {
|
|
10453
|
+
return this[state].isReadonly;
|
|
10454
|
+
}
|
|
10455
|
+
};
|
|
10334
10456
|
// src/model.ts
|
|
10335
10457
|
/**
|
|
10336
10458
|
* The library's base class: an app's base class extends it, and
|
|
10337
10459
|
* methods, statics, callbacks and scopes declared there are shared by every Model built on it.
|
|
10338
10460
|
* It has no table, so it's never used as a Model itself.
|
|
10339
10461
|
*/
|
|
10340
|
-
var Model = class extends
|
|
10462
|
+
var Model = class extends ReadonlyMarks {
|
|
10341
10463
|
/**
|
|
10342
10464
|
* An app-wide query listener, as `connect(env.DB, { onQuery })` is a database's: called for
|
|
10343
10465
|
* every statement of this Model (and those extending it), whichever database runs it, after
|
|
@@ -10650,11 +10772,13 @@ var Model = class extends AttributeWrites {
|
|
|
10650
10772
|
/** `assign` then `save`. */
|
|
10651
10773
|
async update(attributes) {
|
|
10652
10774
|
this[state].requireLive("be updated");
|
|
10775
|
+
requireWritable(this, "save");
|
|
10653
10776
|
return this.assign(attributes).save();
|
|
10654
10777
|
}
|
|
10655
10778
|
/** `assign` then `saveOrThrow`. */
|
|
10656
10779
|
async updateOrThrow(attributes) {
|
|
10657
10780
|
this[state].requireLive("be updated");
|
|
10781
|
+
requireWritable(this, "save");
|
|
10658
10782
|
return this.assign(attributes).saveOrThrow();
|
|
10659
10783
|
}
|
|
10660
10784
|
/**
|
|
@@ -10999,6 +11123,13 @@ function recordsOf(entry) {
|
|
|
10999
11123
|
const { record, kind } = entry[recordStatementParts];
|
|
11000
11124
|
return kind === "save" ? savingGroups(record)[0].records : [record];
|
|
11001
11125
|
}
|
|
11126
|
+
/** Refuses an entry that would write a read-only record (#358), before any entry's callbacks run. */
|
|
11127
|
+
function refuseReadonly(entry) {
|
|
11128
|
+
if (!(entry instanceof RecordStatement)) return;
|
|
11129
|
+
const { record, kind } = entry[recordStatementParts];
|
|
11130
|
+
if (kind === "destroy") requireWritable(record, "destroy");
|
|
11131
|
+
else requireSavesWritable(savingGroups(record).flatMap(({ records }) => records));
|
|
11132
|
+
}
|
|
11002
11133
|
/**
|
|
11003
11134
|
* Refuses an entry whose record would also write on another database (#228), before anything
|
|
11004
11135
|
* runs, since a batch writes one: a save whose autosave reaches one, or a destroy whose
|
|
@@ -11032,6 +11163,7 @@ async function runBatch(entries, needs, handles = []) {
|
|
|
11032
11163
|
const statements = entries.filter((entry) => !(entry instanceof RecordStatement));
|
|
11033
11164
|
const all = [...handles, ...statements.map(executorOf)];
|
|
11034
11165
|
for (const entry of entries) refuseElsewhere(entry, needs);
|
|
11166
|
+
for (const entry of entries) refuseReadonly(entry);
|
|
11035
11167
|
const records = entries.flatMap(recordsOf);
|
|
11036
11168
|
if (all.length === 0 && records.length === 0) return [];
|
|
11037
11169
|
const database = await pinBefore(linksOf(records), needs, all);
|