@forestfuture/active-record 0.7.0 → 0.8.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/config-schema.json +6 -2
- package/dist/adapter.d.mts +3 -3
- package/dist/adapter.mjs +5 -4
- package/dist/batch-Ms5p9lKq.mjs +9777 -0
- package/dist/cli.d.mts +55 -33
- package/dist/cli.mjs +4 -4
- package/dist/command.mjs +530 -271
- package/dist/d1.d.mts +2 -10
- package/dist/d1.mjs +0 -0
- package/dist/{for-adapters-t3-LukJQ.d.mts → for-adapters-BT2GDjIA.d.mts} +8 -6
- package/dist/{for-adapters-Ch6CoHD4.mjs → for-adapters-BbIMUNcz.mjs} +46 -10
- package/dist/{for-adapters-D_Iu0gS_.mjs → for-adapters-C-MQxaIx.mjs} +3 -5
- package/dist/{generated-model-Cnt0Ot9q.mjs → generated-model-DJA8vmNE.mjs} +705 -508
- package/dist/identifiers-Dh5DFACX.mjs +989 -0
- package/dist/index-D5getfHx.d.mts +242 -0
- package/dist/index.d.mts +4 -3
- package/dist/index.mjs +5 -4
- package/dist/metadata-CzntpYzC.d.mts +182 -0
- package/dist/{plugin-Cyoej7qV.mjs → plugin-CZPDqguF.mjs} +211 -112
- package/dist/{plugin-XOHYndhP.mjs → plugin-Cf-5Z0_h.mjs} +148 -52
- package/dist/postgresql.d.mts +1 -9
- package/dist/postgresql.mjs +42 -26
- package/dist/src-BAVZKQ7J.mjs +46 -0
- package/dist/{storage-override-CpbkdIqE.mjs → storage-override-0ZgeP2sc.mjs} +61 -28
- package/dist/validations-BSZ5gVeI.d.mts +2024 -0
- package/llms-full.txt +2326 -229
- package/package.json +1 -1
- package/skills/active-record/SKILL.md +24 -15
- package/dist/adapter-AGKp6wfO.d.mts +0 -1326
- package/dist/batch-BS_WseLf.mjs +0 -4255
- package/dist/epoch-storage-o2aoOH7H.mjs +0 -112
- package/dist/index-CyCJuM96.d.mts +0 -149
- package/dist/src-la_KkjCS.mjs +0 -1
|
@@ -1,146 +1,23 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
/** Base class for every error the library throws on purpose. */
|
|
4
|
-
var ActiveRecordError = class extends Error {
|
|
5
|
-
name = "ActiveRecordError";
|
|
6
|
-
};
|
|
7
|
-
/** A Model's declaration is invalid, e.g. an association's foreign key isn't an attribute. */
|
|
8
|
-
var InvalidModel = class extends ActiveRecordError {
|
|
9
|
-
name = "InvalidModel";
|
|
10
|
-
};
|
|
11
|
-
/** A key that isn't a declared attribute of the Model. */
|
|
12
|
-
var UnknownAttribute = class extends ActiveRecordError {
|
|
13
|
-
name = "UnknownAttribute";
|
|
14
|
-
};
|
|
15
|
-
/** A record constructed directly (`new User()`) was used for something that needs D1. */
|
|
16
|
-
var NoDatabase = class extends ActiveRecordError {
|
|
17
|
-
name = "NoDatabase";
|
|
18
|
-
};
|
|
19
|
-
/** No record matched a lookup that requires one (`find`, `findByOrThrow`). */
|
|
20
|
-
var RecordNotFound = class extends ActiveRecordError {
|
|
21
|
-
name = "RecordNotFound";
|
|
22
|
-
};
|
|
23
|
-
/** Reading an attribute that wasn't loaded, e.g. one left out of `select(...)`. */
|
|
24
|
-
var MissingAttribute = class extends ActiveRecordError {
|
|
25
|
-
name = "MissingAttribute";
|
|
26
|
-
};
|
|
27
|
-
/** Destroying a record whose `dependent: "restrictWithException"` association still has records. */
|
|
28
|
-
var DeleteRestriction = class extends ActiveRecordError {
|
|
29
|
-
name = "DeleteRestriction";
|
|
30
|
-
};
|
|
31
|
-
/** `last()` can't reverse an order given as an `sql` fragment (Rails' IrreversibleOrderError). */
|
|
32
|
-
var IrreversibleOrder = class extends ActiveRecordError {
|
|
33
|
-
name = "IrreversibleOrder";
|
|
34
|
-
};
|
|
35
|
-
/**
|
|
36
|
-
* Things that can't be combined: relations in `or`/`merge` (e.g. of different Models),
|
|
37
|
-
* `includes` or a write statement with `distinct()`, or statements of two Databases in a batch.
|
|
38
|
-
*/
|
|
39
|
-
var IncompatibleRelation = class extends ActiveRecordError {
|
|
40
|
-
name = "IncompatibleRelation";
|
|
41
|
-
};
|
|
42
|
-
/** Using a destroyed record as a live one: `save`, `update`, `destroy` or `reload` after `destroy()`. */
|
|
43
|
-
var RecordDestroyed = class extends ActiveRecordError {
|
|
44
|
-
name = "RecordDestroyed";
|
|
45
|
-
};
|
|
46
|
-
/**
|
|
47
|
-
* D1 rejected a write because of a database constraint. `table`, `columns` and `attributes`
|
|
48
|
-
* are filled in when D1's message names them. `table` is null only for a batch writing to
|
|
49
|
-
* several tables, when D1 doesn't say which one failed. The original D1 error is the `cause`.
|
|
50
|
-
*/
|
|
51
|
-
var ConstraintViolation = class extends ActiveRecordError {
|
|
52
|
-
name = "ConstraintViolation";
|
|
53
|
-
table;
|
|
54
|
-
columns;
|
|
55
|
-
attributes;
|
|
56
|
-
constructor(message, details) {
|
|
57
|
-
super(message, { cause: details.cause });
|
|
58
|
-
this.table = details.table;
|
|
59
|
-
this.columns = details.columns;
|
|
60
|
-
this.attributes = details.attributes;
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
/** A UNIQUE constraint failed, e.g. another request won the race after validation passed. */
|
|
64
|
-
var RecordNotUnique = class extends ConstraintViolation {
|
|
65
|
-
name = "RecordNotUnique";
|
|
66
|
-
};
|
|
67
|
-
/** A FOREIGN KEY constraint failed. SQLite's message doesn't name the column. */
|
|
68
|
-
var InvalidForeignKey = class extends ConstraintViolation {
|
|
69
|
-
name = "InvalidForeignKey";
|
|
70
|
-
};
|
|
71
|
-
/** A NOT NULL constraint failed. */
|
|
72
|
-
var NotNullViolation = class extends ConstraintViolation {
|
|
73
|
-
name = "NotNullViolation";
|
|
74
|
-
};
|
|
75
|
-
/** A CHECK constraint failed. */
|
|
76
|
-
var CheckViolation = class extends ConstraintViolation {
|
|
77
|
-
name = "CheckViolation";
|
|
78
|
-
};
|
|
79
|
-
/** A `…OrThrow` save was refused because the record is invalid; `record.errors` says why. */
|
|
80
|
-
var RecordInvalid = class extends ActiveRecordError {
|
|
81
|
-
name = "RecordInvalid";
|
|
82
|
-
record;
|
|
83
|
-
constructor(record) {
|
|
84
|
-
super(`Validation failed: ${record.errors.fullMessages().join(", ")}`);
|
|
85
|
-
this.record = record;
|
|
86
|
-
}
|
|
87
|
-
};
|
|
88
|
-
/**
|
|
89
|
-
* Thrown by a callback to refuse a save or destroy: `throw abort("Account is suspended")`.
|
|
90
|
-
* Only this exact class halts a lifecycle; returning `false` never does.
|
|
91
|
-
*/
|
|
92
|
-
var CallbackAbort = class extends ActiveRecordError {
|
|
93
|
-
name = "CallbackAbort";
|
|
94
|
-
reason;
|
|
95
|
-
constructor(reason) {
|
|
96
|
-
super(reason);
|
|
97
|
-
this.reason = reason;
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
/** Makes the sentinel a pre-write callback throws to refuse: `throw abort("reason")`. */
|
|
101
|
-
function abort(reason = "Aborted by a callback") {
|
|
102
|
-
return new CallbackAbort(reason);
|
|
103
|
-
}
|
|
104
|
-
/** A `…OrThrow` save was refused by a callback's `abort(reason)`. */
|
|
105
|
-
var RecordNotSaved = class extends ActiveRecordError {
|
|
106
|
-
name = "RecordNotSaved";
|
|
107
|
-
};
|
|
108
|
-
/**
|
|
109
|
-
* `abort()` was thrown from an after-write callback (`afterSave`, `afterCreate`, `afterUpdate`,
|
|
110
|
-
* `afterDestroy`). That's a mistake: the save or destroy already succeeded and nothing rolls back.
|
|
111
|
-
*/
|
|
112
|
-
var AbortAfterPersistence = class extends ActiveRecordError {
|
|
113
|
-
name = "AbortAfterPersistence";
|
|
114
|
-
callback;
|
|
115
|
-
reason;
|
|
116
|
-
constructor(callback, lifecycle, abortion) {
|
|
117
|
-
super(`abort() in ${callback}: the ${lifecycle} has already succeeded`, { cause: abortion });
|
|
118
|
-
this.callback = callback;
|
|
119
|
-
this.reason = abortion.reason;
|
|
120
|
-
}
|
|
121
|
-
};
|
|
122
|
-
/** A `destroyOrThrow()` was refused by a `beforeDestroy` callback's `abort(reason)`. */
|
|
123
|
-
var RecordNotDestroyed = class extends ActiveRecordError {
|
|
124
|
-
name = "RecordNotDestroyed";
|
|
125
|
-
};
|
|
126
|
-
/** A name passed to `includes()` or `loaded()` that isn't one of the Model's associations. */
|
|
127
|
-
var UnknownAssociation = class extends ActiveRecordError {
|
|
128
|
-
name = "UnknownAssociation";
|
|
129
|
-
};
|
|
130
|
-
/** `record.loaded(name)` for an association that wasn't preloaded or read yet. */
|
|
131
|
-
var AssociationNotLoaded = class extends ActiveRecordError {
|
|
132
|
-
name = "AssociationNotLoaded";
|
|
133
|
-
};
|
|
134
|
-
//#endregion
|
|
135
|
-
//#region src/ancestors.ts
|
|
1
|
+
import { C as pluralize, E as underscore, H as RecordDestroyed, I as InvalidModel, R as MissingAttribute, S as isSameCell, Z as UnknownAttribute, b as listedNames, c as castValue, d as uncastable, g as enumProblem, h as enumEntries, i as digitsProblem, l as isInvalidDate, n as reservedWords, o as castCondition, p as writeValue, r as epochStorages, s as castKey, t as isIdentifier, u as readValue, y as isEnumValues, z as NoDatabase } from "./identifiers-Dh5DFACX.mjs";
|
|
2
|
+
// src/ancestors.ts
|
|
136
3
|
/** A class and every class (and object) it extends, nearest first. */
|
|
137
4
|
function ancestors(model) {
|
|
138
5
|
const chain = [];
|
|
139
6
|
for (let current = model; current !== null; current = Object.getPrototypeOf(current)) chain.push(current);
|
|
140
7
|
return chain;
|
|
141
8
|
}
|
|
142
|
-
|
|
143
|
-
|
|
9
|
+
/**
|
|
10
|
+
* How `model`, or the nearest class it extends below `root`, declares the static `name`: its
|
|
11
|
+
* property descriptor, read without calling a getter, or undefined when none does.
|
|
12
|
+
*/
|
|
13
|
+
function staticBelow(model, root, name) {
|
|
14
|
+
for (const each of ancestors(model)) {
|
|
15
|
+
if (each === root) return void 0;
|
|
16
|
+
const declared = Object.getOwnPropertyDescriptor(each, name);
|
|
17
|
+
if (declared !== void 0) return declared;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
// src/table-names.ts
|
|
144
21
|
/**
|
|
145
22
|
* The classes `Model.define({...})` makes; their `table` is inferred unless a subclass sets one.
|
|
146
23
|
* Module-level, but not request state (ADR-0003): derived only from the classes.
|
|
@@ -152,19 +29,37 @@ const bases = /* @__PURE__ */ new WeakSet();
|
|
|
152
29
|
*/
|
|
153
30
|
const boundTables = /* @__PURE__ */ new WeakMap();
|
|
154
31
|
/**
|
|
155
|
-
* Each Model's answer to `
|
|
32
|
+
* Each Model's answer to `isIgnoringColumns`, remembered since the compiler asks on every query.
|
|
156
33
|
* Module-level, but not request state (ADR-0003): derived only from the class.
|
|
157
34
|
*/
|
|
158
35
|
const ignoring = /* @__PURE__ */ new WeakMap();
|
|
36
|
+
/** A class's `modelName`: its own name, unless it (or a class it extends) sets one. */
|
|
37
|
+
function modelNameOf(model) {
|
|
38
|
+
return model.modelName;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Gives the library's base class `modelName`: each class's own name, as Rails' `model_name`,
|
|
42
|
+
* unless it sets `static modelName = "…"`, which the classes extending it inherit (a set one is
|
|
43
|
+
* a value, found before this getter). Empty for a class with no name: anonymous, or `export
|
|
44
|
+
* default`.
|
|
45
|
+
*/
|
|
46
|
+
function defineModelName(root) {
|
|
47
|
+
Object.defineProperty(root, "modelName", {
|
|
48
|
+
configurable: true,
|
|
49
|
+
get() {
|
|
50
|
+
return this.name === "default" ? "" : this.name;
|
|
51
|
+
},
|
|
52
|
+
set: ownValueSetter("modelName")
|
|
53
|
+
});
|
|
54
|
+
}
|
|
159
55
|
/**
|
|
160
|
-
* The
|
|
161
|
-
* Rails; empty when it has none (anonymous, `export default`, or `Model.define({...})` itself).
|
|
56
|
+
* The `modelName` of the class that extends `base` directly, the one a table is named after, as
|
|
57
|
+
* in Rails; empty when it has none (anonymous, `export default`, or `Model.define({...})` itself).
|
|
162
58
|
*/
|
|
163
|
-
function
|
|
59
|
+
function modelNameBelow(base, model) {
|
|
164
60
|
let current = model;
|
|
165
61
|
while (current !== base && Object.getPrototypeOf(current) !== base) current = Object.getPrototypeOf(current);
|
|
166
|
-
|
|
167
|
-
return current === base || name === "default" ? "" : name;
|
|
62
|
+
return current === base ? "" : modelNameOf(current);
|
|
168
63
|
}
|
|
169
64
|
/**
|
|
170
65
|
* A class name's table, by Rails' `tableize`: the name through `underscore`, pluralized
|
|
@@ -197,27 +92,27 @@ function inferTableNames(base) {
|
|
|
197
92
|
Object.defineProperty(base, "table", {
|
|
198
93
|
configurable: true,
|
|
199
94
|
get() {
|
|
200
|
-
const name =
|
|
95
|
+
const name = modelNameBelow(base, this);
|
|
201
96
|
return name === "" ? "" : tableize(name);
|
|
202
97
|
},
|
|
203
98
|
set: ownValueSetter("table")
|
|
204
99
|
});
|
|
205
100
|
}
|
|
206
|
-
/** The
|
|
101
|
+
/** The modelName a Model's table name was inferred from, or undefined when it's declared. */
|
|
207
102
|
function tableNameSource(model) {
|
|
208
103
|
const owner = ancestors(model).find((each) => Object.hasOwn(each, "table"));
|
|
209
|
-
return owner !== void 0 && bases.has(owner) && !boundTables.has(owner) ?
|
|
104
|
+
return owner !== void 0 && bases.has(owner) && !boundTables.has(owner) ? modelNameBelow(owner, model) : void 0;
|
|
210
105
|
}
|
|
211
106
|
/**
|
|
212
107
|
* Binds a generated Model's table to the class it belongs to: a subclass can't name another,
|
|
213
108
|
* since the attributes are that table's columns; and records whether its overrides ignore some
|
|
214
109
|
* columns.
|
|
215
110
|
*/
|
|
216
|
-
function bindTable(owner, table, {
|
|
111
|
+
function bindTable(owner, table, { isIgnoringColumns }) {
|
|
217
112
|
owner.table = table;
|
|
218
113
|
boundTables.set(owner, {
|
|
219
114
|
table,
|
|
220
|
-
|
|
115
|
+
isIgnoringColumns
|
|
221
116
|
});
|
|
222
117
|
}
|
|
223
118
|
/** The table bound to the class `model` is, or extends, if any. */
|
|
@@ -234,10 +129,10 @@ function boundTableOf(model) {
|
|
|
234
129
|
* Remembered per Model: its table is bound when it's first used, before any query, so the
|
|
235
130
|
* answer can't change.
|
|
236
131
|
*/
|
|
237
|
-
function
|
|
132
|
+
function isIgnoringColumns(model) {
|
|
238
133
|
let answer = ignoring.get(model);
|
|
239
134
|
if (answer === void 0) {
|
|
240
|
-
answer = boundTableOf(model)?.
|
|
135
|
+
answer = boundTableOf(model)?.isIgnoringColumns ?? false;
|
|
241
136
|
ignoring.set(model, answer);
|
|
242
137
|
}
|
|
243
138
|
return answer;
|
|
@@ -252,13 +147,18 @@ function rejectAbstract(model) {
|
|
|
252
147
|
const example = model.name ? `, such as class Product extends ${model.name} {}` : "";
|
|
253
148
|
throw new InvalidModel(`${model.name || "This class"} is an abstract base class, with no table; use a Model that extends it${example}`);
|
|
254
149
|
}
|
|
255
|
-
/** A Model must
|
|
150
|
+
/** A Model's `modelName` must be a string, since names are made from it and the schema lists it by it. */
|
|
151
|
+
function requireModelName(model) {
|
|
152
|
+
if (typeof model.modelName === "string") return;
|
|
153
|
+
throw new InvalidModel(`${model.name}'s modelName must be a string; remove it to use the class name`);
|
|
154
|
+
}
|
|
155
|
+
/** A Model must have a table name: its own, or one inferred from its modelName. */
|
|
256
156
|
function requireTableName(model) {
|
|
257
157
|
const { table } = model;
|
|
258
158
|
const bound = boundTableOf(model);
|
|
259
159
|
if (bound !== void 0 && table !== bound.table) throw new InvalidModel(`${model.name} sets table "${String(table)}", but its attributes are the ${bound.table} table's, as ${bound.owner.name}'s are; a subclass shares its parent's table`);
|
|
260
160
|
if (typeof table === "string" && table !== "") return;
|
|
261
|
-
throw new InvalidModel(tableNameSource(model) === "" ? `${model.name || "A Model class"} has no class name to infer its table from; set static table` : `${model.name}'s table must be a table's name; remove it to use the one inferred from
|
|
161
|
+
throw new InvalidModel(tableNameSource(model) === "" ? `${model.name || "A Model class"} has no class name to infer its table from; set static table, or static modelName` : `${model.name}'s table must be a table's name; remove it to use the one inferred from its modelName`);
|
|
262
162
|
}
|
|
263
163
|
/**
|
|
264
164
|
* A database's "no such table" for a table whose name was inferred, as an `InvalidModel` saying where
|
|
@@ -269,19 +169,18 @@ function explainMissingTable(adapter, error, models) {
|
|
|
269
169
|
const model = models.find((each) => each.table === table && tableNameSource(each));
|
|
270
170
|
const source = model && tableNameSource(model);
|
|
271
171
|
if (table === void 0 || model === void 0) return error;
|
|
272
|
-
return new InvalidModel(`${model.name}'s table "${table}" doesn't exist in ${adapter.name} (inferred from the
|
|
172
|
+
return new InvalidModel(`${model.name}'s table "${table}" doesn't exist in ${adapter.name} (inferred from the modelName ${source}; create it, set static table, or set static modelName if your bundler renames classes)`, { cause: error });
|
|
273
173
|
}
|
|
274
174
|
/**
|
|
275
|
-
* The
|
|
276
|
-
* is (`Post`, for `class FeaturedPost extends Post {}`).
|
|
175
|
+
* The name a Model's foreign keys are inferred from: the `modelName` of the class whose table
|
|
176
|
+
* it is (`Post`, for `class FeaturedPost extends Post {}`).
|
|
277
177
|
*/
|
|
278
|
-
function
|
|
178
|
+
function tableOwnerModelName(model) {
|
|
279
179
|
const base = ancestors(model).find((each) => bases.has(each));
|
|
280
|
-
if (base !== void 0) return
|
|
281
|
-
return (boundTableOf(model)?.owner ?? model)
|
|
180
|
+
if (base !== void 0) return modelNameBelow(base, model);
|
|
181
|
+
return modelNameOf(boundTableOf(model)?.owner ?? model);
|
|
282
182
|
}
|
|
283
|
-
|
|
284
|
-
//#region src/filtering.ts
|
|
183
|
+
// src/filtering.ts
|
|
285
184
|
/** What a listener sees in place of a filtered attribute's value (#83). */
|
|
286
185
|
const FILTERED = "[FILTERED]";
|
|
287
186
|
/**
|
|
@@ -304,11 +203,16 @@ const defaultFilterAttributes = [
|
|
|
304
203
|
];
|
|
305
204
|
/**
|
|
306
205
|
* Whether `attribute`'s values are hidden from listeners: its snake_case name holds a string
|
|
307
|
-
* entry
|
|
206
|
+
* entry lowercased, or read in snake_case (`"apiKey"` as `api_key`, #397), or a RegExp entry
|
|
207
|
+
* matches the attribute or its snake_case name.
|
|
308
208
|
*/
|
|
309
209
|
function isFiltered(model, attribute) {
|
|
310
210
|
const name = underscore(attribute);
|
|
311
|
-
return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
|
|
211
|
+
return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) || name.includes(underscore(entry)) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
|
|
212
|
+
}
|
|
213
|
+
/** The values of `attributes` that `model` filters, so a message can tell not to show them. */
|
|
214
|
+
function filteredValues(model, attributes) {
|
|
215
|
+
return Object.entries(attributes).filter(([name]) => isFiltered(model, name)).map(([, value]) => value);
|
|
312
216
|
}
|
|
313
217
|
/** A bound value D1 gets as `value`, and listeners see as `shown`. */
|
|
314
218
|
var Filtered = class {
|
|
@@ -331,249 +235,23 @@ function boundValue(param) {
|
|
|
331
235
|
function shownValue$1(param) {
|
|
332
236
|
return param instanceof Filtered ? param.shown : param;
|
|
333
237
|
}
|
|
334
|
-
|
|
335
|
-
//#region src/conversion.ts
|
|
336
|
-
/** A value that can't be read as the attribute's type. */
|
|
337
|
-
const uncastable = Symbol("uncastable");
|
|
338
|
-
const identity = (value) => value;
|
|
339
|
-
const keyOf = ({ type, storage }) => storage ?? type;
|
|
340
|
-
const converters = {
|
|
341
|
-
string: {
|
|
342
|
-
cast: text,
|
|
343
|
-
read: text,
|
|
344
|
-
write: identity
|
|
345
|
-
},
|
|
346
|
-
integer: {
|
|
347
|
-
cast: castInteger,
|
|
348
|
-
read: safeInteger,
|
|
349
|
-
write: identity
|
|
350
|
-
},
|
|
351
|
-
real: {
|
|
352
|
-
cast: castReal,
|
|
353
|
-
read: finiteNumber,
|
|
354
|
-
write: identity
|
|
355
|
-
},
|
|
356
|
-
boolean: {
|
|
357
|
-
cast: castBoolean,
|
|
358
|
-
read: readBoolean,
|
|
359
|
-
write: (value) => value ? 1 : 0
|
|
360
|
-
},
|
|
361
|
-
datetime: {
|
|
362
|
-
cast: castDatetime,
|
|
363
|
-
read: readDatetime,
|
|
364
|
-
write: (value) => value.toISOString()
|
|
365
|
-
},
|
|
366
|
-
unixSeconds: {
|
|
367
|
-
cast: castDatetime,
|
|
368
|
-
read: unixTime(1e3),
|
|
369
|
-
write: (value) => Math.floor(value.getTime() / 1e3)
|
|
370
|
-
},
|
|
371
|
-
unixMilliseconds: {
|
|
372
|
-
cast: castDatetime,
|
|
373
|
-
read: unixTime(1),
|
|
374
|
-
write: (value) => value.getTime()
|
|
375
|
-
},
|
|
376
|
-
json: {
|
|
377
|
-
cast: castJson,
|
|
378
|
-
read: readJson,
|
|
379
|
-
write: (value) => JSON.stringify(value)
|
|
380
|
-
}
|
|
381
|
-
};
|
|
382
|
-
/** `value` as the attribute's type (null stays null), or `uncastable`. */
|
|
383
|
-
function castValue(attribute, value) {
|
|
384
|
-
return value === null ? null : converters[keyOf(attribute)].cast(value);
|
|
385
|
-
}
|
|
386
|
-
/**
|
|
387
|
-
* A condition's value as the attribute's type, or `uncastable`: as `castValue`, except that a
|
|
388
|
-
* finite number matches a string attribute as its decimal string (`7` → `"7"`), as `find` does
|
|
389
|
-
* for a text key and as Rails does, so a foreign key of another type still finds its target.
|
|
390
|
-
*/
|
|
391
|
-
function castCondition(attribute, value) {
|
|
392
|
-
if (attribute.type === "string" && typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
393
|
-
return castValue(attribute, value);
|
|
394
|
-
}
|
|
395
|
-
/**
|
|
396
|
-
* A stored value as the attribute's, or `uncastable` for one that isn't. `Attribute#read`, in
|
|
397
|
-
* attribute.ts, is how a cell D1 returned is read, so it fails naming its attribute.
|
|
398
|
-
*/
|
|
399
|
-
function readValue(attribute, value) {
|
|
400
|
-
return value === null || value === void 0 ? null : converters[keyOf(attribute)].read(value);
|
|
401
|
-
}
|
|
402
|
-
function writeValue(attribute, value) {
|
|
403
|
-
return value === null || value === void 0 ? null : converters[keyOf(attribute)].write(value);
|
|
404
|
-
}
|
|
405
|
-
/**
|
|
406
|
-
* Converts a value with no declared attribute type (e.g. one interpolated into
|
|
407
|
-
* an `sql` fragment) using the converter its runtime type implies, so it's
|
|
408
|
-
* stored the same way as an attribute of that type.
|
|
409
|
-
*/
|
|
410
|
-
function writeUntypedValue(value) {
|
|
411
|
-
if (value instanceof Date) return writeValue({ type: "datetime" }, value);
|
|
412
|
-
if (typeof value === "boolean") return writeValue({ type: "boolean" }, value);
|
|
413
|
-
return value;
|
|
414
|
-
}
|
|
415
|
-
const booleans = /* @__PURE__ */ new Map([
|
|
416
|
-
[true, true],
|
|
417
|
-
[false, false],
|
|
418
|
-
[1, true],
|
|
419
|
-
[0, false],
|
|
420
|
-
["1", true],
|
|
421
|
-
["0", false],
|
|
422
|
-
["true", true],
|
|
423
|
-
["false", false],
|
|
424
|
-
["on", true],
|
|
425
|
-
["off", false]
|
|
426
|
-
]);
|
|
427
|
-
/** `true`/`false`, `1`/`0`, `"1"`/`"0"`, and `"true"`/`"false"` or `"on"`/`"off"` in any case. */
|
|
428
|
-
function castBoolean(value) {
|
|
429
|
-
const key = typeof value === "string" ? value.toLowerCase() : value;
|
|
430
|
-
return booleans.has(key) ? booleans.get(key) : uncastable;
|
|
431
|
-
}
|
|
432
|
-
/**
|
|
433
|
-
* Any value JSON can write, as it is. What `stringify` writes lossily (a `Map` as `{}`, `NaN` as
|
|
434
|
-
* `null`) is kept; what it throws on (a BigInt, a cycle) or gives nothing for (a function, a
|
|
435
|
-
* symbol) is refused (#146). It's checked here, and written again at save, so a value is
|
|
436
|
-
* refused where it's assigned rather than where it's stored, and the cost is one more
|
|
437
|
-
* `stringify` per assignment.
|
|
438
|
-
*/
|
|
439
|
-
function castJson(value) {
|
|
440
|
-
try {
|
|
441
|
-
return JSON.stringify(value) === void 0 ? uncastable : value;
|
|
442
|
-
} catch {
|
|
443
|
-
return uncastable;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
/**
|
|
447
|
-
* Text is parsed; one that isn't JSON is `uncastable`. Under a column declared JSON, SQLite
|
|
448
|
-
* stores a number-like value (123) as a number, and D1 returns it as one, which is already the
|
|
449
|
-
* value.
|
|
450
|
-
*/
|
|
451
|
-
function readJson(value) {
|
|
452
|
-
if (typeof value !== "string") return value;
|
|
453
|
-
try {
|
|
454
|
-
return JSON.parse(value);
|
|
455
|
-
} catch {
|
|
456
|
-
return uncastable;
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
/** A whole number, signed, with nothing else but spaces around it. */
|
|
460
|
-
const integerText = /^\s*[+-]?\d+\s*$/;
|
|
461
|
-
/**
|
|
462
|
-
* A decimal number, with an optional exponent (`1.5`, `-2e3`, `.5`), and spaces around it.
|
|
463
|
-
* Digits after the point only follow a point, so no run of digits can match two ways: an
|
|
464
|
-
* optional point between two runs of digits backtracks quadratically on a long string (ReDoS).
|
|
465
|
-
*/
|
|
466
|
-
const realText = /^\s*[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?\s*$/i;
|
|
467
|
-
/** `value` as a number: a number as it is, or a string matching `pattern`; else `uncastable`. */
|
|
468
|
-
function numberFrom(value, pattern) {
|
|
469
|
-
if (typeof value === "number") return value;
|
|
470
|
-
return typeof value === "string" && pattern.test(value) ? Number(value) : uncastable;
|
|
471
|
-
}
|
|
472
|
-
/** `value` if it's text, else `uncastable`. */
|
|
473
|
-
function text(value) {
|
|
474
|
-
return typeof value === "string" ? value : uncastable;
|
|
475
|
-
}
|
|
476
|
-
/** `value` if it's a safe integer, else `uncastable`. */
|
|
477
|
-
function safeInteger(value) {
|
|
478
|
-
return Number.isSafeInteger(value) ? value : uncastable;
|
|
479
|
-
}
|
|
480
|
-
/** `value` if it's a finite number, else `uncastable`. */
|
|
481
|
-
function finiteNumber(value) {
|
|
482
|
-
return Number.isFinite(value) ? value : uncastable;
|
|
483
|
-
}
|
|
484
|
-
/** A safe integer, or a string that's wholly one: `1.7`, `"12abc"` and `"1e3"` aren't. */
|
|
485
|
-
function castInteger(value) {
|
|
486
|
-
return safeInteger(numberFrom(value, integerText));
|
|
487
|
-
}
|
|
488
|
-
/** A finite number, or a string that's wholly a decimal number. */
|
|
489
|
-
function castReal(value) {
|
|
490
|
-
return finiteNumber(numberFrom(value, realText));
|
|
491
|
-
}
|
|
492
|
-
/** A Unix time of this many milliseconds per unit as a `Date`; anything but a number is `uncastable`. */
|
|
493
|
-
function unixTime(millisecondsPer) {
|
|
494
|
-
return (value) => typeof value === "number" ? validDate(new Date(value * millisecondsPer)) : uncastable;
|
|
495
|
-
}
|
|
496
|
-
/** An ISO-8601 date: `2026-01-02`, read as midnight UTC. */
|
|
497
|
-
const isoDate = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
498
|
-
/** An ISO-8601 date and time, with `Z` or an offset: a time without one is ambiguous. */
|
|
499
|
-
const isoDateTime = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
500
|
-
/** A stored date and time with no zone, as SQLite's `CURRENT_TIMESTAMP` writes it: UTC (#73). */
|
|
501
|
-
const zonelessDateTime = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/;
|
|
502
|
-
/** What `toISOString` writes, the form datetimes are stored in: `2026-01-02T03:04:05.678Z`. */
|
|
503
|
-
const isoStringForm = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
504
|
-
/** What `toISOString` writes for a year outside 0000-9999: a sign and six digits (`+010000-…`). */
|
|
505
|
-
const expandedYearDateTime = /^[+-]\d{6}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
506
|
-
/**
|
|
507
|
-
* A stored datetime as a `Date`: text in a form an assignment accepts (an ISO date, or a date and
|
|
508
|
-
* time with its offset), what `toISOString` writes for a far year, or SQLite's own, with no
|
|
509
|
-
* zone, which is UTC, where `new Date` would read it in the process's time zone. A number isn't
|
|
510
|
-
* one: it's a Unix time (#73), and read as a time in ISO text it would be a moment in January
|
|
511
|
-
* 1970 (#159).
|
|
512
|
-
*/
|
|
513
|
-
function readDatetime(value) {
|
|
514
|
-
if (typeof value !== "string") return uncastable;
|
|
515
|
-
const stored = isoStringForm.test(value) ? dateIfOnCalendar(value) : void 0;
|
|
516
|
-
if (stored !== void 0) return stored;
|
|
517
|
-
if (expandedYearDateTime.test(value)) return dateIfCanonical(value) ?? uncastable;
|
|
518
|
-
return castDatetime(zonelessDateTime.test(value) ? `${value}Z` : value);
|
|
519
|
-
}
|
|
520
|
-
/**
|
|
521
|
-
* Text in the stored form as a `Date`, if it names a moment on the calendar. `value` must match
|
|
522
|
-
* `isoStringForm`, which fixes where the month and day are. Every character is then a digit or a
|
|
523
|
-
* fixed separator, so only the calendar can be wrong, and `Date` rolls a day that
|
|
524
|
-
* doesn't exist over (`2026-02-30` to 2 March, `T24:00` to the next day): a date whose day or
|
|
525
|
-
* month isn't the text's is refused. Cheaper than writing the text back to compare (#216).
|
|
526
|
-
*/
|
|
527
|
-
function dateIfOnCalendar(value) {
|
|
528
|
-
const date = new Date(value);
|
|
529
|
-
const month = Number(value.slice(5, 7));
|
|
530
|
-
const day = Number(value.slice(8, 10));
|
|
531
|
-
return date.getUTCDate() === day && date.getUTCMonth() + 1 === month ? date : void 0;
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* `value` as a `Date`, if `toISOString` writes exactly this text for it. That also refuses a day
|
|
535
|
-
* that doesn't exist, and a year written with more digits than it needs (`+002026`).
|
|
536
|
-
*/
|
|
537
|
-
function dateIfCanonical(value) {
|
|
538
|
-
const date = new Date(value);
|
|
539
|
-
return !isInvalidDate(date) && date.toISOString() === value ? date : void 0;
|
|
540
|
-
}
|
|
541
|
-
/** `1` and `0` are the stored form of a boolean; any other cell isn't one. */
|
|
542
|
-
function readBoolean(value) {
|
|
543
|
-
if (value === 1) return true;
|
|
544
|
-
return value === 0 ? false : uncastable;
|
|
545
|
-
}
|
|
546
|
-
/** A valid `Date`, or an ISO-8601 string (a date, or a date and time with its offset). */
|
|
547
|
-
function castDatetime(value) {
|
|
548
|
-
if (value instanceof Date) return isInvalidDate(value) ? uncastable : value;
|
|
549
|
-
if (typeof value !== "string") return uncastable;
|
|
550
|
-
if (isoDate.test(value)) return dayOf(value) ?? uncastable;
|
|
551
|
-
if (!isoDateTime.test(value) || dayOf(value.slice(0, 10)) === void 0) return uncastable;
|
|
552
|
-
const date = new Date(value.replace(" ", "T"));
|
|
553
|
-
return isInvalidDate(date) ? uncastable : date;
|
|
554
|
-
}
|
|
555
|
-
/** `date`, or `uncastable` for an invalid one (a stored number past the range of a `Date`). */
|
|
556
|
-
function validDate(date) {
|
|
557
|
-
return isInvalidDate(date) ? uncastable : date;
|
|
558
|
-
}
|
|
559
|
-
/** Midnight UTC on `day` (`2026-01-02`), if that day exists. */
|
|
560
|
-
function dayOf(day) {
|
|
561
|
-
const date = /* @__PURE__ */ new Date(`${day}T00:00:00.000Z`);
|
|
562
|
-
return !isInvalidDate(date) && date.toISOString().startsWith(day) ? date : void 0;
|
|
563
|
-
}
|
|
564
|
-
function isInvalidDate(value) {
|
|
565
|
-
return value instanceof Date && Number.isNaN(value.getTime());
|
|
566
|
-
}
|
|
567
|
-
//#endregion
|
|
568
|
-
//#region src/spec-keys.ts
|
|
238
|
+
// src/spec-keys.ts
|
|
569
239
|
const attributeTypes = Object.keys({
|
|
570
240
|
string: true,
|
|
571
241
|
integer: true,
|
|
572
242
|
real: true,
|
|
243
|
+
decimal: true,
|
|
573
244
|
boolean: true,
|
|
574
245
|
datetime: true,
|
|
575
|
-
|
|
246
|
+
date: true,
|
|
247
|
+
time: true,
|
|
248
|
+
json: true,
|
|
249
|
+
binary: true
|
|
576
250
|
});
|
|
251
|
+
/** The built-in types' names, as a message lists them: `"string", "integer", …`. */
|
|
252
|
+
const typeNameList = attributeTypes.map((name) => `"${String(name)}"`).join(", ");
|
|
253
|
+
/** The built-in types' names as a list to choose from: `"string", …, or "binary"`. */
|
|
254
|
+
const attributeTypeNames = typeNameList.replace(/, ([^,]+)$/, ", or $1");
|
|
577
255
|
/** Whether `value` names an attribute type. */
|
|
578
256
|
function isAttributeType(value) {
|
|
579
257
|
return attributeTypes.includes(value);
|
|
@@ -584,7 +262,7 @@ function isAttributeType(value) {
|
|
|
584
262
|
*/
|
|
585
263
|
const rules = {
|
|
586
264
|
type: {
|
|
587
|
-
isWellFormed: isAttributeType,
|
|
265
|
+
isWellFormed: (value) => isAttributeType(value) || isCustomType(value),
|
|
588
266
|
copiedToDefinition: false
|
|
589
267
|
},
|
|
590
268
|
null: {
|
|
@@ -620,8 +298,81 @@ const rules = {
|
|
|
620
298
|
because: "only a datetime is stored as an epoch"
|
|
621
299
|
},
|
|
622
300
|
onRetype: "drop"
|
|
301
|
+
},
|
|
302
|
+
precision: decimalDigits("a precision"),
|
|
303
|
+
scale: decimalDigits("a scale"),
|
|
304
|
+
enum: {
|
|
305
|
+
isWellFormed: isEnumValues,
|
|
306
|
+
describedAs: "an enum",
|
|
307
|
+
onlyFor: {
|
|
308
|
+
types: ["string", "integer"],
|
|
309
|
+
because: "an enum is stored as text or integers"
|
|
310
|
+
},
|
|
311
|
+
problemFor: enumProblem,
|
|
312
|
+
onRetype: "drop"
|
|
313
|
+
},
|
|
314
|
+
prefix: affixRule("prefix"),
|
|
315
|
+
suffix: affixRule("suffix"),
|
|
316
|
+
scopes: methodsSwitch("scopes"),
|
|
317
|
+
instanceMethods: methodsSwitch("instanceMethods"),
|
|
318
|
+
validate: {
|
|
319
|
+
isWellFormed: isEnumValidation,
|
|
320
|
+
describedAs: "validate",
|
|
321
|
+
wellFormedAs: "use true, or { allowNull: true }",
|
|
322
|
+
isGiven: isGivenUnless(false),
|
|
323
|
+
requires: "enum",
|
|
324
|
+
onRetype: "drop"
|
|
623
325
|
}
|
|
624
326
|
};
|
|
327
|
+
/** The rule for a decimal's precision or scale: a whole number of digits. */
|
|
328
|
+
function decimalDigits(describedAs) {
|
|
329
|
+
return {
|
|
330
|
+
isWellFormed: (value) => Number.isSafeInteger(value) && value >= 0,
|
|
331
|
+
describedAs,
|
|
332
|
+
wellFormedAs: "use a whole number of digits",
|
|
333
|
+
onlyFor: {
|
|
334
|
+
types: ["decimal"],
|
|
335
|
+
because: "only a decimal has digits to limit"
|
|
336
|
+
},
|
|
337
|
+
onRetype: "drop"
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
/** `true`, `false`, or an object holding only a boolean `allowNull`. */
|
|
341
|
+
function isEnumValidation(value) {
|
|
342
|
+
if (typeof value === "boolean") return true;
|
|
343
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
344
|
+
return Object.entries(value).every(([key, each]) => key === "allowNull" && (each === void 0 || typeof each === "boolean"));
|
|
345
|
+
}
|
|
346
|
+
/** The rule for a switch that leaves an enum's methods out when it's `false`. */
|
|
347
|
+
function methodsSwitch(key) {
|
|
348
|
+
return {
|
|
349
|
+
isWellFormed: (value) => typeof value === "boolean",
|
|
350
|
+
describedAs: key,
|
|
351
|
+
wellFormedAs: "use false to leave them out",
|
|
352
|
+
isGiven: isGivenUnless(true),
|
|
353
|
+
requires: "enum",
|
|
354
|
+
onRetype: "drop"
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
/** `isGiven` for a key whose `off` value (and `undefined`) leaves it as if it weren't given. */
|
|
358
|
+
function isGivenUnless(off) {
|
|
359
|
+
return (value) => value !== void 0 && value !== off;
|
|
360
|
+
}
|
|
361
|
+
/** The rule for a prefix or a suffix: a word around an enum's names in its methods' names. */
|
|
362
|
+
function affixRule(key) {
|
|
363
|
+
return {
|
|
364
|
+
isWellFormed: isAffix,
|
|
365
|
+
describedAs: `a ${key}`,
|
|
366
|
+
wellFormedAs: "use true for the attribute's name, or a word",
|
|
367
|
+
isGiven: isGivenUnless(false),
|
|
368
|
+
requires: "enum",
|
|
369
|
+
onRetype: "drop"
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
/** A prefix or suffix: `true` for the attribute's name, `false` for none, or a word. */
|
|
373
|
+
function isAffix(value) {
|
|
374
|
+
return typeof value === "boolean" || typeof value === "string" && value !== "";
|
|
375
|
+
}
|
|
625
376
|
const entries = Object.entries(rules);
|
|
626
377
|
/** For each key, the keys it conflicts with, whichever of the two declares it. */
|
|
627
378
|
const conflicts = new Map(entries.map(([key]) => [key, []]));
|
|
@@ -629,6 +380,12 @@ for (const [key, { conflictsWith = [] }] of entries) for (const other of conflic
|
|
|
629
380
|
conflicts.get(key).push(other);
|
|
630
381
|
conflicts.get(other).push(key);
|
|
631
382
|
}
|
|
383
|
+
/** An enum's keys: `enum`, and those it means nothing without (`prefix`, `scopes`, …). */
|
|
384
|
+
const enumKeys = new Set(entries.filter(([key, rule]) => key === "enum" || rule.requires === "enum").map(([key]) => key));
|
|
385
|
+
/** A spec without its enum and the keys that go with one (#64). */
|
|
386
|
+
function withoutEnum(spec) {
|
|
387
|
+
return Object.fromEntries(Object.entries(spec).filter(([key]) => !enumKeys.has(key)));
|
|
388
|
+
}
|
|
632
389
|
/** The keys an override may hold, as a message lists them: `type, null, default, …`. */
|
|
633
390
|
const overridableKeyNames = entries.filter(([, rule]) => rule.overridable !== false).map(([key]) => key).join(", ");
|
|
634
391
|
/** The value of a key if it's given, else `undefined`. */
|
|
@@ -636,6 +393,10 @@ function givenValue(spec, key) {
|
|
|
636
393
|
const value = spec[key];
|
|
637
394
|
return (rules[key].isGiven ?? ((each) => each !== void 0))(value) ? value : void 0;
|
|
638
395
|
}
|
|
396
|
+
/** How a spec's type reads in a message: `"integer"`, or `a custom type` (#20). */
|
|
397
|
+
function typeNamed(type) {
|
|
398
|
+
return isAttributeType(type) ? `"${type}"` : "a custom type";
|
|
399
|
+
}
|
|
639
400
|
/** How a key reads in a message. */
|
|
640
401
|
const readsAs = (key) => rules[key].describedAs ?? key;
|
|
641
402
|
/** Whether `value` is an object holding only spec keys an override may change, each well formed or `undefined`. */
|
|
@@ -659,23 +420,40 @@ function shown$1(value) {
|
|
|
659
420
|
return String(value);
|
|
660
421
|
}
|
|
661
422
|
}
|
|
423
|
+
/** The problem with a given key's shape, past the types, or with it given without the key it needs. */
|
|
424
|
+
function shapeProblem(where, spec, key) {
|
|
425
|
+
const { requires, isWellFormed, wellFormedAs } = rules[key];
|
|
426
|
+
const value = givenValue(spec, key);
|
|
427
|
+
if (wellFormedAs !== void 0 && !isWellFormed(value)) return `${where} has ${readsAs(key)} ${shown$1(value)}; ${wellFormedAs}`;
|
|
428
|
+
if (requires !== void 0 && givenValue(spec, requires) === void 0) return `${where} has ${readsAs(key)} but no ${requires}; give it ${readsAs(requires)}, or remove ${readsAs(key)}`;
|
|
429
|
+
}
|
|
662
430
|
/** The problem with a given key's value, or with its attribute's type. */
|
|
663
431
|
function valueProblem(where, spec, key) {
|
|
664
|
-
const { allowedValues, onlyFor } = rules[key];
|
|
432
|
+
const { allowedValues, onlyFor, problemFor } = rules[key];
|
|
665
433
|
const value = givenValue(spec, key);
|
|
666
434
|
if (allowedValues !== void 0 && !allowedValues.includes(value)) {
|
|
667
435
|
const names = allowedValues.map((each) => `"${each}"`).join(" or ");
|
|
668
436
|
return `${where} has ${key} ${shown$1(value)}; use ${names}`;
|
|
669
437
|
}
|
|
670
|
-
|
|
438
|
+
const { type } = spec;
|
|
439
|
+
if (onlyFor !== void 0 && !(isAttributeType(type) && onlyFor.types.includes(type))) return `${where} is ${typeNamed(type)}, so it can't have ${readsAs(key)}: ${onlyFor.because}`;
|
|
440
|
+
const problem = isAttributeType(type) ? problemFor?.(value, type) : void 0;
|
|
441
|
+
return problem === void 0 ? void 0 : `${where}${problem}`;
|
|
671
442
|
}
|
|
672
443
|
/** Why a spec can't be as it is, or undefined if it can. `where` names it (`User.id`). */
|
|
673
444
|
function specProblem(where, spec) {
|
|
445
|
+
if (!rules.type.isWellFormed(spec.type)) return `${where} has type ${shown$1(spec.type)}; use a type's name (${typeNameList}), or a type defineType made`;
|
|
674
446
|
for (const [key] of entries) {
|
|
675
447
|
if (givenValue(spec, key) === void 0) continue;
|
|
676
|
-
const problem = conflictProblem(where, spec, key) ?? valueProblem(where, spec, key);
|
|
448
|
+
const problem = conflictProblem(where, spec, key) ?? shapeProblem(where, spec, key) ?? valueProblem(where, spec, key);
|
|
677
449
|
if (problem !== void 0) return problem;
|
|
678
450
|
}
|
|
451
|
+
return decimalDigitsProblem(where, spec);
|
|
452
|
+
}
|
|
453
|
+
/** A precision and scale no `NUMERIC(p, s)` can have (#398). */
|
|
454
|
+
function decimalDigitsProblem(where, spec) {
|
|
455
|
+
const problem = digitsProblem(spec);
|
|
456
|
+
return problem === void 0 ? void 0 : `${where} has ${problem}`;
|
|
679
457
|
}
|
|
680
458
|
/**
|
|
681
459
|
* `base` with `override` applied. A key `override` gives replaces one it conflicts with, and a new
|
|
@@ -694,24 +472,77 @@ function applyOverride(base, override) {
|
|
|
694
472
|
...given
|
|
695
473
|
};
|
|
696
474
|
}
|
|
697
|
-
/** The keys of `spec` that go into its attribute's definition as given:
|
|
475
|
+
/** The keys of `spec` that go into its attribute's definition as given: all but its type, nullability and column. */
|
|
698
476
|
function copiedKeys(spec) {
|
|
699
477
|
const copied = entries.filter(([key, rule]) => rule.copiedToDefinition !== false && givenValue(spec, key) !== void 0).map(([key]) => [key, spec[key]]);
|
|
700
478
|
return Object.fromEntries(copied);
|
|
701
479
|
}
|
|
702
|
-
|
|
703
|
-
|
|
480
|
+
// src/custom-types.ts
|
|
481
|
+
/** Every type `defineType` made, so a spec can't pass off another object as one. */
|
|
482
|
+
const defined = /* @__PURE__ */ new WeakSet();
|
|
483
|
+
/**
|
|
484
|
+
* Defines an attribute type, used in a spec as a type name is: `price: money`, or
|
|
485
|
+
* `{ type: money, null: false }`. Its values are kept as `storedAs` keeps its own, so they're
|
|
486
|
+
* read strictly, compared and ordered as that type's are.
|
|
487
|
+
*/
|
|
488
|
+
function defineType(type) {
|
|
489
|
+
requireWellFormed(type);
|
|
490
|
+
const made = Object.freeze({
|
|
491
|
+
storedAs: type.storedAs,
|
|
492
|
+
cast: (input) => type.cast(input),
|
|
493
|
+
serialize: (value) => type.serialize(value),
|
|
494
|
+
deserialize: (stored) => type.deserialize(stored)
|
|
495
|
+
});
|
|
496
|
+
defined.add(made);
|
|
497
|
+
return made;
|
|
498
|
+
}
|
|
499
|
+
/** The functions a type needs, each checked when it's made. */
|
|
500
|
+
const functionNames = [
|
|
501
|
+
"cast",
|
|
502
|
+
"serialize",
|
|
503
|
+
"deserialize"
|
|
504
|
+
];
|
|
505
|
+
/**
|
|
506
|
+
* Throws `TypeError` for a type that couldn't work, past the types (plain JavaScript, or a cast):
|
|
507
|
+
* a `storedAs` that isn't a built-in type's name, or a function it lacks.
|
|
508
|
+
*/
|
|
509
|
+
function requireWellFormed(type) {
|
|
510
|
+
if (!isAttributeType(type.storedAs)) throw new TypeError(`defineType: storedAs ${JSON.stringify(type.storedAs)} isn't a type's name; use ${attributeTypeNames}`);
|
|
511
|
+
const missing = functionNames.find((name) => typeof type[name] !== "function");
|
|
512
|
+
if (missing !== void 0) throw new TypeError(`defineType: ${missing} isn't a function`);
|
|
513
|
+
}
|
|
514
|
+
/** Whether `value` is a type `defineType` made. */
|
|
515
|
+
function isCustomType(value) {
|
|
516
|
+
return typeof value === "object" && value !== null && defined.has(value);
|
|
517
|
+
}
|
|
518
|
+
// src/metadata.ts
|
|
519
|
+
/** A spec written out: a type alone (a name, or a custom type) as `{ type }`. */
|
|
520
|
+
function specObjectOf(spec) {
|
|
521
|
+
return typeof spec === "string" || isCustomType(spec) ? { type: spec } : spec;
|
|
522
|
+
}
|
|
704
523
|
/** Resolves an attribute's spec into its type, column and default. */
|
|
705
524
|
function define(name, spec) {
|
|
706
|
-
|
|
525
|
+
if (typeof spec === "string") return {
|
|
707
526
|
type: spec,
|
|
708
527
|
column: underscore(name)
|
|
709
|
-
}
|
|
710
|
-
|
|
528
|
+
};
|
|
529
|
+
if (isCustomType(spec)) return {
|
|
530
|
+
...resolvedType(spec),
|
|
531
|
+
column: underscore(name)
|
|
532
|
+
};
|
|
533
|
+
return {
|
|
534
|
+
...resolvedType(spec.type),
|
|
711
535
|
column: spec.column ?? underscore(name),
|
|
712
536
|
...copiedKeys(spec)
|
|
713
537
|
};
|
|
714
538
|
}
|
|
539
|
+
/** A spec's type as a definition holds it: a custom type as the type it's stored as, and itself. */
|
|
540
|
+
function resolvedType(type) {
|
|
541
|
+
return isCustomType(type) ? {
|
|
542
|
+
type: type.storedAs,
|
|
543
|
+
customType: type
|
|
544
|
+
} : { type };
|
|
545
|
+
}
|
|
715
546
|
/** Looks up a declared attribute; throws `UnknownAttribute` for any other name. */
|
|
716
547
|
function attributeOf(model, name) {
|
|
717
548
|
const attribute = model.attributeDefinitions.get(name);
|
|
@@ -737,8 +568,7 @@ function initialValues(model, given = {}) {
|
|
|
737
568
|
function hasInitialValue(definition) {
|
|
738
569
|
return definition.generateId === true || definition.default !== void 0;
|
|
739
570
|
}
|
|
740
|
-
|
|
741
|
-
//#region src/attribute.ts
|
|
571
|
+
// src/attribute.ts
|
|
742
572
|
/** What `condition()` and `conditionCell()` give for a value that can't match anything. */
|
|
743
573
|
const noMatch = uncastable;
|
|
744
574
|
/**
|
|
@@ -762,6 +592,10 @@ var Attribute = class {
|
|
|
762
592
|
get isText() {
|
|
763
593
|
return this.#definition.type === "string";
|
|
764
594
|
}
|
|
595
|
+
/** Whether it's a `binary` attribute, whose cells are bytes, which JSON can't hold (#20). */
|
|
596
|
+
get isBinary() {
|
|
597
|
+
return this.#definition.type === "binary";
|
|
598
|
+
}
|
|
765
599
|
/** Whether it's a `json` attribute, whose stored text is JSON itself. */
|
|
766
600
|
get isJson() {
|
|
767
601
|
return this.#definition.type === "json";
|
|
@@ -774,7 +608,14 @@ var Attribute = class {
|
|
|
774
608
|
*/
|
|
775
609
|
cast(value) {
|
|
776
610
|
requireDefined(this.#model, this.name, value);
|
|
777
|
-
|
|
611
|
+
const cast = this.#convertOrRefuse(value, () => castValue(this.#definition, value));
|
|
612
|
+
if (cast === uncastable && this.#isValidatedEnum()) return value;
|
|
613
|
+
return this.#orRefuse(cast, value);
|
|
614
|
+
}
|
|
615
|
+
/** Whether it's an enum declared `validate: true`, which keeps an unknown value it's given. */
|
|
616
|
+
#isValidatedEnum() {
|
|
617
|
+
const { enum: values, validate = false } = this.#definition;
|
|
618
|
+
return values !== void 0 && validate !== false;
|
|
778
619
|
}
|
|
779
620
|
/**
|
|
780
621
|
* A key copied from another record or inherited from a condition: cast as a condition's, but
|
|
@@ -782,7 +623,7 @@ var Attribute = class {
|
|
|
782
623
|
*/
|
|
783
624
|
key(value, association) {
|
|
784
625
|
requireDefined(this.#model, this.name, value);
|
|
785
|
-
return this.#orRefuse(
|
|
626
|
+
return this.#orRefuse(castKey(this.#definition, value), value, association);
|
|
786
627
|
}
|
|
787
628
|
/**
|
|
788
629
|
* A condition's value (`where`, `find`, a preload) as the attribute's type, or `noMatch`: a
|
|
@@ -806,6 +647,7 @@ var Attribute = class {
|
|
|
806
647
|
try {
|
|
807
648
|
stored = writeValue(this.#definition, value);
|
|
808
649
|
} catch (error) {
|
|
650
|
+
if (this.#definition.customType !== void 0) throw this.#refusal(value, void 0, error);
|
|
809
651
|
if (this.#definition.type !== "json") throw error;
|
|
810
652
|
throw this.#refusal(value);
|
|
811
653
|
}
|
|
@@ -822,7 +664,7 @@ var Attribute = class {
|
|
|
822
664
|
* attribute, with the cell hidden if it's filtered, not the parser's own error (#73, #146).
|
|
823
665
|
*/
|
|
824
666
|
read(cell) {
|
|
825
|
-
const value = readValue(this.#definition, cell);
|
|
667
|
+
const value = this.#convertOrRefuse(cell, () => readValue(this.#definition, cell));
|
|
826
668
|
if (value === uncastable) throw this.#refusal(cell);
|
|
827
669
|
return value;
|
|
828
670
|
}
|
|
@@ -830,9 +672,24 @@ var Attribute = class {
|
|
|
830
672
|
copy(value) {
|
|
831
673
|
return this.read(this.write(value));
|
|
832
674
|
}
|
|
833
|
-
/**
|
|
834
|
-
same(
|
|
835
|
-
|
|
675
|
+
/**
|
|
676
|
+
* Whether two values are the same as stored (dates by time, json and bytes by content). Each is
|
|
677
|
+
* cast as a condition's value first, so `isAttributeChanged`'s `from` and `to` compare as
|
|
678
|
+
* Rails' do, and one that can't be cast is the same as nothing (#20).
|
|
679
|
+
*/
|
|
680
|
+
isSame(a, b) {
|
|
681
|
+
const [x, y] = [this.#comparable(a), this.#comparable(b)];
|
|
682
|
+
if (x === noMatch || y === noMatch) return false;
|
|
683
|
+
return isSameCell(writeValue(this.#definition, x), writeValue(this.#definition, y));
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* A value to compare, cast as a condition's: `null` stays `null`, and a validated enum's
|
|
687
|
+
* unknown value, which a record may hold, stays as it is (#340).
|
|
688
|
+
*/
|
|
689
|
+
#comparable(value) {
|
|
690
|
+
if (value === null || value === void 0) return value ?? null;
|
|
691
|
+
const cast = this.condition(value);
|
|
692
|
+
return cast === noMatch && this.#isValidatedEnum() ? value : cast;
|
|
836
693
|
}
|
|
837
694
|
/** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
|
|
838
695
|
bind(params, value) {
|
|
@@ -844,29 +701,47 @@ var Attribute = class {
|
|
|
844
701
|
* time, since `filterAttributes` is a static a Model may set after this was resolved.
|
|
845
702
|
*/
|
|
846
703
|
bindCells(params, ...cells) {
|
|
847
|
-
const hidden = this.#
|
|
704
|
+
const hidden = this.#isHidden();
|
|
848
705
|
for (const cell of cells) params.push(hidden ? new Filtered(cell) : cell);
|
|
849
706
|
}
|
|
850
707
|
#orRefuse(cast, value, association) {
|
|
851
708
|
if (cast === uncastable) throw this.#refusal(value, association);
|
|
852
709
|
return cast;
|
|
853
710
|
}
|
|
711
|
+
/**
|
|
712
|
+
* `convert`'s result. What a custom type's own function throws for `value` is refused as any
|
|
713
|
+
* value its type can't hold, with the type's error as the cause (#20).
|
|
714
|
+
*/
|
|
715
|
+
#convertOrRefuse(value, convert) {
|
|
716
|
+
try {
|
|
717
|
+
return convert();
|
|
718
|
+
} catch (error) {
|
|
719
|
+
if (this.#definition.customType === void 0) throw error;
|
|
720
|
+
throw this.#refusal(value, void 0, error);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
854
723
|
/** Whether the attribute's values are hidden from listeners and errors (#83). */
|
|
855
|
-
#
|
|
724
|
+
#isHidden() {
|
|
856
725
|
return isFiltered(this.#model, this.name);
|
|
857
726
|
}
|
|
858
727
|
/**
|
|
859
728
|
* "Sample: "no" isn't a boolean for "enabled"", the value hidden for a filtered attribute. Also
|
|
860
729
|
* what a stored value that can't be read says: a Unix time that isn't one (#73), or a json
|
|
861
|
-
* cell that isn't JSON (#146).
|
|
730
|
+
* cell that isn't JSON (#146). A custom type's own error is its cause, unless the attribute is
|
|
731
|
+
* filtered: the error may show the value (#20).
|
|
862
732
|
*/
|
|
863
|
-
#refusal(value, association) {
|
|
864
|
-
const
|
|
865
|
-
const
|
|
866
|
-
const article = /^[aeiou]/.test(noun) ? "an" : "a";
|
|
867
|
-
const text = this.#hidden() ? FILTERED : shown(value);
|
|
733
|
+
#refusal(value, association, cause) {
|
|
734
|
+
const hidden = this.#isHidden();
|
|
735
|
+
const text = hidden ? FILTERED : shown(value);
|
|
868
736
|
const from = association === void 0 ? "" : `, the key of ${association}`;
|
|
869
|
-
return
|
|
737
|
+
return new TypeError(`${this.#model.name}: ${text} isn't ${this.#described()} for "${this.name}"${from}`, hidden || cause === void 0 ? void 0 : { cause });
|
|
738
|
+
}
|
|
739
|
+
/** What a value of the attribute is, as a refusal says it: `a boolean`, `one of "draft", "published"`. */
|
|
740
|
+
#described() {
|
|
741
|
+
const { type, enum: values, customType } = this.#definition;
|
|
742
|
+
if (values !== void 0) return `one of ${listedNames(values)}`;
|
|
743
|
+
if (customType !== void 0) return "a valid value";
|
|
744
|
+
return valueNames[type] ?? withArticle(type);
|
|
870
745
|
}
|
|
871
746
|
};
|
|
872
747
|
const resolved = /* @__PURE__ */ new WeakMap();
|
|
@@ -888,19 +763,6 @@ function attributeFor(model, name) {
|
|
|
888
763
|
return attribute;
|
|
889
764
|
}
|
|
890
765
|
/**
|
|
891
|
-
* Rows of `names`' values, assigned, as one JSON value the dialect reads them from; listeners see
|
|
892
|
-
* a filtered attribute's column as "[FILTERED]" in every row.
|
|
893
|
-
*/
|
|
894
|
-
function storedRows(model, names, rows) {
|
|
895
|
-
const attributes = names.map((name) => attributeFor(model, name));
|
|
896
|
-
const stored = rows.map((row) => row.map((value, index) => attributes[index].store(value)));
|
|
897
|
-
const json = JSON.stringify(stored);
|
|
898
|
-
const filtered = names.map((attribute) => isFiltered(model, attribute));
|
|
899
|
-
if (!filtered.includes(true)) return json;
|
|
900
|
-
const shown = stored.map((row) => row.map((value, index) => filtered[index] ? FILTERED : value));
|
|
901
|
-
return new Filtered(json, JSON.stringify(shown));
|
|
902
|
-
}
|
|
903
|
-
/**
|
|
904
766
|
* The values a record built from a Relation inherits from its conditions, cast as keys are: a
|
|
905
767
|
* hasMany's foreign key names its association (`link`) when it can't be cast.
|
|
906
768
|
*/
|
|
@@ -910,16 +772,25 @@ function castInherited(model, inherited, link) {
|
|
|
910
772
|
return [attribute, attributeFor(model, attribute).key(value, association)];
|
|
911
773
|
}));
|
|
912
774
|
}
|
|
775
|
+
/** A word with `a` or `an` before it, as a message reads it: `an integer`, `a string`. */
|
|
776
|
+
function withArticle(word) {
|
|
777
|
+
return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
|
|
778
|
+
}
|
|
913
779
|
/** How much of a value an error shows: it came from outside, and errors are often logged. */
|
|
914
780
|
const SHOWN_LENGTH = 60;
|
|
915
|
-
/** What an attribute type is called in a refusal, where its name isn't it. */
|
|
916
|
-
const
|
|
781
|
+
/** What a value of an attribute type is called in a refusal, where `a`/`an` and its name isn't it. */
|
|
782
|
+
const valueNames = {
|
|
783
|
+
json: "a JSON value",
|
|
784
|
+
binary: "binary data"
|
|
785
|
+
};
|
|
917
786
|
/** A value as an error shows it: JSON where it has one, numbers as written, and at most 60 characters. */
|
|
918
787
|
function shown(value) {
|
|
919
788
|
const text = textOf(value);
|
|
920
789
|
return text.length > SHOWN_LENGTH ? `${text.slice(0, SHOWN_LENGTH)}…` : text;
|
|
921
790
|
}
|
|
922
791
|
function textOf(value) {
|
|
792
|
+
if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return `<${value.constructor.name} of ${value.byteLength} bytes>`;
|
|
793
|
+
if (value instanceof Blob) return `<${value.constructor.name} of ${value.size} bytes>`;
|
|
923
794
|
if (typeof value === "number" || isInvalidDate(value)) return String(value);
|
|
924
795
|
try {
|
|
925
796
|
return JSON.stringify(value) ?? String(value);
|
|
@@ -935,8 +806,7 @@ function plainText(value) {
|
|
|
935
806
|
return Object.prototype.toString.call(value);
|
|
936
807
|
}
|
|
937
808
|
}
|
|
938
|
-
|
|
939
|
-
//#region src/declarations.ts
|
|
809
|
+
// src/declarations.ts
|
|
940
810
|
/**
|
|
941
811
|
* Per-Model declarations (validations, callbacks, …), keyed by Model class. A subclass starts
|
|
942
812
|
* from a copy of its parent's list, so declaring on it never changes the parent.
|
|
@@ -994,13 +864,16 @@ function listsOf(lists, model) {
|
|
|
994
864
|
lists.set(model, found);
|
|
995
865
|
return found;
|
|
996
866
|
}
|
|
997
|
-
|
|
998
|
-
//#region src/error-messages.ts
|
|
867
|
+
// src/error-messages.ts
|
|
999
868
|
/** @internal Rails' English messages, used where no class has its own (listed in the guide). */
|
|
1000
869
|
const builtInMessages = {
|
|
1001
870
|
blank: "can't be blank",
|
|
871
|
+
present: "must be blank",
|
|
1002
872
|
invalid: "is invalid",
|
|
873
|
+
required: "must exist",
|
|
1003
874
|
inclusion: "is not included in the list",
|
|
875
|
+
exclusion: "is reserved",
|
|
876
|
+
accepted: "must be accepted",
|
|
1004
877
|
taken: "has already been taken",
|
|
1005
878
|
tooShort: {
|
|
1006
879
|
one: "is too short (minimum is 1 character)",
|
|
@@ -1020,6 +893,8 @@ const builtInMessages = {
|
|
|
1020
893
|
greaterThanOrEqualTo: "must be greater than or equal to %{count}",
|
|
1021
894
|
lessThan: "must be less than %{count}",
|
|
1022
895
|
lessThanOrEqualTo: "must be less than or equal to %{count}",
|
|
896
|
+
equalTo: "must be equal to %{count}",
|
|
897
|
+
otherThan: "must be other than %{count}",
|
|
1023
898
|
restrictDependentDestroy: {
|
|
1024
899
|
hasOne: "Cannot delete record because a dependent %{record} exists",
|
|
1025
900
|
hasMany: "Cannot delete record because dependent %{record} exist"
|
|
@@ -1069,7 +944,7 @@ function messageText(template, entry) {
|
|
|
1069
944
|
}
|
|
1070
945
|
/** "createdAt" → "Created at" */
|
|
1071
946
|
function inWords(name) {
|
|
1072
|
-
const words = underscore(name).replaceAll(
|
|
947
|
+
const words = underscore(name).replaceAll(/[_.]/g, " ");
|
|
1073
948
|
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
1074
949
|
}
|
|
1075
950
|
/** An attribute's name as messages show it: a class's `humanAttributeNames`, or "Created at". */
|
|
@@ -1093,7 +968,7 @@ function messageOf(source, entry) {
|
|
|
1093
968
|
if (text === void 0) throw missingMessage(model, entry);
|
|
1094
969
|
return text.replace(/%\{(\w+)\}/g, (placeholder, name) => {
|
|
1095
970
|
if (name === "attribute") return humanAttributeName(model, entry.attribute);
|
|
1096
|
-
if (name === "model") return inWords(model.
|
|
971
|
+
if (name === "model") return inWords(model.modelName);
|
|
1097
972
|
if (name === "value") return shownValue(source, entry.attribute);
|
|
1098
973
|
return String(ownValue(entry.values, name) ?? placeholder);
|
|
1099
974
|
});
|
|
@@ -1115,8 +990,7 @@ function attributesNamedInMessages(model) {
|
|
|
1115
990
|
names: values.flatMap((value) => Object.keys(value))
|
|
1116
991
|
}))];
|
|
1117
992
|
}
|
|
1118
|
-
|
|
1119
|
-
//#region src/inspect-support.ts
|
|
993
|
+
// src/inspect-support.ts
|
|
1120
994
|
/** Node and workerd call a value's inspector under this registered symbol. */
|
|
1121
995
|
const inspectCustom = Symbol.for("nodejs.util.inspect.custom");
|
|
1122
996
|
/** Text in the color of a special value, or plain when colors are off. */
|
|
@@ -1144,12 +1018,13 @@ function printed(label, name, body, { depth, options, inspect }) {
|
|
|
1144
1018
|
depth
|
|
1145
1019
|
})}`;
|
|
1146
1020
|
}
|
|
1147
|
-
|
|
1148
|
-
//#region src/errors-collection.ts
|
|
1021
|
+
// src/errors-collection.ts
|
|
1149
1022
|
/** @internal The library's key for emptying an errors collection. */
|
|
1150
1023
|
const clearErrors = Symbol("clearErrors");
|
|
1151
1024
|
/** @internal The library's key for adding a failure it found, with an optional message to use as it is. */
|
|
1152
1025
|
const addFailure = Symbol("addFailure");
|
|
1026
|
+
/** @internal The library's key for a failure's full message, without adding it (`strict`). */
|
|
1027
|
+
const fullMessageOf = Symbol("fullMessageOf");
|
|
1153
1028
|
/** A record's validation errors: `record.errors`. Cleared at the start of each validation run. */
|
|
1154
1029
|
var Errors = class {
|
|
1155
1030
|
#entries = [];
|
|
@@ -1184,11 +1059,12 @@ var Errors = class {
|
|
|
1184
1059
|
}
|
|
1185
1060
|
/** Every message with its attribute's human name first: "Email can't be blank". */
|
|
1186
1061
|
fullMessages() {
|
|
1187
|
-
return this.#entries.map((entry) =>
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1062
|
+
return this.#entries.map((entry) => this.#fullMessage(entry));
|
|
1063
|
+
}
|
|
1064
|
+
#fullMessage(entry) {
|
|
1065
|
+
const message = messageOf(this.#source, entry);
|
|
1066
|
+
if (entry.attribute === "base") return message;
|
|
1067
|
+
return `${humanAttributeName(this.#source.model, entry.attribute)} ${message}`;
|
|
1192
1068
|
}
|
|
1193
1069
|
/** Every error as `{ attribute, type, message }`, with its `values` when it has some (copies). */
|
|
1194
1070
|
toArray() {
|
|
@@ -1229,13 +1105,20 @@ var Errors = class {
|
|
|
1229
1105
|
this.#entries.push(entry);
|
|
1230
1106
|
return messageOf(this.#source, entry);
|
|
1231
1107
|
}
|
|
1108
|
+
/** @internal A failure's full message, as `fullMessages()` would give it, without adding it. */
|
|
1109
|
+
[fullMessageOf](attribute, { values = {}, ...failure }) {
|
|
1110
|
+
return this.#fullMessage({
|
|
1111
|
+
attribute,
|
|
1112
|
+
values,
|
|
1113
|
+
...failure
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1232
1116
|
/** @internal Called at the start of each validation run. */
|
|
1233
1117
|
[clearErrors]() {
|
|
1234
1118
|
this.#entries = [];
|
|
1235
1119
|
}
|
|
1236
1120
|
};
|
|
1237
|
-
|
|
1238
|
-
//#region src/loaded-associations.ts
|
|
1121
|
+
// src/loaded-associations.ts
|
|
1239
1122
|
/**
|
|
1240
1123
|
* The associations one record has loaded (preloaded, read, or set by a write): a record, an
|
|
1241
1124
|
* array of records, or null. Each stays loaded while the owner's attribute still holds the key
|
|
@@ -1254,7 +1137,7 @@ var LoadedAssociations = class {
|
|
|
1254
1137
|
/** The loaded association, if it was loaded for the key the owner holds now. */
|
|
1255
1138
|
get(name) {
|
|
1256
1139
|
const entry = this.#entries.get(name);
|
|
1257
|
-
if (entry === void 0 || !
|
|
1140
|
+
if (entry === void 0 || !isSameKey(this.#key(entry.attribute), entry.key)) return void 0;
|
|
1258
1141
|
return entry;
|
|
1259
1142
|
}
|
|
1260
1143
|
/**
|
|
@@ -1271,10 +1154,10 @@ var LoadedAssociations = class {
|
|
|
1271
1154
|
}
|
|
1272
1155
|
/**
|
|
1273
1156
|
* Starts a load of the association, before its query is sent, for the key its query was built
|
|
1274
|
-
* for: the function it returns keeps the loaded value only if nothing changed the association
|
|
1157
|
+
* for (the attributes' values now, unless it's given): the function it returns keeps the loaded value only if nothing changed the association
|
|
1275
1158
|
* meanwhile (#181).
|
|
1276
1159
|
*/
|
|
1277
|
-
startLoad(name, attribute, key) {
|
|
1160
|
+
startLoad(name, attribute, key = this.#key(attribute)) {
|
|
1278
1161
|
const generation = this.#generation(name);
|
|
1279
1162
|
return (value) => {
|
|
1280
1163
|
if (this.#generation(name) === generation) this.#entries.set(name, {
|
|
@@ -1295,6 +1178,7 @@ var LoadedAssociations = class {
|
|
|
1295
1178
|
this.#allLoadsDiscarded += 1;
|
|
1296
1179
|
}
|
|
1297
1180
|
#key(attribute) {
|
|
1181
|
+
if (typeof attribute !== "string") return attribute.map((each) => this.#keyOf(each) ?? null);
|
|
1298
1182
|
return this.#keyOf(attribute) ?? null;
|
|
1299
1183
|
}
|
|
1300
1184
|
#discardPendingLoads(name) {
|
|
@@ -1308,11 +1192,16 @@ var LoadedAssociations = class {
|
|
|
1308
1192
|
return this.#allLoadsDiscarded + (this.#loadsDiscarded.get(name) ?? 0);
|
|
1309
1193
|
}
|
|
1310
1194
|
};
|
|
1311
|
-
|
|
1312
|
-
|
|
1195
|
+
/** Whether two keys are the same: one value, or each of a list's (#60). */
|
|
1196
|
+
function isSameKey(now, loaded) {
|
|
1197
|
+
if (!Array.isArray(now) || !Array.isArray(loaded)) return Object.is(now, loaded);
|
|
1198
|
+
return now.every((each, index) => Object.is(each, loaded[index]));
|
|
1199
|
+
}
|
|
1200
|
+
// src/pending-autosaves.ts
|
|
1313
1201
|
/**
|
|
1314
|
-
* The
|
|
1315
|
-
* associations, after it
|
|
1202
|
+
* The records saving one record may also save: those built through its hasMany and hasOne
|
|
1203
|
+
* associations or pushed onto a hasMany, after it (`autosavesOf` says which), and the new ones
|
|
1204
|
+
* its belongsTo associations point at, before it.
|
|
1316
1205
|
*/
|
|
1317
1206
|
var PendingAutosaves = class {
|
|
1318
1207
|
#built = /* @__PURE__ */ new Map();
|
|
@@ -1321,6 +1210,15 @@ var PendingAutosaves = class {
|
|
|
1321
1210
|
addBuilt(name, record) {
|
|
1322
1211
|
this.#built.set(name, [...this.#built.get(name) ?? [], record]);
|
|
1323
1212
|
}
|
|
1213
|
+
/** Takes `records` out of those built through the association (`delete`, `destroy`). */
|
|
1214
|
+
removeBuilt(name, records) {
|
|
1215
|
+
const kept = this.built(name).filter((record) => !records.includes(record));
|
|
1216
|
+
this.#built.set(name, kept);
|
|
1217
|
+
}
|
|
1218
|
+
/** A hasOne's one record to save with this record, replacing any before it. */
|
|
1219
|
+
setBuilt(name, record) {
|
|
1220
|
+
this.#built.set(name, [record]);
|
|
1221
|
+
}
|
|
1324
1222
|
/** The records built through the association, in the order they were built. */
|
|
1325
1223
|
built(name) {
|
|
1326
1224
|
return this.#built.get(name) ?? [];
|
|
@@ -1338,6 +1236,10 @@ var PendingAutosaves = class {
|
|
|
1338
1236
|
allBelongsTo() {
|
|
1339
1237
|
return [...this.#belongsTo];
|
|
1340
1238
|
}
|
|
1239
|
+
/** Whether there are none: saving the record saves no other record with it. */
|
|
1240
|
+
isEmpty() {
|
|
1241
|
+
return [...this.#built.values()].every((records) => records.length === 0) && this.#belongsTo.size === 0;
|
|
1242
|
+
}
|
|
1341
1243
|
/** Forgets what was built through the association or set on it (`reloadAssociation`). */
|
|
1342
1244
|
clear(name) {
|
|
1343
1245
|
this.#built.delete(name);
|
|
@@ -1349,8 +1251,7 @@ var PendingAutosaves = class {
|
|
|
1349
1251
|
this.#belongsTo.clear();
|
|
1350
1252
|
}
|
|
1351
1253
|
};
|
|
1352
|
-
|
|
1353
|
-
//#region src/record-state.ts
|
|
1254
|
+
// src/record-state.ts
|
|
1354
1255
|
/** @internal The hidden slot where a Record keeps its `RecordState`. */
|
|
1355
1256
|
const state = Symbol("state");
|
|
1356
1257
|
/** Each record's link to its database (its `RecordState`), for pinning it to one (#93). */
|
|
@@ -1383,6 +1284,12 @@ var RecordState = class {
|
|
|
1383
1284
|
associations = new LoadedAssociations((attribute) => this.#values[attribute]);
|
|
1384
1285
|
/** The new records saving it also saves, built through or pointed at by its associations. */
|
|
1385
1286
|
autosaves = new PendingAutosaves();
|
|
1287
|
+
/** Destroyed when its owner is saved through an `autosave: true` association (#37). */
|
|
1288
|
+
isMarkedForDestruction = false;
|
|
1289
|
+
/** Whether its last save created it, as Rails' `previously_new_record?` (#351). */
|
|
1290
|
+
isPreviouslyNew = false;
|
|
1291
|
+
/** The contexts it's being validated in, while it is (#51). */
|
|
1292
|
+
validationContexts = [];
|
|
1386
1293
|
constructor(model) {
|
|
1387
1294
|
this.#model = model;
|
|
1388
1295
|
const read = (name) => Object.hasOwn(this.#values, name) ? this.#values[name] : null;
|
|
@@ -1438,7 +1345,7 @@ var RecordState = class {
|
|
|
1438
1345
|
/** A persisted record needs its primary key to be found by; one from `distinct()` has none. */
|
|
1439
1346
|
requireKey(action) {
|
|
1440
1347
|
const { name, primaryKey } = this.#model;
|
|
1441
|
-
if (this.#lifecycle === "persisted" && !this.#
|
|
1348
|
+
if (this.#lifecycle === "persisted" && !this.#isInSnapshot(primaryKey)) throw new MissingAttribute(`${name} record has no primary key loaded (it came from select(...).distinct()); it can't ${action}`);
|
|
1442
1349
|
}
|
|
1443
1350
|
/** An attribute's value; `MissingAttribute` if it wasn't loaded (left out of `select`). */
|
|
1444
1351
|
read(name) {
|
|
@@ -1483,10 +1390,14 @@ var RecordState = class {
|
|
|
1483
1390
|
}
|
|
1484
1391
|
this.assign(attributes);
|
|
1485
1392
|
}
|
|
1486
|
-
/**
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1393
|
+
/**
|
|
1394
|
+
* Points this record at `value` through `association`'s foreign key, keeping it loaded for its
|
|
1395
|
+
* key attributes (a polymorphic belongsTo's type is written before, by its `set`; #60).
|
|
1396
|
+
*/
|
|
1397
|
+
pointAt(association, key, value) {
|
|
1398
|
+
const { name, ownerAttribute, keyAttributes } = association;
|
|
1399
|
+
this.writeKey(ownerAttribute, key, name);
|
|
1400
|
+
this.associations.set(name, keyAttributes, value);
|
|
1490
1401
|
}
|
|
1491
1402
|
/** Forgets an association: what's loaded and its autosaves (`reloadAssociation`). */
|
|
1492
1403
|
resetAssociation(name) {
|
|
@@ -1513,20 +1424,24 @@ var RecordState = class {
|
|
|
1513
1424
|
attributes() {
|
|
1514
1425
|
return { ...this.#values };
|
|
1515
1426
|
}
|
|
1516
|
-
/**
|
|
1427
|
+
/**
|
|
1428
|
+
* A new record's assigned attributes that differ from their initial values (a declared default
|
|
1429
|
+
* or generated id, else null), as Rails' changes run from defaults (#41); or a persisted
|
|
1430
|
+
* one's that differ from the Snapshot. Both compare stored forms.
|
|
1431
|
+
*/
|
|
1517
1432
|
changedNames() {
|
|
1518
|
-
if (this.#lifecycle === "new") return [...this.#assigned];
|
|
1519
|
-
return Object.keys(this.#values).filter((name) => !this.#
|
|
1433
|
+
if (this.#lifecycle === "new") return [...this.#assigned].filter((name) => !isSameCell(this.#storedForm(name), this.#initialOf(name)));
|
|
1434
|
+
return Object.keys(this.#values).filter((name) => !this.#isInSnapshot(name) || !isSameCell(this.#snapshotOf(name), this.#storedForm(name)));
|
|
1520
1435
|
}
|
|
1521
1436
|
/** `{ attribute: [before, after] }`; both are copies, never the record's own objects. */
|
|
1522
1437
|
changes() {
|
|
1523
1438
|
const changes = {};
|
|
1524
|
-
for (const name of this.changedNames()) changes[name] = [this.#
|
|
1439
|
+
for (const name of this.changedNames()) changes[name] = [this.#valueBefore(name), this.#copyOf(name)];
|
|
1525
1440
|
return changes;
|
|
1526
1441
|
}
|
|
1527
1442
|
/** `changes()`, with `undefined` before an attribute the record never loaded (a partial record's). */
|
|
1528
1443
|
changesSinceLoad() {
|
|
1529
|
-
return Object.fromEntries(Object.entries(this.changes()).map(([name, [before, after]]) => [name, [this.#
|
|
1444
|
+
return Object.fromEntries(Object.entries(this.changes()).map(([name, [before, after]]) => [name, [this.#isInSnapshot(name) ? before : void 0, after]]));
|
|
1530
1445
|
}
|
|
1531
1446
|
/** The changes the last successful save wrote (copies). */
|
|
1532
1447
|
savedChanges() {
|
|
@@ -1538,9 +1453,7 @@ var RecordState = class {
|
|
|
1538
1453
|
*/
|
|
1539
1454
|
valueInDatabase(name) {
|
|
1540
1455
|
this.read(name);
|
|
1541
|
-
|
|
1542
|
-
if (this.#inSnapshot(name)) return this.#snapshotValue(name);
|
|
1543
|
-
return this.#initialValues.has(name) ? attribute.read(this.#initialValues.get(name)) : null;
|
|
1456
|
+
return this.#valueBefore(name);
|
|
1544
1457
|
}
|
|
1545
1458
|
/**
|
|
1546
1459
|
* Whether the attribute has an unsaved change, optionally `from` and `to` given values
|
|
@@ -1549,13 +1462,13 @@ var RecordState = class {
|
|
|
1549
1462
|
isAttributeChanged(name, options = {}) {
|
|
1550
1463
|
this.read(name);
|
|
1551
1464
|
if (!this.changedNames().includes(name)) return false;
|
|
1552
|
-
return this.#
|
|
1465
|
+
return this.#isMatching(name, this.valueInDatabase(name), this.#values[name], options);
|
|
1553
1466
|
}
|
|
1554
1467
|
/** Whether the last save changed the attribute, optionally `from` and `to` given values. */
|
|
1555
1468
|
hasSavedChangeTo(name, options = {}) {
|
|
1556
1469
|
this.read(name);
|
|
1557
1470
|
const change = this.#savedChanges[name];
|
|
1558
|
-
return change !== void 0 && this.#
|
|
1471
|
+
return change !== void 0 && this.#isMatching(name, change[0], change[1], options);
|
|
1559
1472
|
}
|
|
1560
1473
|
/** Puts unsaved changes back: to the Snapshot, or to a new record's initial values (or null). */
|
|
1561
1474
|
restore(names = this.changedNames()) {
|
|
@@ -1563,7 +1476,7 @@ var RecordState = class {
|
|
|
1563
1476
|
for (const name of names) {
|
|
1564
1477
|
const attribute = this.#attribute(name);
|
|
1565
1478
|
if (this.#lifecycle !== "new") {
|
|
1566
|
-
if (this.#
|
|
1479
|
+
if (this.#isInSnapshot(name)) this.#values[name] = this.#snapshotValue(name);
|
|
1567
1480
|
} else if (this.#initialValues.has(name)) this.#values[name] = attribute.read(this.#initialValues.get(name));
|
|
1568
1481
|
else {
|
|
1569
1482
|
this.#values[name] = null;
|
|
@@ -1571,8 +1484,8 @@ var RecordState = class {
|
|
|
1571
1484
|
}
|
|
1572
1485
|
}
|
|
1573
1486
|
}
|
|
1574
|
-
#
|
|
1575
|
-
const same = (a, b) => this.#attribute(name).
|
|
1487
|
+
#isMatching(name, before, after, options) {
|
|
1488
|
+
const same = (a, b) => this.#attribute(name).isSame(a, b);
|
|
1576
1489
|
return (!("from" in options) || same(options.from, before)) && (!("to" in options) || same(options.to, after));
|
|
1577
1490
|
}
|
|
1578
1491
|
/** The attributes an insert writes: the assigned ones, so column defaults apply to the rest. */
|
|
@@ -1591,13 +1504,23 @@ var RecordState = class {
|
|
|
1591
1504
|
get storedKeyValue() {
|
|
1592
1505
|
return this.#attribute(this.#model.primaryKey).read(this.storedKey);
|
|
1593
1506
|
}
|
|
1594
|
-
/**
|
|
1507
|
+
/**
|
|
1508
|
+
* After an insert: load what D1 stored. `savedChanges` is the changes the insert wrote, and
|
|
1509
|
+
* what the write or the database filled in (a generated key, timestamps, a column default),
|
|
1510
|
+
* each from its value before: a declared default the record kept isn't one (#41).
|
|
1511
|
+
*/
|
|
1595
1512
|
commitInsert(row) {
|
|
1513
|
+
const written = new Set(this.changedNames());
|
|
1514
|
+
const before = new Map(Object.keys(this.#values).map((name) => [name, {
|
|
1515
|
+
stored: this.#storedForm(name),
|
|
1516
|
+
value: this.#valueBefore(name)
|
|
1517
|
+
}]));
|
|
1596
1518
|
if (row === void 0) {
|
|
1597
1519
|
this.#settle();
|
|
1598
1520
|
this.#markSaved();
|
|
1599
1521
|
} else this.loadRow(row);
|
|
1600
|
-
this.#savedChanges = Object.fromEntries(
|
|
1522
|
+
this.#savedChanges = Object.fromEntries([...before].filter(([name, { stored }]) => written.has(name) || !isSameCell(this.#storedForm(name), stored)).map(([name, { value }]) => [name, [value, this.#copyOf(name)]]));
|
|
1523
|
+
this.isPreviouslyNew = true;
|
|
1601
1524
|
}
|
|
1602
1525
|
/**
|
|
1603
1526
|
* After an update: apply values the write added (timestamps), then record the save. Every
|
|
@@ -1610,13 +1533,38 @@ var RecordState = class {
|
|
|
1610
1533
|
this.#settle();
|
|
1611
1534
|
this.#savedChanges = this.changes();
|
|
1612
1535
|
this.#markSaved();
|
|
1536
|
+
this.isPreviouslyNew = false;
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* After a write straight to the row (`updateColumns`, #351): these attributes hold what was
|
|
1540
|
+
* stored, or what `row` returned for them, and have no unsaved change. The rest, and
|
|
1541
|
+
* `savedChanges`, are as they were.
|
|
1542
|
+
*/
|
|
1543
|
+
commitColumns(names, row = {}) {
|
|
1544
|
+
for (const name of names) {
|
|
1545
|
+
const { column } = this.#definition(name);
|
|
1546
|
+
const attribute = this.#attribute(name);
|
|
1547
|
+
this.#values[name] = column in row ? attribute.read(row[column]) : this.#copyOf(name);
|
|
1548
|
+
this.#snapshot.set(name, this.#storedForm(name));
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* After a touch (#50): as `commitColumns`, and `savedChanges` holds only the touched
|
|
1553
|
+
* attributes' changes, as Rails' `touch` applies them. The record's other changes stay unsaved.
|
|
1554
|
+
*/
|
|
1555
|
+
commitTouch(names) {
|
|
1556
|
+
const changes = this.changes();
|
|
1557
|
+
this.commitColumns(names);
|
|
1558
|
+
this.#savedChanges = Object.fromEntries(names.filter((name) => Object.hasOwn(changes, name)).map((name) => [name, changes[name]]));
|
|
1613
1559
|
}
|
|
1614
1560
|
/** A save with nothing to write: nothing changes but `savedChanges`. */
|
|
1615
1561
|
commitClean() {
|
|
1616
1562
|
this.#savedChanges = {};
|
|
1563
|
+
this.isPreviouslyNew = false;
|
|
1617
1564
|
}
|
|
1618
1565
|
markDestroyed() {
|
|
1619
1566
|
this.#lifecycle = "destroyed";
|
|
1567
|
+
this.isPreviouslyNew = false;
|
|
1620
1568
|
}
|
|
1621
1569
|
/** A destroyed record is a read-only snapshot. (A keyless record may change in memory.) */
|
|
1622
1570
|
#requireNotDestroyed(action) {
|
|
@@ -1633,6 +1581,15 @@ var RecordState = class {
|
|
|
1633
1581
|
#attribute(name) {
|
|
1634
1582
|
return attributeFor(this.#model, name);
|
|
1635
1583
|
}
|
|
1584
|
+
/** A new record's initial value as stored: its declared default or generated id, else null. */
|
|
1585
|
+
#initialOf(name) {
|
|
1586
|
+
return this.#initialValues.has(name) ? this.#initialValues.get(name) : this.#attribute(name).write(null);
|
|
1587
|
+
}
|
|
1588
|
+
/** The value before the unsaved change: as last loaded or saved, or a new record's initial one. */
|
|
1589
|
+
#valueBefore(name) {
|
|
1590
|
+
if (this.#isInSnapshot(name)) return this.#snapshotValue(name);
|
|
1591
|
+
return this.#attribute(name).read(this.#initialOf(name));
|
|
1592
|
+
}
|
|
1636
1593
|
/** An attribute's current value in its stored form, for comparing with the Snapshot. */
|
|
1637
1594
|
#storedForm(name) {
|
|
1638
1595
|
return this.#attribute(name).write(this.#values[name]);
|
|
@@ -1658,18 +1615,18 @@ var RecordState = class {
|
|
|
1658
1615
|
this.#snapshotRow = row;
|
|
1659
1616
|
const names = Object.keys(this.#values);
|
|
1660
1617
|
if (names.length !== loadedCount) {
|
|
1661
|
-
for (const name of names) if (!this.#
|
|
1618
|
+
for (const name of names) if (!this.#isInRow(name)) this.#snapshot.set(name, this.#storedForm(name));
|
|
1662
1619
|
}
|
|
1663
1620
|
this.#lifecycle = "persisted";
|
|
1664
1621
|
this.#assigned.clear();
|
|
1665
1622
|
}
|
|
1666
1623
|
/** Whether the Snapshot has `name`: it was loaded or saved. */
|
|
1667
|
-
#
|
|
1668
|
-
return this.#snapshot.has(name) || this.#
|
|
1624
|
+
#isInSnapshot(name) {
|
|
1625
|
+
return this.#snapshot.has(name) || this.#isInRow(name);
|
|
1669
1626
|
}
|
|
1670
1627
|
/** `name`'s Snapshot entry, its stored form, made from the loaded row's cell on first use. */
|
|
1671
1628
|
#snapshotOf(name) {
|
|
1672
|
-
if (this.#snapshot.has(name) || !this.#
|
|
1629
|
+
if (this.#snapshot.has(name) || !this.#isInRow(name)) return this.#snapshot.get(name);
|
|
1673
1630
|
const attribute = this.#attribute(name);
|
|
1674
1631
|
const stored = attribute.write(attribute.read(this.#snapshotRow[this.#definition(name).column]));
|
|
1675
1632
|
this.#snapshot.set(name, stored);
|
|
@@ -1680,12 +1637,241 @@ var RecordState = class {
|
|
|
1680
1637
|
return this.#attribute(name).read(this.#snapshotOf(name));
|
|
1681
1638
|
}
|
|
1682
1639
|
/** Whether the row the Snapshot was loaded from has a cell for `name`. */
|
|
1683
|
-
#
|
|
1640
|
+
#isInRow(name) {
|
|
1684
1641
|
return this.#snapshotRow !== void 0 && this.#definition(name).column in this.#snapshotRow;
|
|
1685
1642
|
}
|
|
1686
1643
|
};
|
|
1687
|
-
|
|
1688
|
-
|
|
1644
|
+
// src/enum-methods.ts
|
|
1645
|
+
/** Each name of every enum attribute, with the methods it gives. */
|
|
1646
|
+
function enumNames(definitions) {
|
|
1647
|
+
return [...definitions].flatMap(([attribute, definition]) => {
|
|
1648
|
+
if (definition.enum === void 0) return [];
|
|
1649
|
+
const before = affix(attribute, definition.prefix);
|
|
1650
|
+
const after = affix(attribute, definition.suffix);
|
|
1651
|
+
return enumEntries(definition.enum).map(([name]) => {
|
|
1652
|
+
const stem = `${before}${methodPart(name)}${after}`;
|
|
1653
|
+
const records = [
|
|
1654
|
+
`is${stem}`,
|
|
1655
|
+
`saveAs${stem}`,
|
|
1656
|
+
`saveAs${stem}OrThrow`
|
|
1657
|
+
];
|
|
1658
|
+
const scopes = [uncapitalized(stem), `not${stem}`];
|
|
1659
|
+
return {
|
|
1660
|
+
attribute,
|
|
1661
|
+
name,
|
|
1662
|
+
records: definition.instanceMethods === false ? [] : records,
|
|
1663
|
+
scopes: definition.scopes === false ? [] : scopes
|
|
1664
|
+
};
|
|
1665
|
+
});
|
|
1666
|
+
});
|
|
1667
|
+
}
|
|
1668
|
+
function affix(attribute, option) {
|
|
1669
|
+
if (option === true) return methodPart(attribute);
|
|
1670
|
+
return typeof option === "string" ? methodPart(option) : "";
|
|
1671
|
+
}
|
|
1672
|
+
/** The scopes the enums of `definitions` give a Model, as `EnumStatics` types them. */
|
|
1673
|
+
function enumScopeNames(definitions) {
|
|
1674
|
+
return enumNames(definitions).flatMap(({ scopes }) => scopes);
|
|
1675
|
+
}
|
|
1676
|
+
/** How a word reads inside a method's name, as `MethodPart` types it. */
|
|
1677
|
+
function methodPart(word) {
|
|
1678
|
+
const [head = "", ...rest] = word.split("_");
|
|
1679
|
+
return capitalized(head + rest.map(capitalized).join(""));
|
|
1680
|
+
}
|
|
1681
|
+
const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
|
|
1682
|
+
const uncapitalized = (text) => text.charAt(0).toLowerCase() + text.slice(1);
|
|
1683
|
+
/**
|
|
1684
|
+
* Defines each enum attribute's methods on `prototype`: `isPublished()` is `status === "published"`,
|
|
1685
|
+
* and `saveAsPublished()` is `update({ status: "published" })`, so it saves the record's other
|
|
1686
|
+
* changes too, as Rails' `published!` does.
|
|
1687
|
+
*/
|
|
1688
|
+
function defineEnumMethods(prototype, definitions) {
|
|
1689
|
+
for (const { attribute, name, records } of enumNames(definitions)) {
|
|
1690
|
+
const [predicate, setter, throwingSetter] = records;
|
|
1691
|
+
if (predicate === void 0) continue;
|
|
1692
|
+
defineMethod(prototype, predicate, function() {
|
|
1693
|
+
return this[attribute] === name;
|
|
1694
|
+
});
|
|
1695
|
+
defineMethod(prototype, setter, function() {
|
|
1696
|
+
return this.update({ [attribute]: name });
|
|
1697
|
+
});
|
|
1698
|
+
defineMethod(prototype, throwingSetter, function() {
|
|
1699
|
+
return this.updateOrThrow({ [attribute]: name });
|
|
1700
|
+
});
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
/**
|
|
1704
|
+
* Defines each enum attribute's scopes on `model`, as `this.scope(…)` statics: `published()` is
|
|
1705
|
+
* `where({ status: "published" })`, and `notPublished()` is `whereNot(…)`, as Rails' are.
|
|
1706
|
+
*/
|
|
1707
|
+
function defineEnumStatics(model, definitions) {
|
|
1708
|
+
const declaring = model;
|
|
1709
|
+
for (const { attribute, name, scopes } of enumNames(definitions)) {
|
|
1710
|
+
const [only, without] = scopes;
|
|
1711
|
+
if (only === void 0) continue;
|
|
1712
|
+
const onlyScope = declaring.scope((q) => q.where({ [attribute]: name }));
|
|
1713
|
+
const withoutScope = declaring.scope((q) => q.whereNot({ [attribute]: name }));
|
|
1714
|
+
enumScopes.add(onlyScope);
|
|
1715
|
+
enumScopes.add(withoutScope);
|
|
1716
|
+
defineMethod(model, only, onlyScope, { named: false });
|
|
1717
|
+
defineMethod(model, without, withoutScope, { named: false });
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
/** Puts `method` on `target` as `name`, writable as a declared method is, and names it unless told not to. */
|
|
1721
|
+
function defineMethod(target, name, method, { named = true } = {}) {
|
|
1722
|
+
if (Object.hasOwn(target, name)) return;
|
|
1723
|
+
if (named) Object.defineProperty(method, "name", { value: name });
|
|
1724
|
+
Object.defineProperty(target, name, {
|
|
1725
|
+
value: method,
|
|
1726
|
+
writable: true,
|
|
1727
|
+
configurable: true
|
|
1728
|
+
});
|
|
1729
|
+
}
|
|
1730
|
+
/** The scope statics `defineEnumStatics` made, so a static a Model declares itself is told apart. */
|
|
1731
|
+
const enumScopes = /* @__PURE__ */ new WeakSet();
|
|
1732
|
+
/**
|
|
1733
|
+
* Why an enum's method names can't be as they are, or undefined: two enums give one name, or one
|
|
1734
|
+
* takes the name of a record method, an attribute, a Relation method, a Model static, or a static
|
|
1735
|
+
* the Model declares itself. Rails refuses the same when an enum is declared.
|
|
1736
|
+
*/
|
|
1737
|
+
function enumNameProblem(model, taken, methodsOff = /* @__PURE__ */ new Map()) {
|
|
1738
|
+
const checks = {
|
|
1739
|
+
...taken,
|
|
1740
|
+
methodsOffFix: (attribute) => methodsOff.get(attribute)
|
|
1741
|
+
};
|
|
1742
|
+
const givenBy = /* @__PURE__ */ new Map();
|
|
1743
|
+
for (const each of enumNames(model.attributeDefinitions)) {
|
|
1744
|
+
const { attribute, records, scopes } = each;
|
|
1745
|
+
for (const method of [...records, ...scopes]) {
|
|
1746
|
+
const other = givenBy.get(method);
|
|
1747
|
+
if (other !== void 0) return repeated(model.name, {
|
|
1748
|
+
first: other,
|
|
1749
|
+
second: attribute,
|
|
1750
|
+
method
|
|
1751
|
+
}, checks);
|
|
1752
|
+
givenBy.set(method, attribute);
|
|
1753
|
+
}
|
|
1754
|
+
const problem = declarableProblem(model, each, [...records, ...scopes], checks) ?? recordProblem(model, attribute, records, checks) ?? staticProblem(model, attribute, scopes, checks);
|
|
1755
|
+
if (problem !== void 0) return problem;
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
/**
|
|
1759
|
+
* A method name an enum's name gives that TypeScript can't declare (#340): one that isn't an
|
|
1760
|
+
* identifier (`isIn-progress`), or a scope that's a reserved word (`new`), which the generated
|
|
1761
|
+
* schema couldn't declare as a static.
|
|
1762
|
+
*/
|
|
1763
|
+
function declarableProblem(model, { attribute, name, scopes }, methods, checks) {
|
|
1764
|
+
const fix = remedy(attribute, checks);
|
|
1765
|
+
const undeclarable = methods.find((method) => !isIdentifier(method));
|
|
1766
|
+
if (undeclarable !== void 0) {
|
|
1767
|
+
const kind = scopes.includes(undeclarable) ? "scope" : "method";
|
|
1768
|
+
const suggested = uncapitalized(methodPart(name.split(/[^\p{L}\p{N}_$]+/u).join("_")));
|
|
1769
|
+
const example = isIdentifier(suggested) ? ` ({ ${suggested}: ${JSON.stringify(name)} })` : "";
|
|
1770
|
+
return `${model.name}'s enum ${attribute} gives a ${kind} named "${undeclarable}", which isn't a name TypeScript can declare; name it with letters, digits, _ and $, and map it to the value it's stored as${example}${offFix(attribute, checks)}`;
|
|
1771
|
+
}
|
|
1772
|
+
const reserved = methods.find((method) => reservedWords.has(method));
|
|
1773
|
+
return reserved === void 0 ? void 0 : `${model.name}'s enum ${attribute} gives a scope named "${reserved}", which is a reserved word; ${fix}`;
|
|
1774
|
+
}
|
|
1775
|
+
/** Two of an enum's names, or two enums, giving one method name. */
|
|
1776
|
+
function repeated(model, { first, second, method }, checks) {
|
|
1777
|
+
if (first !== second) return `${model}'s enums ${first} and ${second} both give a method named "${method}"; give one a prefix or a suffix${[first, second].map((attribute) => namedOffFix(attribute, checks)).join("")}`;
|
|
1778
|
+
const off = offFix(second, checks);
|
|
1779
|
+
return `${model}'s enum ${first} gives "${method}" for two of its names; ${off === "" ? "rename one" : "map one to a name of your own"}${off}`;
|
|
1780
|
+
}
|
|
1781
|
+
/** `offFix`, naming the enum: for a message about two of them. */
|
|
1782
|
+
function namedOffFix(attribute, checks) {
|
|
1783
|
+
const fix = checks.methodsOffFix(attribute);
|
|
1784
|
+
return fix === void 0 ? "" : `, or leave ${attribute}'s methods off (remove ${fix})`;
|
|
1785
|
+
}
|
|
1786
|
+
/** How to fix an enum whose method name is taken: an affix, or for the database's, its methods off. */
|
|
1787
|
+
const remedy = (attribute, checks) => `give ${attribute} a prefix or a suffix${offFix(attribute, checks)}`;
|
|
1788
|
+
/** For an enum whose names the database gave (#64): leaving its methods off, as they start. */
|
|
1789
|
+
function offFix(attribute, checks) {
|
|
1790
|
+
const fix = checks.methodsOffFix(attribute);
|
|
1791
|
+
return fix === void 0 ? "" : `, or leave its methods off (remove ${fix})`;
|
|
1792
|
+
}
|
|
1793
|
+
function recordProblem(model, attribute, methods, checks) {
|
|
1794
|
+
for (const method of methods) {
|
|
1795
|
+
const what = model.attributeDefinitions.has(method) ? "an attribute" : checks.isRecordName(method) ? "a record method" : void 0;
|
|
1796
|
+
if (what !== void 0) return `${model.name}'s enum ${attribute} gives a method named "${method}", which is the name of ${what}; ${remedy(attribute, checks)}`;
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
function staticProblem(model, attribute, scopes, checks) {
|
|
1800
|
+
for (const scope of scopes) {
|
|
1801
|
+
const what = scope in Function.prototype ? "a Function method" : checks.isReservedStatic(scope) ? "a Relation method or a Model static" : void 0;
|
|
1802
|
+
if (what !== void 0) return `${model.name}'s enum ${attribute} gives a scope named "${scope}", which is the name of ${what}; ${remedy(attribute, checks)}`;
|
|
1803
|
+
const declared = checks.staticOf(scope);
|
|
1804
|
+
const isEnumScope = typeof declared?.value === "function" && enumScopes.has(declared.value);
|
|
1805
|
+
if (declared !== void 0 && !isEnumScope) return `${model.name} declares "${scope}", which is also the name of a scope its enum ${attribute} gives; rename it, or ${remedy(attribute, checks)}`;
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
// src/enum-switch.ts
|
|
1809
|
+
/** Takes an override's `enum: true` or `false` out of it, so its other changes are checked as any override's. */
|
|
1810
|
+
function takeEnumSwitch(override) {
|
|
1811
|
+
if (typeof override !== "object" || override === null) return { change: override };
|
|
1812
|
+
if (!("enum" in override) || typeof override.enum !== "boolean") return { change: override };
|
|
1813
|
+
const { enum: useDatabaseEnum, ...change } = override;
|
|
1814
|
+
return {
|
|
1815
|
+
useDatabaseEnum,
|
|
1816
|
+
change
|
|
1817
|
+
};
|
|
1818
|
+
}
|
|
1819
|
+
/**
|
|
1820
|
+
* A generated spec as an override's switch leaves it: `enum: true` lifts the `scopes: false` and
|
|
1821
|
+
* `instanceMethods: false` the schema wrote, so an enum's defaults apply, and the override's own
|
|
1822
|
+
* switches, applied after, win; so does an override's own list, which replaces the names.
|
|
1823
|
+
* `enum: false` drops the enum and its keys. Either switch is an `InvalidModel` on a column
|
|
1824
|
+
* without a generated enum.
|
|
1825
|
+
*/
|
|
1826
|
+
function generatedEnumBase(where, spec, { useDatabaseEnum, change }) {
|
|
1827
|
+
if (useDatabaseEnum === void 0) return hasOwnNames(change) ? withMethodsOn(spec) : spec;
|
|
1828
|
+
if (spec.enum === void 0) throw new InvalidModel(nothingToSwitch(where, useDatabaseEnum));
|
|
1829
|
+
return useDatabaseEnum ? withMethodsOn(spec) : withoutEnum(spec);
|
|
1830
|
+
}
|
|
1831
|
+
/** Whether an override gives an enum's names itself: a list or a mapping, not `undefined`. */
|
|
1832
|
+
function hasOwnNames(change) {
|
|
1833
|
+
return "enum" in change && change.enum !== void 0;
|
|
1834
|
+
}
|
|
1835
|
+
/** A spec without the switches a generated enum's methods are off by, so an enum's defaults apply. */
|
|
1836
|
+
function withMethodsOn(spec) {
|
|
1837
|
+
const { scopes: _scopes, instanceMethods: _instanceMethods, ...lifted } = spec;
|
|
1838
|
+
return lifted;
|
|
1839
|
+
}
|
|
1840
|
+
/** Why a switch has nothing to act on, and what to write instead of `enum: true`. */
|
|
1841
|
+
function nothingToSwitch(where, useDatabaseEnum) {
|
|
1842
|
+
return useDatabaseEnum ? `${where} has no enum from the database to turn on; list its names instead (enum: ["…", …])` : `${where} has no enum from the database to turn off`;
|
|
1843
|
+
}
|
|
1844
|
+
/** The method switches an override turns on, as written: `enum: true`, or `scopes: true`, … */
|
|
1845
|
+
const methodSwitches = [
|
|
1846
|
+
"enum",
|
|
1847
|
+
"scopes",
|
|
1848
|
+
"instanceMethods"
|
|
1849
|
+
];
|
|
1850
|
+
/** An override as an object of keys, whatever was written: `{}` for a type name, `false` or none. */
|
|
1851
|
+
function overrideKeys(override) {
|
|
1852
|
+
return typeof override === "object" && override !== null ? override : {};
|
|
1853
|
+
}
|
|
1854
|
+
/**
|
|
1855
|
+
* What to remove from an attribute's override to leave its database enum's methods off again
|
|
1856
|
+
* (`enum: true`), or undefined: no enum from the database, its methods off, or a list of its own.
|
|
1857
|
+
*/
|
|
1858
|
+
function methodsOffFix(spec, definition, override) {
|
|
1859
|
+
if (!(spec !== void 0 && specObjectOf(spec).enum !== void 0) || definition.enum === void 0 || typeof override["enum"] === "object") return;
|
|
1860
|
+
const turnedOn = methodSwitches.filter((key) => override[key] === true);
|
|
1861
|
+
return turnedOn.length === 0 ? void 0 : turnedOn.map((key) => `${key}: true`).join(" and ");
|
|
1862
|
+
}
|
|
1863
|
+
/** For each enum whose names the database gave, with its methods on, `methodsOffFix`'s answer (#64). */
|
|
1864
|
+
function methodsOffFixes(model) {
|
|
1865
|
+
const table = model.schema?.tables[model.table]?.attributes ?? {};
|
|
1866
|
+
const overrides = overrideKeys(model.attributes);
|
|
1867
|
+
const fixes = /* @__PURE__ */ new Map();
|
|
1868
|
+
for (const [attribute, definition] of model.attributeDefinitions) {
|
|
1869
|
+
const fix = methodsOffFix(table[attribute], definition, overrideKeys(overrides[attribute]));
|
|
1870
|
+
if (fix !== void 0) fixes.set(attribute, fix);
|
|
1871
|
+
}
|
|
1872
|
+
return fixes;
|
|
1873
|
+
}
|
|
1874
|
+
// src/generated-model.ts
|
|
1689
1875
|
const noAttributes = /* @__PURE__ */ new Map();
|
|
1690
1876
|
/**
|
|
1691
1877
|
* What each generated Model settled on when it was first used, by class (a subclass shares its
|
|
@@ -1736,19 +1922,23 @@ function rejectUngenerated(name, table, schema) {
|
|
|
1736
1922
|
if (generatedTable === void 0) throw new InvalidModel(`${name} isn't in the generated schema; run active-record schema`);
|
|
1737
1923
|
if (generatedTable !== table) throw new InvalidModel(`${name}'s table is ${table}, but the generated schema has ${generatedTable}; run active-record schema`);
|
|
1738
1924
|
}
|
|
1739
|
-
/**
|
|
1925
|
+
/**
|
|
1926
|
+
* Finds a generated Model's table in its schema, and its attributes after its overrides. The
|
|
1927
|
+
* schema lists it by its `modelName`, which its table is inferred from too.
|
|
1928
|
+
*/
|
|
1740
1929
|
function find(owner, schema) {
|
|
1741
|
-
const
|
|
1742
|
-
|
|
1930
|
+
const name = modelNameOf(owner);
|
|
1931
|
+
const table = Object.hasOwn(owner, "table") ? owner.table : tableize(name);
|
|
1932
|
+
rejectUngenerated(name, table, schema);
|
|
1743
1933
|
const tableSchema = Object.hasOwn(schema.tables, table) ? schema.tables[table] : void 0;
|
|
1744
1934
|
if (tableSchema === void 0) throw new InvalidModel(`${owner.name}'s table, ${table}, isn't in the generated schema`);
|
|
1745
|
-
const { specs,
|
|
1935
|
+
const { specs, isIgnoringColumns } = specsFor(owner.name, tableSchema, owner.attributes ?? {});
|
|
1746
1936
|
const definitions = new Map(Object.entries(specs).map(([name, spec]) => [name, define(name, spec)]));
|
|
1747
1937
|
return {
|
|
1748
1938
|
table,
|
|
1749
1939
|
primaryKey: Object.hasOwn(owner, "primaryKey") ? owner.primaryKey : tableSchema.primaryKey,
|
|
1750
1940
|
definitions,
|
|
1751
|
-
|
|
1941
|
+
isIgnoringColumns
|
|
1752
1942
|
};
|
|
1753
1943
|
}
|
|
1754
1944
|
/**
|
|
@@ -1774,8 +1964,10 @@ function settleGenerated(model) {
|
|
|
1774
1964
|
let found = settled.get(owner);
|
|
1775
1965
|
if (found === void 0) {
|
|
1776
1966
|
found = find(owner, place.schema);
|
|
1777
|
-
bindTable(owner, found.table, {
|
|
1967
|
+
bindTable(owner, found.table, { isIgnoringColumns: found.isIgnoringColumns });
|
|
1778
1968
|
defineAttributeAccessors(owner.prototype, found.definitions.keys());
|
|
1969
|
+
defineEnumMethods(owner.prototype, found.definitions);
|
|
1970
|
+
defineEnumStatics(owner, found.definitions);
|
|
1779
1971
|
settled.set(owner, found);
|
|
1780
1972
|
}
|
|
1781
1973
|
settled.set(model, found);
|
|
@@ -1784,7 +1976,7 @@ function settleGenerated(model) {
|
|
|
1784
1976
|
* Whether a class's attributes are fixed: a hand-declared Model's are when it's defined, and a
|
|
1785
1977
|
* generated Model's when it's first used. A base class has none, which is fixed too.
|
|
1786
1978
|
*/
|
|
1787
|
-
function
|
|
1979
|
+
function hasSettledAttributes(model) {
|
|
1788
1980
|
return settled.has(model) || tableOwnerOf(model) === void 0;
|
|
1789
1981
|
}
|
|
1790
1982
|
/** Whether a class is a generated Model: built on a base holding a generated schema. */
|
|
@@ -1819,16 +2011,22 @@ function defineGeneratedStatics(root) {
|
|
|
1819
2011
|
*/
|
|
1820
2012
|
function checked(where, attribute, override) {
|
|
1821
2013
|
if (override === false) return false;
|
|
1822
|
-
if (isAttributeType(override)) return { type: override };
|
|
1823
|
-
|
|
1824
|
-
|
|
2014
|
+
if (isAttributeType(override) || isCustomType(override)) return { change: { type: override } };
|
|
2015
|
+
const { useDatabaseEnum, change } = takeEnumSwitch(override);
|
|
2016
|
+
if (!isSpecOverride(change)) throw new InvalidModel(`${where}.${attribute}: an override is a type name, { ${overridableKeyNames} }, or false`);
|
|
2017
|
+
return {
|
|
2018
|
+
useDatabaseEnum,
|
|
2019
|
+
change
|
|
2020
|
+
};
|
|
1825
2021
|
}
|
|
1826
2022
|
/**
|
|
1827
2023
|
* A generated spec with an override applied, refused if it leaves a spec a type can't have (#99,
|
|
1828
2024
|
* #73). The merged spec's type isn't known statically, so it's checked here, as a Model's is.
|
|
1829
2025
|
*/
|
|
1830
|
-
function checkedOverride(where, spec,
|
|
1831
|
-
const
|
|
2026
|
+
function checkedOverride(where, spec, override) {
|
|
2027
|
+
const base = generatedEnumBase(where, specObjectOf(spec), override);
|
|
2028
|
+
const { change } = override;
|
|
2029
|
+
const changed = applyOverride(base, change);
|
|
1832
2030
|
const problem = specProblem(where, changed);
|
|
1833
2031
|
if (problem !== void 0) throw new InvalidModel(problem);
|
|
1834
2032
|
return changed;
|
|
@@ -1850,8 +2048,7 @@ function specsFor(name, table, overrides) {
|
|
|
1850
2048
|
}
|
|
1851
2049
|
return {
|
|
1852
2050
|
specs,
|
|
1853
|
-
|
|
2051
|
+
isIgnoringColumns: [...changes.values()].includes(false)
|
|
1854
2052
|
};
|
|
1855
2053
|
}
|
|
1856
|
-
|
|
1857
|
-
export { CallbackAbort as $, requireDefined as A, shownKey as B, castInherited as C, attributesForColumn as D, attributeOf as E, zonelessDateTime as F, modelClassName as G, explainMissingTable as H, Filtered as I, tableize as J, rejectAbstract as K, boundValue as L, castValue as M, uncastable as N, define as O, writeUntypedValue as P, AssociationNotLoaded as Q, defaultFilterAttributes as R, attributeFor as S, storedRows as T, ignoresColumns as U, shownValue$1 as V, inferTableNames as W, AbortAfterPersistence as X, ancestors as Y, ActiveRecordError as Z, attributesNamedInMessages as _, UnknownAttribute as _t, isGenerated as a, InvalidModel as at, declared as b, RecordState as c, NoDatabase as ct, Errors as d, RecordInvalid as dt, CheckViolation as et, addFailure as f, RecordNotDestroyed as ft, printed as g, UnknownAssociation as gt, inspectCustom as h, RecordNotUnique as ht, isBase as i, InvalidForeignKey as it, specProblem as j, initialValues as k, linksOf as l, NotNullViolation as lt, FilteredMark as m, RecordNotSaved as mt, defineAttributeAccessors as n, DeleteRestriction as nt, schemaAdapter as o, IrreversibleOrder as ot, clearErrors as p, RecordNotFound as pt, requireTableName as q, defineGeneratedStatics as r, IncompatibleRelation as rt, settleGenerated as s, MissingAttribute as st, attributesSettled as t, ConstraintViolation as tt, state as u, RecordDestroyed as ut, humanAttributeName as v, abort as vt, noMatch as w, seal as x, declare as y, isFiltered as z };
|
|
2054
|
+
export { modelNameOf as $, attributeFor as A, specProblem as B, styled as C, declared as D, declare as E, attributesForColumn as F, filteredValues as G, Filtered as H, define as I, shownValue$1 as J, isFiltered as K, initialValues as L, noMatch as M, withArticle as N, declaredByClass as O, attributeOf as P, isIgnoringColumns as Q, requireDefined as R, printed as S, humanAttributeName as T, boundValue as U, FILTERED as V, defaultFilterAttributes as W, explainMissingTable as X, defineModelName as Y, inferTableNames as Z, addFailure as _, isGenerated as a, tableize as at, FilteredMark as b, methodsOffFixes as c, enumNameProblem as d, ownValueSetter as et, enumScopeNames as f, Errors as g, state as h, isBase as i, tableOwnerModelName as it, castInherited as j, seal as k, defineEnumMethods as l, linksOf as m, defineGeneratedStatics as n, requireModelName as nt, schemaAdapter as o, ancestors as ot, RecordState as p, shownKey as q, hasSettledAttributes as r, requireTableName as rt, settleGenerated as s, staticBelow as st, defineAttributeAccessors as t, rejectAbstract as tt, defineEnumStatics as u, clearErrors as v, attributesNamedInMessages as w, inspectCustom as x, fullMessageOf as y, defineType as z };
|