@forestfuture/active-record 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/config-schema.json +6 -2
  2. package/dist/adapter.d.mts +3 -3
  3. package/dist/adapter.mjs +5 -4
  4. package/dist/batch-ReqVoCfa.mjs +9559 -0
  5. package/dist/cli.d.mts +55 -33
  6. package/dist/cli.mjs +4 -4
  7. package/dist/command.mjs +530 -271
  8. package/dist/d1.d.mts +2 -10
  9. package/dist/d1.mjs +0 -0
  10. package/dist/epoch-storage-CDlQZcBB.mjs +988 -0
  11. package/dist/{for-adapters-t3-LukJQ.d.mts → for-adapters-B0xMP6Dq.d.mts} +8 -6
  12. package/dist/{for-adapters-D_Iu0gS_.mjs → for-adapters-CfXMGeOu.mjs} +3 -5
  13. package/dist/{for-adapters-Ch6CoHD4.mjs → for-adapters-DhNV1mWf.mjs} +46 -10
  14. package/dist/{generated-model-Cnt0Ot9q.mjs → generated-model-g5oWsDKE.mjs} +728 -540
  15. package/dist/index-BATasvJa.d.mts +241 -0
  16. package/dist/index.d.mts +4 -3
  17. package/dist/index.mjs +5 -4
  18. package/dist/metadata-CzntpYzC.d.mts +182 -0
  19. package/dist/{plugin-Cyoej7qV.mjs → plugin-wOSILvSB.mjs} +211 -112
  20. package/dist/{plugin-XOHYndhP.mjs → plugin-x5-d3TSN.mjs} +148 -52
  21. package/dist/postgresql.d.mts +1 -9
  22. package/dist/postgresql.mjs +42 -26
  23. package/dist/src-D56_3odT.mjs +46 -0
  24. package/dist/{storage-override-CpbkdIqE.mjs → storage-override-n4w1cS_M.mjs} +61 -28
  25. package/dist/validations-DHDVV8hB.d.mts +1996 -0
  26. package/llms-full.txt +2354 -363
  27. package/package.json +1 -1
  28. package/skills/active-record/SKILL.md +22 -14
  29. package/dist/adapter-AGKp6wfO.d.mts +0 -1326
  30. package/dist/batch-BS_WseLf.mjs +0 -4255
  31. package/dist/epoch-storage-o2aoOH7H.mjs +0 -112
  32. package/dist/index-CyCJuM96.d.mts +0 -149
  33. package/dist/src-la_KkjCS.mjs +0 -1
@@ -1,146 +1,23 @@
1
- import { a as underscore, n as pluralize, t as epochStorages } from "./epoch-storage-o2aoOH7H.mjs";
2
- //#region src/errors.ts
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 listedNames, Z as UnknownAttribute, _ as enumEntries, a as castKey, c as readValue, d as writeValue, g as reservedWords, h as isIdentifier, i as castCondition, l as uncastable, m as isSameCell, n as digitsProblem, o as castValue, s as isInvalidDate, t as epochStorages, v as enumProblem, x as isEnumValues, z as NoDatabase } from "./epoch-storage-CDlQZcBB.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
- //#endregion
143
- //#region src/table-names.ts
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 `ignoresColumns`, remembered since the compiler asks on every query.
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 name of the class that extends `base` directly, the one a table is named after, as in
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 className(base, model) {
59
+ function modelNameBelow(base, model) {
164
60
  let current = model;
165
61
  while (current !== base && Object.getPrototypeOf(current) !== base) current = Object.getPrototypeOf(current);
166
- const { name } = current;
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 = className(base, this);
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 class name a Model's table name was inferred from, or undefined when it's declared. */
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) ? className(owner, model) : void 0;
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, { ignoresColumns }) {
111
+ function bindTable(owner, table, { isIgnoringColumns }) {
217
112
  owner.table = table;
218
113
  boundTables.set(owner, {
219
114
  table,
220
- ignoresColumns
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 ignoresColumns(model) {
132
+ function isIgnoringColumns(model) {
238
133
  let answer = ignoring.get(model);
239
134
  if (answer === void 0) {
240
- answer = boundTableOf(model)?.ignoresColumns ?? false;
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 have a table name: its own, or one inferred from its class name. */
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 the class name`);
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,311 +169,198 @@ 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 class name ${source}; create it, set static table, or keep class names if your bundler renames them)`, { cause: error });
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 class name a Model's names are inferred from, its foreign keys': the class whose table it
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 modelClassName(model) {
178
+ function tableOwnerModelName(model) {
279
179
  const base = ancestors(model).find((each) => bases.has(each));
280
- if (base !== void 0) return className(base, model);
281
- return (boundTableOf(model)?.owner ?? model).name;
282
- }
283
- //#endregion
284
- //#region src/filtering.ts
285
- /** What a listener sees in place of a filtered attribute's value (#83). */
286
- const FILTERED = "[FILTERED]";
287
- /**
288
- * Rails' default `filter_parameters` for a new app: an attribute whose snake_case name holds
289
- * one of these, in any case, is filtered (`passwordDigest`, `apiKey`, `resetToken`, `email`).
290
- */
291
- const defaultFilterAttributes = [
292
- "passw",
293
- "email",
294
- "secret",
295
- "token",
296
- "_key",
297
- "crypt",
298
- "salt",
299
- "certificate",
300
- "otp",
301
- "ssn",
302
- "cvv",
303
- "cvc"
304
- ];
305
- /**
306
- * Whether `attribute`'s values are hidden from listeners: its snake_case name holds a string
307
- * entry (in any case), or a RegExp entry matches the attribute or its snake_case name.
308
- */
309
- function isFiltered(model, attribute) {
310
- 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);
312
- }
313
- /** A bound value D1 gets as `value`, and listeners see as `shown`. */
314
- var Filtered = class {
315
- value;
316
- shown;
317
- constructor(value, shown = FILTERED) {
318
- this.value = value;
319
- this.shown = shown;
320
- }
321
- };
322
- /** A primary key as an error shows it: "[FILTERED]" when the key is a filtered attribute. */
323
- function shownKey(model, key) {
324
- return isFiltered(model, model.primaryKey) ? FILTERED : String(key);
325
- }
326
- /** The value D1 binds. */
327
- function boundValue(param) {
328
- return param instanceof Filtered ? param.value : param;
329
- }
330
- /** The value listeners see. */
331
- function shownValue$1(param) {
332
- return param instanceof Filtered ? param.shown : param;
333
- }
334
- //#endregion
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);
180
+ if (base !== void 0) return modelNameBelow(base, model);
181
+ return modelNameOf(boundTableOf(model)?.owner ?? model);
182
+ }
183
+ // src/enum-methods.ts
184
+ /** Each name of every enum attribute, with the methods it gives. */
185
+ function enumNames(definitions) {
186
+ return [...definitions].flatMap(([attribute, definition]) => {
187
+ if (definition.enum === void 0) return [];
188
+ const before = affix(attribute, definition.prefix);
189
+ const after = affix(attribute, definition.suffix);
190
+ return enumEntries(definition.enum).map(([name]) => {
191
+ const stem = `${before}${methodPart(name)}${after}`;
192
+ const records = [
193
+ `is${stem}`,
194
+ `saveAs${stem}`,
195
+ `saveAs${stem}OrThrow`
196
+ ];
197
+ const scopes = [uncapitalized(stem), `not${stem}`];
198
+ return {
199
+ attribute,
200
+ name,
201
+ records: definition.instanceMethods === false ? [] : records,
202
+ scopes: definition.scopes === false ? [] : scopes
203
+ };
204
+ });
205
+ });
401
206
  }
402
- function writeValue(attribute, value) {
403
- return value === null || value === void 0 ? null : converters[keyOf(attribute)].write(value);
207
+ function affix(attribute, option) {
208
+ if (option === true) return methodPart(attribute);
209
+ return typeof option === "string" ? methodPart(option) : "";
404
210
  }
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;
211
+ /** The scopes the enums of `definitions` give a Model, as `EnumStatics` types them. */
212
+ function enumScopeNames(definitions) {
213
+ return enumNames(definitions).flatMap(({ scopes }) => scopes);
431
214
  }
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
- }
215
+ /** How a word reads inside a method's name, as `MethodPart` types it. */
216
+ function methodPart(word) {
217
+ const [head = "", ...rest] = word.split("_");
218
+ return capitalized(head + rest.map(capitalized).join(""));
445
219
  }
220
+ const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
221
+ const uncapitalized = (text) => text.charAt(0).toLowerCase() + text.slice(1);
446
222
  /**
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.
223
+ * Defines each enum attribute's methods on `prototype`: `isPublished()` is `status === "published"`,
224
+ * and `saveAsPublished()` is `update({ status: "published" })`, so it saves the record's other
225
+ * changes too, as Rails' `published!` does.
450
226
  */
451
- function readJson(value) {
452
- if (typeof value !== "string") return value;
453
- try {
454
- return JSON.parse(value);
455
- } catch {
456
- return uncastable;
227
+ function defineEnumMethods(prototype, definitions) {
228
+ for (const { attribute, name, records } of enumNames(definitions)) {
229
+ const [predicate, setter, throwingSetter] = records;
230
+ if (predicate === void 0) continue;
231
+ defineMethod(prototype, predicate, function() {
232
+ return this[attribute] === name;
233
+ });
234
+ defineMethod(prototype, setter, function() {
235
+ return this.update({ [attribute]: name });
236
+ });
237
+ defineMethod(prototype, throwingSetter, function() {
238
+ return this.updateOrThrow({ [attribute]: name });
239
+ });
457
240
  }
458
241
  }
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
242
  /**
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).
243
+ * Defines each enum attribute's scopes on `model`, as `this.scope(…)` statics: `published()` is
244
+ * `where({ status: "published" })`, and `notPublished()` is `whereNot(…)`, as Rails' are.
512
245
  */
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);
246
+ function defineEnumStatics(model, definitions) {
247
+ const declaring = model;
248
+ for (const { attribute, name, scopes } of enumNames(definitions)) {
249
+ const [only, without] = scopes;
250
+ if (only === void 0) continue;
251
+ const onlyScope = declaring.scope((q) => q.where({ [attribute]: name }));
252
+ const withoutScope = declaring.scope((q) => q.whereNot({ [attribute]: name }));
253
+ enumScopes.add(onlyScope);
254
+ enumScopes.add(withoutScope);
255
+ defineMethod(model, only, onlyScope, { named: false });
256
+ defineMethod(model, without, withoutScope, { named: false });
257
+ }
258
+ }
259
+ /** Puts `method` on `target` as `name`, writable as a declared method is, and names it unless told not to. */
260
+ function defineMethod(target, name, method, { named = true } = {}) {
261
+ if (Object.hasOwn(target, name)) return;
262
+ if (named) Object.defineProperty(method, "name", { value: name });
263
+ Object.defineProperty(target, name, {
264
+ value: method,
265
+ writable: true,
266
+ configurable: true
267
+ });
519
268
  }
269
+ /** The scope statics `defineEnumStatics` made, so a static a Model declares itself is told apart. */
270
+ const enumScopes = /* @__PURE__ */ new WeakSet();
520
271
  /**
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).
272
+ * Why an enum's method names can't be as they are, or undefined: two enums give one name, or one
273
+ * takes the name of a record method, an attribute, a Relation method, a Model static, or a static
274
+ * the Model declares itself. Rails refuses the same when an enum is declared.
526
275
  */
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;
276
+ function enumNameProblem(model, taken, methodsOff = /* @__PURE__ */ new Map()) {
277
+ const checks = {
278
+ ...taken,
279
+ methodsOffFix: (attribute) => methodsOff.get(attribute)
280
+ };
281
+ const givenBy = /* @__PURE__ */ new Map();
282
+ for (const each of enumNames(model.attributeDefinitions)) {
283
+ const { attribute, records, scopes } = each;
284
+ for (const method of [...records, ...scopes]) {
285
+ const other = givenBy.get(method);
286
+ if (other !== void 0) return repeated(model.name, {
287
+ first: other,
288
+ second: attribute,
289
+ method
290
+ }, checks);
291
+ givenBy.set(method, attribute);
292
+ }
293
+ const problem = declarableProblem(model, each, [...records, ...scopes], checks) ?? recordProblem(model, attribute, records, checks) ?? staticProblem(model, attribute, scopes, checks);
294
+ if (problem !== void 0) return problem;
295
+ }
532
296
  }
533
297
  /**
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`).
298
+ * A method name an enum's name gives that TypeScript can't declare (#340): one that isn't an
299
+ * identifier (`isIn-progress`), or a scope that's a reserved word (`new`), which the generated
300
+ * schema couldn't declare as a static.
536
301
  */
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
302
+ function declarableProblem(model, { attribute, name, scopes }, methods, checks) {
303
+ const fix = remedy(attribute, checks);
304
+ const undeclarable = methods.find((method) => !isIdentifier(method));
305
+ if (undeclarable !== void 0) {
306
+ const kind = scopes.includes(undeclarable) ? "scope" : "method";
307
+ const suggested = uncapitalized(methodPart(name.split(/[^\p{L}\p{N}_$]+/u).join("_")));
308
+ const example = isIdentifier(suggested) ? ` ({ ${suggested}: ${JSON.stringify(name)} })` : "";
309
+ 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)}`;
310
+ }
311
+ const reserved = methods.find((method) => reservedWords.has(method));
312
+ return reserved === void 0 ? void 0 : `${model.name}'s enum ${attribute} gives a scope named "${reserved}", which is a reserved word; ${fix}`;
313
+ }
314
+ /** Two of an enum's names, or two enums, giving one method name. */
315
+ function repeated(model, { first, second, method }, checks) {
316
+ 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("")}`;
317
+ const off = offFix(second, checks);
318
+ return `${model}'s enum ${first} gives "${method}" for two of its names; ${off === "" ? "rename one" : "map one to a name of your own"}${off}`;
319
+ }
320
+ /** `offFix`, naming the enum: for a message about two of them. */
321
+ function namedOffFix(attribute, checks) {
322
+ const fix = checks.methodsOffFix(attribute);
323
+ return fix === void 0 ? "" : `, or leave ${attribute}'s methods off (remove ${fix})`;
324
+ }
325
+ /** How to fix an enum whose method name is taken: an affix, or for the database's, its methods off. */
326
+ const remedy = (attribute, checks) => `give ${attribute} a prefix or a suffix${offFix(attribute, checks)}`;
327
+ /** For an enum whose names the database gave (#64): leaving its methods off, as they start. */
328
+ function offFix(attribute, checks) {
329
+ const fix = checks.methodsOffFix(attribute);
330
+ return fix === void 0 ? "" : `, or leave its methods off (remove ${fix})`;
331
+ }
332
+ function recordProblem(model, attribute, methods, checks) {
333
+ for (const method of methods) {
334
+ const what = model.attributeDefinitions.has(method) ? "an attribute" : checks.isRecordName(method) ? "a record method" : void 0;
335
+ if (what !== void 0) return `${model.name}'s enum ${attribute} gives a method named "${method}", which is the name of ${what}; ${remedy(attribute, checks)}`;
336
+ }
337
+ }
338
+ function staticProblem(model, attribute, scopes, checks) {
339
+ for (const scope of scopes) {
340
+ const what = scope in Function.prototype ? "a Function method" : checks.isReservedStatic(scope) ? "a Relation method or a Model static" : void 0;
341
+ if (what !== void 0) return `${model.name}'s enum ${attribute} gives a scope named "${scope}", which is the name of ${what}; ${remedy(attribute, checks)}`;
342
+ const declared = checks.staticOf(scope);
343
+ const isEnumScope = typeof declared?.value === "function" && enumScopes.has(declared.value);
344
+ 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)}`;
345
+ }
346
+ }
347
+ // src/spec-keys.ts
569
348
  const attributeTypes = Object.keys({
570
349
  string: true,
571
350
  integer: true,
572
351
  real: true,
352
+ decimal: true,
573
353
  boolean: true,
574
354
  datetime: true,
575
- json: true
355
+ date: true,
356
+ time: true,
357
+ json: true,
358
+ binary: true
576
359
  });
360
+ /** The built-in types' names, as a message lists them: `"string", "integer", …`. */
361
+ const typeNameList = attributeTypes.map((name) => `"${String(name)}"`).join(", ");
362
+ /** The built-in types' names as a list to choose from: `"string", …, or "binary"`. */
363
+ const attributeTypeNames = typeNameList.replace(/, ([^,]+)$/, ", or $1");
577
364
  /** Whether `value` names an attribute type. */
578
365
  function isAttributeType(value) {
579
366
  return attributeTypes.includes(value);
@@ -584,7 +371,7 @@ function isAttributeType(value) {
584
371
  */
585
372
  const rules = {
586
373
  type: {
587
- isWellFormed: isAttributeType,
374
+ isWellFormed: (value) => isAttributeType(value) || isCustomType(value),
588
375
  copiedToDefinition: false
589
376
  },
590
377
  null: {
@@ -620,8 +407,81 @@ const rules = {
620
407
  because: "only a datetime is stored as an epoch"
621
408
  },
622
409
  onRetype: "drop"
410
+ },
411
+ precision: decimalDigits("a precision"),
412
+ scale: decimalDigits("a scale"),
413
+ enum: {
414
+ isWellFormed: isEnumValues,
415
+ describedAs: "an enum",
416
+ onlyFor: {
417
+ types: ["string", "integer"],
418
+ because: "an enum is stored as text or integers"
419
+ },
420
+ problemFor: enumProblem,
421
+ onRetype: "drop"
422
+ },
423
+ prefix: affixRule("prefix"),
424
+ suffix: affixRule("suffix"),
425
+ scopes: methodsSwitch("scopes"),
426
+ instanceMethods: methodsSwitch("instanceMethods"),
427
+ validate: {
428
+ isWellFormed: isEnumValidation,
429
+ describedAs: "validate",
430
+ wellFormedAs: "use true, or { allowNull: true }",
431
+ isGiven: isGivenUnless(false),
432
+ requires: "enum",
433
+ onRetype: "drop"
623
434
  }
624
435
  };
436
+ /** The rule for a decimal's precision or scale: a whole number of digits. */
437
+ function decimalDigits(describedAs) {
438
+ return {
439
+ isWellFormed: (value) => Number.isSafeInteger(value) && value >= 0,
440
+ describedAs,
441
+ wellFormedAs: "use a whole number of digits",
442
+ onlyFor: {
443
+ types: ["decimal"],
444
+ because: "only a decimal has digits to limit"
445
+ },
446
+ onRetype: "drop"
447
+ };
448
+ }
449
+ /** `true`, `false`, or an object holding only a boolean `allowNull`. */
450
+ function isEnumValidation(value) {
451
+ if (typeof value === "boolean") return true;
452
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
453
+ return Object.entries(value).every(([key, each]) => key === "allowNull" && (each === void 0 || typeof each === "boolean"));
454
+ }
455
+ /** The rule for a switch that leaves an enum's methods out when it's `false`. */
456
+ function methodsSwitch(key) {
457
+ return {
458
+ isWellFormed: (value) => typeof value === "boolean",
459
+ describedAs: key,
460
+ wellFormedAs: "use false to leave them out",
461
+ isGiven: isGivenUnless(true),
462
+ requires: "enum",
463
+ onRetype: "drop"
464
+ };
465
+ }
466
+ /** `isGiven` for a key whose `off` value (and `undefined`) leaves it as if it weren't given. */
467
+ function isGivenUnless(off) {
468
+ return (value) => value !== void 0 && value !== off;
469
+ }
470
+ /** The rule for a prefix or a suffix: a word around an enum's names in its methods' names. */
471
+ function affixRule(key) {
472
+ return {
473
+ isWellFormed: isAffix,
474
+ describedAs: `a ${key}`,
475
+ wellFormedAs: "use true for the attribute's name, or a word",
476
+ isGiven: isGivenUnless(false),
477
+ requires: "enum",
478
+ onRetype: "drop"
479
+ };
480
+ }
481
+ /** A prefix or suffix: `true` for the attribute's name, `false` for none, or a word. */
482
+ function isAffix(value) {
483
+ return typeof value === "boolean" || typeof value === "string" && value !== "";
484
+ }
625
485
  const entries = Object.entries(rules);
626
486
  /** For each key, the keys it conflicts with, whichever of the two declares it. */
627
487
  const conflicts = new Map(entries.map(([key]) => [key, []]));
@@ -629,6 +489,12 @@ for (const [key, { conflictsWith = [] }] of entries) for (const other of conflic
629
489
  conflicts.get(key).push(other);
630
490
  conflicts.get(other).push(key);
631
491
  }
492
+ /** An enum's keys: `enum`, and those it means nothing without (`prefix`, `scopes`, …). */
493
+ const enumKeys = new Set(entries.filter(([key, rule]) => key === "enum" || rule.requires === "enum").map(([key]) => key));
494
+ /** A spec without its enum and the keys that go with one (#64). */
495
+ function withoutEnum(spec) {
496
+ return Object.fromEntries(Object.entries(spec).filter(([key]) => !enumKeys.has(key)));
497
+ }
632
498
  /** The keys an override may hold, as a message lists them: `type, null, default, …`. */
633
499
  const overridableKeyNames = entries.filter(([, rule]) => rule.overridable !== false).map(([key]) => key).join(", ");
634
500
  /** The value of a key if it's given, else `undefined`. */
@@ -636,6 +502,10 @@ function givenValue(spec, key) {
636
502
  const value = spec[key];
637
503
  return (rules[key].isGiven ?? ((each) => each !== void 0))(value) ? value : void 0;
638
504
  }
505
+ /** How a spec's type reads in a message: `"integer"`, or `a custom type` (#20). */
506
+ function typeNamed(type) {
507
+ return isAttributeType(type) ? `"${type}"` : "a custom type";
508
+ }
639
509
  /** How a key reads in a message. */
640
510
  const readsAs = (key) => rules[key].describedAs ?? key;
641
511
  /** Whether `value` is an object holding only spec keys an override may change, each well formed or `undefined`. */
@@ -659,23 +529,40 @@ function shown$1(value) {
659
529
  return String(value);
660
530
  }
661
531
  }
532
+ /** The problem with a given key's shape, past the types, or with it given without the key it needs. */
533
+ function shapeProblem(where, spec, key) {
534
+ const { requires, isWellFormed, wellFormedAs } = rules[key];
535
+ const value = givenValue(spec, key);
536
+ if (wellFormedAs !== void 0 && !isWellFormed(value)) return `${where} has ${readsAs(key)} ${shown$1(value)}; ${wellFormedAs}`;
537
+ 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)}`;
538
+ }
662
539
  /** The problem with a given key's value, or with its attribute's type. */
663
540
  function valueProblem(where, spec, key) {
664
- const { allowedValues, onlyFor } = rules[key];
541
+ const { allowedValues, onlyFor, problemFor } = rules[key];
665
542
  const value = givenValue(spec, key);
666
543
  if (allowedValues !== void 0 && !allowedValues.includes(value)) {
667
544
  const names = allowedValues.map((each) => `"${each}"`).join(" or ");
668
545
  return `${where} has ${key} ${shown$1(value)}; use ${names}`;
669
546
  }
670
- if (onlyFor !== void 0 && !onlyFor.types.includes(spec.type)) return `${where} is "${spec.type}", so it can't have ${readsAs(key)}: ${onlyFor.because}`;
547
+ const { type } = spec;
548
+ if (onlyFor !== void 0 && !(isAttributeType(type) && onlyFor.types.includes(type))) return `${where} is ${typeNamed(type)}, so it can't have ${readsAs(key)}: ${onlyFor.because}`;
549
+ const problem = isAttributeType(type) ? problemFor?.(value, type) : void 0;
550
+ return problem === void 0 ? void 0 : `${where}${problem}`;
671
551
  }
672
552
  /** Why a spec can't be as it is, or undefined if it can. `where` names it (`User.id`). */
673
553
  function specProblem(where, spec) {
554
+ 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
555
  for (const [key] of entries) {
675
556
  if (givenValue(spec, key) === void 0) continue;
676
- const problem = conflictProblem(where, spec, key) ?? valueProblem(where, spec, key);
557
+ const problem = conflictProblem(where, spec, key) ?? shapeProblem(where, spec, key) ?? valueProblem(where, spec, key);
677
558
  if (problem !== void 0) return problem;
678
559
  }
560
+ return decimalDigitsProblem(where, spec);
561
+ }
562
+ /** A precision and scale no `NUMERIC(p, s)` can have (#398). */
563
+ function decimalDigitsProblem(where, spec) {
564
+ const problem = digitsProblem(spec);
565
+ return problem === void 0 ? void 0 : `${where} has ${problem}`;
679
566
  }
680
567
  /**
681
568
  * `base` with `override` applied. A key `override` gives replaces one it conflicts with, and a new
@@ -694,24 +581,77 @@ function applyOverride(base, override) {
694
581
  ...given
695
582
  };
696
583
  }
697
- /** The keys of `spec` that go into its attribute's definition as given: `default`, `generateId`, `storage`. */
584
+ /** The keys of `spec` that go into its attribute's definition as given: all but its type, nullability and column. */
698
585
  function copiedKeys(spec) {
699
586
  const copied = entries.filter(([key, rule]) => rule.copiedToDefinition !== false && givenValue(spec, key) !== void 0).map(([key]) => [key, spec[key]]);
700
587
  return Object.fromEntries(copied);
701
588
  }
702
- //#endregion
703
- //#region src/metadata.ts
589
+ // src/custom-types.ts
590
+ /** Every type `defineType` made, so a spec can't pass off another object as one. */
591
+ const defined = /* @__PURE__ */ new WeakSet();
592
+ /**
593
+ * Defines an attribute type, used in a spec as a type name is: `price: money`, or
594
+ * `{ type: money, null: false }`. Its values are kept as `storedAs` keeps its own, so they're
595
+ * read strictly, compared and ordered as that type's are.
596
+ */
597
+ function defineType(type) {
598
+ requireWellFormed(type);
599
+ const made = Object.freeze({
600
+ storedAs: type.storedAs,
601
+ cast: (input) => type.cast(input),
602
+ serialize: (value) => type.serialize(value),
603
+ deserialize: (stored) => type.deserialize(stored)
604
+ });
605
+ defined.add(made);
606
+ return made;
607
+ }
608
+ /** The functions a type needs, each checked when it's made. */
609
+ const functionNames = [
610
+ "cast",
611
+ "serialize",
612
+ "deserialize"
613
+ ];
614
+ /**
615
+ * Throws `TypeError` for a type that couldn't work, past the types (plain JavaScript, or a cast):
616
+ * a `storedAs` that isn't a built-in type's name, or a function it lacks.
617
+ */
618
+ function requireWellFormed(type) {
619
+ if (!isAttributeType(type.storedAs)) throw new TypeError(`defineType: storedAs ${JSON.stringify(type.storedAs)} isn't a type's name; use ${attributeTypeNames}`);
620
+ const missing = functionNames.find((name) => typeof type[name] !== "function");
621
+ if (missing !== void 0) throw new TypeError(`defineType: ${missing} isn't a function`);
622
+ }
623
+ /** Whether `value` is a type `defineType` made. */
624
+ function isCustomType(value) {
625
+ return typeof value === "object" && value !== null && defined.has(value);
626
+ }
627
+ // src/metadata.ts
628
+ /** A spec written out: a type alone (a name, or a custom type) as `{ type }`. */
629
+ function specObjectOf(spec) {
630
+ return typeof spec === "string" || isCustomType(spec) ? { type: spec } : spec;
631
+ }
704
632
  /** Resolves an attribute's spec into its type, column and default. */
705
633
  function define(name, spec) {
706
- return typeof spec === "string" ? {
634
+ if (typeof spec === "string") return {
707
635
  type: spec,
708
636
  column: underscore(name)
709
- } : {
710
- type: spec.type,
637
+ };
638
+ if (isCustomType(spec)) return {
639
+ ...resolvedType(spec),
640
+ column: underscore(name)
641
+ };
642
+ return {
643
+ ...resolvedType(spec.type),
711
644
  column: spec.column ?? underscore(name),
712
645
  ...copiedKeys(spec)
713
646
  };
714
647
  }
648
+ /** A spec's type as a definition holds it: a custom type as the type it's stored as, and itself. */
649
+ function resolvedType(type) {
650
+ return isCustomType(type) ? {
651
+ type: type.storedAs,
652
+ customType: type
653
+ } : { type };
654
+ }
715
655
  /** Looks up a declared attribute; throws `UnknownAttribute` for any other name. */
716
656
  function attributeOf(model, name) {
717
657
  const attribute = model.attributeDefinitions.get(name);
@@ -737,8 +677,62 @@ function initialValues(model, given = {}) {
737
677
  function hasInitialValue(definition) {
738
678
  return definition.generateId === true || definition.default !== void 0;
739
679
  }
740
- //#endregion
741
- //#region src/attribute.ts
680
+ // src/filtering.ts
681
+ /** What a listener sees in place of a filtered attribute's value (#83). */
682
+ const FILTERED = "[FILTERED]";
683
+ /**
684
+ * Rails' default `filter_parameters` for a new app: an attribute whose snake_case name holds
685
+ * one of these, in any case, is filtered (`passwordDigest`, `apiKey`, `resetToken`, `email`).
686
+ */
687
+ const defaultFilterAttributes = [
688
+ "passw",
689
+ "email",
690
+ "secret",
691
+ "token",
692
+ "_key",
693
+ "crypt",
694
+ "salt",
695
+ "certificate",
696
+ "otp",
697
+ "ssn",
698
+ "cvv",
699
+ "cvc"
700
+ ];
701
+ /**
702
+ * Whether `attribute`'s values are hidden from listeners: its snake_case name holds a string
703
+ * entry lowercased, or read in snake_case (`"apiKey"` as `api_key`, #397), or a RegExp entry
704
+ * matches the attribute or its snake_case name.
705
+ */
706
+ function isFiltered(model, attribute) {
707
+ const name = underscore(attribute);
708
+ return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) || name.includes(underscore(entry)) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
709
+ }
710
+ /** The values of `attributes` that `model` filters, so a message can tell not to show them. */
711
+ function filteredValues(model, attributes) {
712
+ return Object.entries(attributes).filter(([name]) => isFiltered(model, name)).map(([, value]) => value);
713
+ }
714
+ /** A bound value D1 gets as `value`, and listeners see as `shown`. */
715
+ var Filtered = class {
716
+ value;
717
+ shown;
718
+ constructor(value, shown = FILTERED) {
719
+ this.value = value;
720
+ this.shown = shown;
721
+ }
722
+ };
723
+ /** A primary key as an error shows it: "[FILTERED]" when the key is a filtered attribute. */
724
+ function shownKey(model, key) {
725
+ return isFiltered(model, model.primaryKey) ? FILTERED : String(key);
726
+ }
727
+ /** The value D1 binds. */
728
+ function boundValue(param) {
729
+ return param instanceof Filtered ? param.value : param;
730
+ }
731
+ /** The value listeners see. */
732
+ function shownValue$1(param) {
733
+ return param instanceof Filtered ? param.shown : param;
734
+ }
735
+ // src/attribute.ts
742
736
  /** What `condition()` and `conditionCell()` give for a value that can't match anything. */
743
737
  const noMatch = uncastable;
744
738
  /**
@@ -762,6 +756,10 @@ var Attribute = class {
762
756
  get isText() {
763
757
  return this.#definition.type === "string";
764
758
  }
759
+ /** Whether it's a `binary` attribute, whose cells are bytes, which JSON can't hold (#20). */
760
+ get isBinary() {
761
+ return this.#definition.type === "binary";
762
+ }
765
763
  /** Whether it's a `json` attribute, whose stored text is JSON itself. */
766
764
  get isJson() {
767
765
  return this.#definition.type === "json";
@@ -774,7 +772,14 @@ var Attribute = class {
774
772
  */
775
773
  cast(value) {
776
774
  requireDefined(this.#model, this.name, value);
777
- return this.#orRefuse(castValue(this.#definition, value), value);
775
+ const cast = this.#convertOrRefuse(value, () => castValue(this.#definition, value));
776
+ if (cast === uncastable && this.#isValidatedEnum()) return value;
777
+ return this.#orRefuse(cast, value);
778
+ }
779
+ /** Whether it's an enum declared `validate: true`, which keeps an unknown value it's given. */
780
+ #isValidatedEnum() {
781
+ const { enum: values, validate = false } = this.#definition;
782
+ return values !== void 0 && validate !== false;
778
783
  }
779
784
  /**
780
785
  * A key copied from another record or inherited from a condition: cast as a condition's, but
@@ -782,7 +787,7 @@ var Attribute = class {
782
787
  */
783
788
  key(value, association) {
784
789
  requireDefined(this.#model, this.name, value);
785
- return this.#orRefuse(castCondition(this.#definition, value), value, association);
790
+ return this.#orRefuse(castKey(this.#definition, value), value, association);
786
791
  }
787
792
  /**
788
793
  * A condition's value (`where`, `find`, a preload) as the attribute's type, or `noMatch`: a
@@ -806,6 +811,7 @@ var Attribute = class {
806
811
  try {
807
812
  stored = writeValue(this.#definition, value);
808
813
  } catch (error) {
814
+ if (this.#definition.customType !== void 0) throw this.#refusal(value, void 0, error);
809
815
  if (this.#definition.type !== "json") throw error;
810
816
  throw this.#refusal(value);
811
817
  }
@@ -822,7 +828,7 @@ var Attribute = class {
822
828
  * attribute, with the cell hidden if it's filtered, not the parser's own error (#73, #146).
823
829
  */
824
830
  read(cell) {
825
- const value = readValue(this.#definition, cell);
831
+ const value = this.#convertOrRefuse(cell, () => readValue(this.#definition, cell));
826
832
  if (value === uncastable) throw this.#refusal(cell);
827
833
  return value;
828
834
  }
@@ -830,9 +836,24 @@ var Attribute = class {
830
836
  copy(value) {
831
837
  return this.read(this.write(value));
832
838
  }
833
- /** Whether two values are the same as stored (dates by time, json by content). */
834
- same(a, b) {
835
- return writeValue(this.#definition, a) === writeValue(this.#definition, b);
839
+ /**
840
+ * Whether two values are the same as stored (dates by time, json and bytes by content). Each is
841
+ * cast as a condition's value first, so `isAttributeChanged`'s `from` and `to` compare as
842
+ * Rails' do, and one that can't be cast is the same as nothing (#20).
843
+ */
844
+ isSame(a, b) {
845
+ const [x, y] = [this.#comparable(a), this.#comparable(b)];
846
+ if (x === noMatch || y === noMatch) return false;
847
+ return isSameCell(writeValue(this.#definition, x), writeValue(this.#definition, y));
848
+ }
849
+ /**
850
+ * A value to compare, cast as a condition's: `null` stays `null`, and a validated enum's
851
+ * unknown value, which a record may hold, stays as it is (#340).
852
+ */
853
+ #comparable(value) {
854
+ if (value === null || value === void 0) return value ?? null;
855
+ const cast = this.condition(value);
856
+ return cast === noMatch && this.#isValidatedEnum() ? value : cast;
836
857
  }
837
858
  /** An assigned value, cast and written, bound hidden from `onQuery` if filtered (#83). */
838
859
  bind(params, value) {
@@ -844,29 +865,47 @@ var Attribute = class {
844
865
  * time, since `filterAttributes` is a static a Model may set after this was resolved.
845
866
  */
846
867
  bindCells(params, ...cells) {
847
- const hidden = this.#hidden();
868
+ const hidden = this.#isHidden();
848
869
  for (const cell of cells) params.push(hidden ? new Filtered(cell) : cell);
849
870
  }
850
871
  #orRefuse(cast, value, association) {
851
872
  if (cast === uncastable) throw this.#refusal(value, association);
852
873
  return cast;
853
874
  }
875
+ /**
876
+ * `convert`'s result. What a custom type's own function throws for `value` is refused as any
877
+ * value its type can't hold, with the type's error as the cause (#20).
878
+ */
879
+ #convertOrRefuse(value, convert) {
880
+ try {
881
+ return convert();
882
+ } catch (error) {
883
+ if (this.#definition.customType === void 0) throw error;
884
+ throw this.#refusal(value, void 0, error);
885
+ }
886
+ }
854
887
  /** Whether the attribute's values are hidden from listeners and errors (#83). */
855
- #hidden() {
888
+ #isHidden() {
856
889
  return isFiltered(this.#model, this.name);
857
890
  }
858
891
  /**
859
892
  * "Sample: "no" isn't a boolean for "enabled"", the value hidden for a filtered attribute. Also
860
893
  * 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).
894
+ * cell that isn't JSON (#146). A custom type's own error is its cause, unless the attribute is
895
+ * filtered: the error may show the value (#20).
862
896
  */
863
- #refusal(value, association) {
864
- const { type } = this.#definition;
865
- const noun = nouns[type] ?? type;
866
- const article = /^[aeiou]/.test(noun) ? "an" : "a";
867
- const text = this.#hidden() ? FILTERED : shown(value);
897
+ #refusal(value, association, cause) {
898
+ const hidden = this.#isHidden();
899
+ const text = hidden ? FILTERED : shown(value);
868
900
  const from = association === void 0 ? "" : `, the key of ${association}`;
869
- return /* @__PURE__ */ new TypeError(`${this.#model.name}: ${text} isn't ${article} ${noun} for "${this.name}"${from}`);
901
+ return new TypeError(`${this.#model.name}: ${text} isn't ${this.#described()} for "${this.name}"${from}`, hidden || cause === void 0 ? void 0 : { cause });
902
+ }
903
+ /** What a value of the attribute is, as a refusal says it: `a boolean`, `one of "draft", "published"`. */
904
+ #described() {
905
+ const { type, enum: values, customType } = this.#definition;
906
+ if (values !== void 0) return `one of ${listedNames(values)}`;
907
+ if (customType !== void 0) return "a valid value";
908
+ return valueNames[type] ?? withArticle(type);
870
909
  }
871
910
  };
872
911
  const resolved = /* @__PURE__ */ new WeakMap();
@@ -888,19 +927,6 @@ function attributeFor(model, name) {
888
927
  return attribute;
889
928
  }
890
929
  /**
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
930
  * The values a record built from a Relation inherits from its conditions, cast as keys are: a
905
931
  * hasMany's foreign key names its association (`link`) when it can't be cast.
906
932
  */
@@ -910,16 +936,25 @@ function castInherited(model, inherited, link) {
910
936
  return [attribute, attributeFor(model, attribute).key(value, association)];
911
937
  }));
912
938
  }
939
+ /** A word with `a` or `an` before it, as a message reads it: `an integer`, `a string`. */
940
+ function withArticle(word) {
941
+ return `${/^[aeiou]/.test(word) ? "an" : "a"} ${word}`;
942
+ }
913
943
  /** How much of a value an error shows: it came from outside, and errors are often logged. */
914
944
  const SHOWN_LENGTH = 60;
915
- /** What an attribute type is called in a refusal, where its name isn't it. */
916
- const nouns = { json: "JSON value" };
945
+ /** What a value of an attribute type is called in a refusal, where `a`/`an` and its name isn't it. */
946
+ const valueNames = {
947
+ json: "a JSON value",
948
+ binary: "binary data"
949
+ };
917
950
  /** A value as an error shows it: JSON where it has one, numbers as written, and at most 60 characters. */
918
951
  function shown(value) {
919
952
  const text = textOf(value);
920
953
  return text.length > SHOWN_LENGTH ? `${text.slice(0, SHOWN_LENGTH)}…` : text;
921
954
  }
922
955
  function textOf(value) {
956
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return `<${value.constructor.name} of ${value.byteLength} bytes>`;
957
+ if (value instanceof Blob) return `<${value.constructor.name} of ${value.size} bytes>`;
923
958
  if (typeof value === "number" || isInvalidDate(value)) return String(value);
924
959
  try {
925
960
  return JSON.stringify(value) ?? String(value);
@@ -935,8 +970,7 @@ function plainText(value) {
935
970
  return Object.prototype.toString.call(value);
936
971
  }
937
972
  }
938
- //#endregion
939
- //#region src/declarations.ts
973
+ // src/declarations.ts
940
974
  /**
941
975
  * Per-Model declarations (validations, callbacks, …), keyed by Model class. A subclass starts
942
976
  * from a copy of its parent's list, so declaring on it never changes the parent.
@@ -994,13 +1028,16 @@ function listsOf(lists, model) {
994
1028
  lists.set(model, found);
995
1029
  return found;
996
1030
  }
997
- //#endregion
998
- //#region src/error-messages.ts
1031
+ // src/error-messages.ts
999
1032
  /** @internal Rails' English messages, used where no class has its own (listed in the guide). */
1000
1033
  const builtInMessages = {
1001
1034
  blank: "can't be blank",
1035
+ present: "must be blank",
1002
1036
  invalid: "is invalid",
1037
+ required: "must exist",
1003
1038
  inclusion: "is not included in the list",
1039
+ exclusion: "is reserved",
1040
+ accepted: "must be accepted",
1004
1041
  taken: "has already been taken",
1005
1042
  tooShort: {
1006
1043
  one: "is too short (minimum is 1 character)",
@@ -1020,6 +1057,8 @@ const builtInMessages = {
1020
1057
  greaterThanOrEqualTo: "must be greater than or equal to %{count}",
1021
1058
  lessThan: "must be less than %{count}",
1022
1059
  lessThanOrEqualTo: "must be less than or equal to %{count}",
1060
+ equalTo: "must be equal to %{count}",
1061
+ otherThan: "must be other than %{count}",
1023
1062
  restrictDependentDestroy: {
1024
1063
  hasOne: "Cannot delete record because a dependent %{record} exists",
1025
1064
  hasMany: "Cannot delete record because dependent %{record} exist"
@@ -1069,7 +1108,7 @@ function messageText(template, entry) {
1069
1108
  }
1070
1109
  /** "createdAt" → "Created at" */
1071
1110
  function inWords(name) {
1072
- const words = underscore(name).replaceAll("_", " ");
1111
+ const words = underscore(name).replaceAll(/[_.]/g, " ");
1073
1112
  return words.charAt(0).toUpperCase() + words.slice(1);
1074
1113
  }
1075
1114
  /** An attribute's name as messages show it: a class's `humanAttributeNames`, or "Created at". */
@@ -1093,7 +1132,7 @@ function messageOf(source, entry) {
1093
1132
  if (text === void 0) throw missingMessage(model, entry);
1094
1133
  return text.replace(/%\{(\w+)\}/g, (placeholder, name) => {
1095
1134
  if (name === "attribute") return humanAttributeName(model, entry.attribute);
1096
- if (name === "model") return inWords(model.name);
1135
+ if (name === "model") return inWords(model.modelName);
1097
1136
  if (name === "value") return shownValue(source, entry.attribute);
1098
1137
  return String(ownValue(entry.values, name) ?? placeholder);
1099
1138
  });
@@ -1115,8 +1154,7 @@ function attributesNamedInMessages(model) {
1115
1154
  names: values.flatMap((value) => Object.keys(value))
1116
1155
  }))];
1117
1156
  }
1118
- //#endregion
1119
- //#region src/inspect-support.ts
1157
+ // src/inspect-support.ts
1120
1158
  /** Node and workerd call a value's inspector under this registered symbol. */
1121
1159
  const inspectCustom = Symbol.for("nodejs.util.inspect.custom");
1122
1160
  /** Text in the color of a special value, or plain when colors are off. */
@@ -1144,12 +1182,13 @@ function printed(label, name, body, { depth, options, inspect }) {
1144
1182
  depth
1145
1183
  })}`;
1146
1184
  }
1147
- //#endregion
1148
- //#region src/errors-collection.ts
1185
+ // src/errors-collection.ts
1149
1186
  /** @internal The library's key for emptying an errors collection. */
1150
1187
  const clearErrors = Symbol("clearErrors");
1151
1188
  /** @internal The library's key for adding a failure it found, with an optional message to use as it is. */
1152
1189
  const addFailure = Symbol("addFailure");
1190
+ /** @internal The library's key for a failure's full message, without adding it (`strict`). */
1191
+ const fullMessageOf = Symbol("fullMessageOf");
1153
1192
  /** A record's validation errors: `record.errors`. Cleared at the start of each validation run. */
1154
1193
  var Errors = class {
1155
1194
  #entries = [];
@@ -1184,11 +1223,12 @@ var Errors = class {
1184
1223
  }
1185
1224
  /** Every message with its attribute's human name first: "Email can't be blank". */
1186
1225
  fullMessages() {
1187
- return this.#entries.map((entry) => {
1188
- const message = messageOf(this.#source, entry);
1189
- if (entry.attribute === "base") return message;
1190
- return `${humanAttributeName(this.#source.model, entry.attribute)} ${message}`;
1191
- });
1226
+ return this.#entries.map((entry) => this.#fullMessage(entry));
1227
+ }
1228
+ #fullMessage(entry) {
1229
+ const message = messageOf(this.#source, entry);
1230
+ if (entry.attribute === "base") return message;
1231
+ return `${humanAttributeName(this.#source.model, entry.attribute)} ${message}`;
1192
1232
  }
1193
1233
  /** Every error as `{ attribute, type, message }`, with its `values` when it has some (copies). */
1194
1234
  toArray() {
@@ -1229,13 +1269,20 @@ var Errors = class {
1229
1269
  this.#entries.push(entry);
1230
1270
  return messageOf(this.#source, entry);
1231
1271
  }
1272
+ /** @internal A failure's full message, as `fullMessages()` would give it, without adding it. */
1273
+ [fullMessageOf](attribute, { values = {}, ...failure }) {
1274
+ return this.#fullMessage({
1275
+ attribute,
1276
+ values,
1277
+ ...failure
1278
+ });
1279
+ }
1232
1280
  /** @internal Called at the start of each validation run. */
1233
1281
  [clearErrors]() {
1234
1282
  this.#entries = [];
1235
1283
  }
1236
1284
  };
1237
- //#endregion
1238
- //#region src/loaded-associations.ts
1285
+ // src/loaded-associations.ts
1239
1286
  /**
1240
1287
  * The associations one record has loaded (preloaded, read, or set by a write): a record, an
1241
1288
  * array of records, or null. Each stays loaded while the owner's attribute still holds the key
@@ -1254,7 +1301,7 @@ var LoadedAssociations = class {
1254
1301
  /** The loaded association, if it was loaded for the key the owner holds now. */
1255
1302
  get(name) {
1256
1303
  const entry = this.#entries.get(name);
1257
- if (entry === void 0 || !Object.is(this.#key(entry.attribute), entry.key)) return void 0;
1304
+ if (entry === void 0 || !isSameKey(this.#key(entry.attribute), entry.key)) return void 0;
1258
1305
  return entry;
1259
1306
  }
1260
1307
  /**
@@ -1271,10 +1318,10 @@ var LoadedAssociations = class {
1271
1318
  }
1272
1319
  /**
1273
1320
  * 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
1321
+ * for (the attributes' values now, unless it's given): the function it returns keeps the loaded value only if nothing changed the association
1275
1322
  * meanwhile (#181).
1276
1323
  */
1277
- startLoad(name, attribute, key) {
1324
+ startLoad(name, attribute, key = this.#key(attribute)) {
1278
1325
  const generation = this.#generation(name);
1279
1326
  return (value) => {
1280
1327
  if (this.#generation(name) === generation) this.#entries.set(name, {
@@ -1295,6 +1342,7 @@ var LoadedAssociations = class {
1295
1342
  this.#allLoadsDiscarded += 1;
1296
1343
  }
1297
1344
  #key(attribute) {
1345
+ if (typeof attribute !== "string") return attribute.map((each) => this.#keyOf(each) ?? null);
1298
1346
  return this.#keyOf(attribute) ?? null;
1299
1347
  }
1300
1348
  #discardPendingLoads(name) {
@@ -1308,11 +1356,16 @@ var LoadedAssociations = class {
1308
1356
  return this.#allLoadsDiscarded + (this.#loadsDiscarded.get(name) ?? 0);
1309
1357
  }
1310
1358
  };
1311
- //#endregion
1312
- //#region src/pending-autosaves.ts
1359
+ /** Whether two keys are the same: one value, or each of a list's (#60). */
1360
+ function isSameKey(now, loaded) {
1361
+ if (!Array.isArray(now) || !Array.isArray(loaded)) return Object.is(now, loaded);
1362
+ return now.every((each, index) => Object.is(each, loaded[index]));
1363
+ }
1364
+ // src/pending-autosaves.ts
1313
1365
  /**
1314
- * The new records saving one record also saves: those built through its hasMany and hasOne
1315
- * associations, after it, and those its belongsTo associations point at, before it.
1366
+ * The records saving one record may also save: those built through its hasMany and hasOne
1367
+ * associations or pushed onto a hasMany, after it (`autosavesOf` says which), and the new ones
1368
+ * its belongsTo associations point at, before it.
1316
1369
  */
1317
1370
  var PendingAutosaves = class {
1318
1371
  #built = /* @__PURE__ */ new Map();
@@ -1321,6 +1374,15 @@ var PendingAutosaves = class {
1321
1374
  addBuilt(name, record) {
1322
1375
  this.#built.set(name, [...this.#built.get(name) ?? [], record]);
1323
1376
  }
1377
+ /** Takes `records` out of those built through the association (`delete`, `destroy`). */
1378
+ removeBuilt(name, records) {
1379
+ const kept = this.built(name).filter((record) => !records.includes(record));
1380
+ this.#built.set(name, kept);
1381
+ }
1382
+ /** A hasOne's one record to save with this record, replacing any before it. */
1383
+ setBuilt(name, record) {
1384
+ this.#built.set(name, [record]);
1385
+ }
1324
1386
  /** The records built through the association, in the order they were built. */
1325
1387
  built(name) {
1326
1388
  return this.#built.get(name) ?? [];
@@ -1338,6 +1400,10 @@ var PendingAutosaves = class {
1338
1400
  allBelongsTo() {
1339
1401
  return [...this.#belongsTo];
1340
1402
  }
1403
+ /** Whether there are none: saving the record saves no other record with it. */
1404
+ isEmpty() {
1405
+ return [...this.#built.values()].every((records) => records.length === 0) && this.#belongsTo.size === 0;
1406
+ }
1341
1407
  /** Forgets what was built through the association or set on it (`reloadAssociation`). */
1342
1408
  clear(name) {
1343
1409
  this.#built.delete(name);
@@ -1349,8 +1415,7 @@ var PendingAutosaves = class {
1349
1415
  this.#belongsTo.clear();
1350
1416
  }
1351
1417
  };
1352
- //#endregion
1353
- //#region src/record-state.ts
1418
+ // src/record-state.ts
1354
1419
  /** @internal The hidden slot where a Record keeps its `RecordState`. */
1355
1420
  const state = Symbol("state");
1356
1421
  /** Each record's link to its database (its `RecordState`), for pinning it to one (#93). */
@@ -1383,6 +1448,12 @@ var RecordState = class {
1383
1448
  associations = new LoadedAssociations((attribute) => this.#values[attribute]);
1384
1449
  /** The new records saving it also saves, built through or pointed at by its associations. */
1385
1450
  autosaves = new PendingAutosaves();
1451
+ /** Destroyed when its owner is saved through an `autosave: true` association (#37). */
1452
+ isMarkedForDestruction = false;
1453
+ /** Whether its last save created it, as Rails' `previously_new_record?` (#351). */
1454
+ isPreviouslyNew = false;
1455
+ /** The contexts it's being validated in, while it is (#51). */
1456
+ validationContexts = [];
1386
1457
  constructor(model) {
1387
1458
  this.#model = model;
1388
1459
  const read = (name) => Object.hasOwn(this.#values, name) ? this.#values[name] : null;
@@ -1438,7 +1509,7 @@ var RecordState = class {
1438
1509
  /** A persisted record needs its primary key to be found by; one from `distinct()` has none. */
1439
1510
  requireKey(action) {
1440
1511
  const { name, primaryKey } = this.#model;
1441
- if (this.#lifecycle === "persisted" && !this.#inSnapshot(primaryKey)) throw new MissingAttribute(`${name} record has no primary key loaded (it came from select(...).distinct()); it can't ${action}`);
1512
+ 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
1513
  }
1443
1514
  /** An attribute's value; `MissingAttribute` if it wasn't loaded (left out of `select`). */
1444
1515
  read(name) {
@@ -1483,10 +1554,14 @@ var RecordState = class {
1483
1554
  }
1484
1555
  this.assign(attributes);
1485
1556
  }
1486
- /** Points this record at `value` through `attribute` (a foreign key), keeping it loaded. */
1487
- pointAt(name, attribute, key, value) {
1488
- this.writeKey(attribute, key, name);
1489
- this.associations.set(name, attribute, value);
1557
+ /**
1558
+ * Points this record at `value` through `association`'s foreign key, keeping it loaded for its
1559
+ * key attributes (a polymorphic belongsTo's type is written before, by its `set`; #60).
1560
+ */
1561
+ pointAt(association, key, value) {
1562
+ const { name, ownerAttribute, keyAttributes } = association;
1563
+ this.writeKey(ownerAttribute, key, name);
1564
+ this.associations.set(name, keyAttributes, value);
1490
1565
  }
1491
1566
  /** Forgets an association: what's loaded and its autosaves (`reloadAssociation`). */
1492
1567
  resetAssociation(name) {
@@ -1513,20 +1588,24 @@ var RecordState = class {
1513
1588
  attributes() {
1514
1589
  return { ...this.#values };
1515
1590
  }
1516
- /** A new record's assigned attributes, or a persisted one's that differ from the Snapshot. */
1591
+ /**
1592
+ * A new record's assigned attributes that differ from their initial values (a declared default
1593
+ * or generated id, else null), as Rails' changes run from defaults (#41); or a persisted
1594
+ * one's that differ from the Snapshot. Both compare stored forms.
1595
+ */
1517
1596
  changedNames() {
1518
- if (this.#lifecycle === "new") return [...this.#assigned];
1519
- return Object.keys(this.#values).filter((name) => !this.#inSnapshot(name) || this.#snapshotOf(name) !== this.#storedForm(name));
1597
+ if (this.#lifecycle === "new") return [...this.#assigned].filter((name) => !isSameCell(this.#storedForm(name), this.#initialOf(name)));
1598
+ return Object.keys(this.#values).filter((name) => !this.#isInSnapshot(name) || !isSameCell(this.#snapshotOf(name), this.#storedForm(name)));
1520
1599
  }
1521
1600
  /** `{ attribute: [before, after] }`; both are copies, never the record's own objects. */
1522
1601
  changes() {
1523
1602
  const changes = {};
1524
- for (const name of this.changedNames()) changes[name] = [this.#inSnapshot(name) ? this.#snapshotValue(name) : null, this.#copyOf(name)];
1603
+ for (const name of this.changedNames()) changes[name] = [this.#valueBefore(name), this.#copyOf(name)];
1525
1604
  return changes;
1526
1605
  }
1527
1606
  /** `changes()`, with `undefined` before an attribute the record never loaded (a partial record's). */
1528
1607
  changesSinceLoad() {
1529
- return Object.fromEntries(Object.entries(this.changes()).map(([name, [before, after]]) => [name, [this.#inSnapshot(name) ? before : void 0, after]]));
1608
+ return Object.fromEntries(Object.entries(this.changes()).map(([name, [before, after]]) => [name, [this.#isInSnapshot(name) ? before : void 0, after]]));
1530
1609
  }
1531
1610
  /** The changes the last successful save wrote (copies). */
1532
1611
  savedChanges() {
@@ -1538,9 +1617,7 @@ var RecordState = class {
1538
1617
  */
1539
1618
  valueInDatabase(name) {
1540
1619
  this.read(name);
1541
- const attribute = this.#attribute(name);
1542
- if (this.#inSnapshot(name)) return this.#snapshotValue(name);
1543
- return this.#initialValues.has(name) ? attribute.read(this.#initialValues.get(name)) : null;
1620
+ return this.#valueBefore(name);
1544
1621
  }
1545
1622
  /**
1546
1623
  * Whether the attribute has an unsaved change, optionally `from` and `to` given values
@@ -1549,13 +1626,13 @@ var RecordState = class {
1549
1626
  isAttributeChanged(name, options = {}) {
1550
1627
  this.read(name);
1551
1628
  if (!this.changedNames().includes(name)) return false;
1552
- return this.#matches(name, this.valueInDatabase(name), this.#values[name], options);
1629
+ return this.#isMatching(name, this.valueInDatabase(name), this.#values[name], options);
1553
1630
  }
1554
1631
  /** Whether the last save changed the attribute, optionally `from` and `to` given values. */
1555
1632
  hasSavedChangeTo(name, options = {}) {
1556
1633
  this.read(name);
1557
1634
  const change = this.#savedChanges[name];
1558
- return change !== void 0 && this.#matches(name, change[0], change[1], options);
1635
+ return change !== void 0 && this.#isMatching(name, change[0], change[1], options);
1559
1636
  }
1560
1637
  /** Puts unsaved changes back: to the Snapshot, or to a new record's initial values (or null). */
1561
1638
  restore(names = this.changedNames()) {
@@ -1563,7 +1640,7 @@ var RecordState = class {
1563
1640
  for (const name of names) {
1564
1641
  const attribute = this.#attribute(name);
1565
1642
  if (this.#lifecycle !== "new") {
1566
- if (this.#inSnapshot(name)) this.#values[name] = this.#snapshotValue(name);
1643
+ if (this.#isInSnapshot(name)) this.#values[name] = this.#snapshotValue(name);
1567
1644
  } else if (this.#initialValues.has(name)) this.#values[name] = attribute.read(this.#initialValues.get(name));
1568
1645
  else {
1569
1646
  this.#values[name] = null;
@@ -1571,8 +1648,8 @@ var RecordState = class {
1571
1648
  }
1572
1649
  }
1573
1650
  }
1574
- #matches(name, before, after, options) {
1575
- const same = (a, b) => this.#attribute(name).same(a, b);
1651
+ #isMatching(name, before, after, options) {
1652
+ const same = (a, b) => this.#attribute(name).isSame(a, b);
1576
1653
  return (!("from" in options) || same(options.from, before)) && (!("to" in options) || same(options.to, after));
1577
1654
  }
1578
1655
  /** The attributes an insert writes: the assigned ones, so column defaults apply to the rest. */
@@ -1591,13 +1668,23 @@ var RecordState = class {
1591
1668
  get storedKeyValue() {
1592
1669
  return this.#attribute(this.#model.primaryKey).read(this.storedKey);
1593
1670
  }
1594
- /** After an insert: load what D1 stored; `savedChanges` is everything the new row holds. */
1671
+ /**
1672
+ * After an insert: load what D1 stored. `savedChanges` is the changes the insert wrote, and
1673
+ * what the write or the database filled in (a generated key, timestamps, a column default),
1674
+ * each from its value before: a declared default the record kept isn't one (#41).
1675
+ */
1595
1676
  commitInsert(row) {
1677
+ const written = new Set(this.changedNames());
1678
+ const before = new Map(Object.keys(this.#values).map((name) => [name, {
1679
+ stored: this.#storedForm(name),
1680
+ value: this.#valueBefore(name)
1681
+ }]));
1596
1682
  if (row === void 0) {
1597
1683
  this.#settle();
1598
1684
  this.#markSaved();
1599
1685
  } else this.loadRow(row);
1600
- this.#savedChanges = Object.fromEntries(Object.keys(this.#values).filter((name) => this.#values[name] !== null).map((name) => [name, [null, this.#copyOf(name)]]));
1686
+ this.#savedChanges = Object.fromEntries([...before].filter(([name, { stored }]) => written.has(name) || !isSameCell(this.#storedForm(name), stored)).map(([name, { value }]) => [name, [value, this.#copyOf(name)]]));
1687
+ this.isPreviouslyNew = true;
1601
1688
  }
1602
1689
  /**
1603
1690
  * After an update: apply values the write added (timestamps), then record the save. Every
@@ -1610,13 +1697,29 @@ var RecordState = class {
1610
1697
  this.#settle();
1611
1698
  this.#savedChanges = this.changes();
1612
1699
  this.#markSaved();
1700
+ this.isPreviouslyNew = false;
1701
+ }
1702
+ /**
1703
+ * After a write straight to the row (`updateColumns`, #351): these attributes hold what was
1704
+ * stored, or what `row` returned for them, and have no unsaved change. The rest, and
1705
+ * `savedChanges`, are as they were.
1706
+ */
1707
+ commitColumns(names, row = {}) {
1708
+ for (const name of names) {
1709
+ const { column } = this.#definition(name);
1710
+ const attribute = this.#attribute(name);
1711
+ this.#values[name] = column in row ? attribute.read(row[column]) : this.#copyOf(name);
1712
+ this.#snapshot.set(name, this.#storedForm(name));
1713
+ }
1613
1714
  }
1614
1715
  /** A save with nothing to write: nothing changes but `savedChanges`. */
1615
1716
  commitClean() {
1616
1717
  this.#savedChanges = {};
1718
+ this.isPreviouslyNew = false;
1617
1719
  }
1618
1720
  markDestroyed() {
1619
1721
  this.#lifecycle = "destroyed";
1722
+ this.isPreviouslyNew = false;
1620
1723
  }
1621
1724
  /** A destroyed record is a read-only snapshot. (A keyless record may change in memory.) */
1622
1725
  #requireNotDestroyed(action) {
@@ -1633,6 +1736,15 @@ var RecordState = class {
1633
1736
  #attribute(name) {
1634
1737
  return attributeFor(this.#model, name);
1635
1738
  }
1739
+ /** A new record's initial value as stored: its declared default or generated id, else null. */
1740
+ #initialOf(name) {
1741
+ return this.#initialValues.has(name) ? this.#initialValues.get(name) : this.#attribute(name).write(null);
1742
+ }
1743
+ /** The value before the unsaved change: as last loaded or saved, or a new record's initial one. */
1744
+ #valueBefore(name) {
1745
+ if (this.#isInSnapshot(name)) return this.#snapshotValue(name);
1746
+ return this.#attribute(name).read(this.#initialOf(name));
1747
+ }
1636
1748
  /** An attribute's current value in its stored form, for comparing with the Snapshot. */
1637
1749
  #storedForm(name) {
1638
1750
  return this.#attribute(name).write(this.#values[name]);
@@ -1658,18 +1770,18 @@ var RecordState = class {
1658
1770
  this.#snapshotRow = row;
1659
1771
  const names = Object.keys(this.#values);
1660
1772
  if (names.length !== loadedCount) {
1661
- for (const name of names) if (!this.#inRow(name)) this.#snapshot.set(name, this.#storedForm(name));
1773
+ for (const name of names) if (!this.#isInRow(name)) this.#snapshot.set(name, this.#storedForm(name));
1662
1774
  }
1663
1775
  this.#lifecycle = "persisted";
1664
1776
  this.#assigned.clear();
1665
1777
  }
1666
1778
  /** Whether the Snapshot has `name`: it was loaded or saved. */
1667
- #inSnapshot(name) {
1668
- return this.#snapshot.has(name) || this.#inRow(name);
1779
+ #isInSnapshot(name) {
1780
+ return this.#snapshot.has(name) || this.#isInRow(name);
1669
1781
  }
1670
1782
  /** `name`'s Snapshot entry, its stored form, made from the loaded row's cell on first use. */
1671
1783
  #snapshotOf(name) {
1672
- if (this.#snapshot.has(name) || !this.#inRow(name)) return this.#snapshot.get(name);
1784
+ if (this.#snapshot.has(name) || !this.#isInRow(name)) return this.#snapshot.get(name);
1673
1785
  const attribute = this.#attribute(name);
1674
1786
  const stored = attribute.write(attribute.read(this.#snapshotRow[this.#definition(name).column]));
1675
1787
  this.#snapshot.set(name, stored);
@@ -1680,12 +1792,77 @@ var RecordState = class {
1680
1792
  return this.#attribute(name).read(this.#snapshotOf(name));
1681
1793
  }
1682
1794
  /** Whether the row the Snapshot was loaded from has a cell for `name`. */
1683
- #inRow(name) {
1795
+ #isInRow(name) {
1684
1796
  return this.#snapshotRow !== void 0 && this.#definition(name).column in this.#snapshotRow;
1685
1797
  }
1686
1798
  };
1687
- //#endregion
1688
- //#region src/generated-model.ts
1799
+ // src/enum-switch.ts
1800
+ /** Takes an override's `enum: true` or `false` out of it, so its other changes are checked as any override's. */
1801
+ function takeEnumSwitch(override) {
1802
+ if (typeof override !== "object" || override === null) return { change: override };
1803
+ if (!("enum" in override) || typeof override.enum !== "boolean") return { change: override };
1804
+ const { enum: useDatabaseEnum, ...change } = override;
1805
+ return {
1806
+ useDatabaseEnum,
1807
+ change
1808
+ };
1809
+ }
1810
+ /**
1811
+ * A generated spec as an override's switch leaves it: `enum: true` lifts the `scopes: false` and
1812
+ * `instanceMethods: false` the schema wrote, so an enum's defaults apply, and the override's own
1813
+ * switches, applied after, win; so does an override's own list, which replaces the names.
1814
+ * `enum: false` drops the enum and its keys. Either switch is an `InvalidModel` on a column
1815
+ * without a generated enum.
1816
+ */
1817
+ function generatedEnumBase(where, spec, { useDatabaseEnum, change }) {
1818
+ if (useDatabaseEnum === void 0) return hasOwnNames(change) ? withMethodsOn(spec) : spec;
1819
+ if (spec.enum === void 0) throw new InvalidModel(nothingToSwitch(where, useDatabaseEnum));
1820
+ return useDatabaseEnum ? withMethodsOn(spec) : withoutEnum(spec);
1821
+ }
1822
+ /** Whether an override gives an enum's names itself: a list or a mapping, not `undefined`. */
1823
+ function hasOwnNames(change) {
1824
+ return "enum" in change && change.enum !== void 0;
1825
+ }
1826
+ /** A spec without the switches a generated enum's methods are off by, so an enum's defaults apply. */
1827
+ function withMethodsOn(spec) {
1828
+ const { scopes: _scopes, instanceMethods: _instanceMethods, ...lifted } = spec;
1829
+ return lifted;
1830
+ }
1831
+ /** Why a switch has nothing to act on, and what to write instead of `enum: true`. */
1832
+ function nothingToSwitch(where, useDatabaseEnum) {
1833
+ 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`;
1834
+ }
1835
+ /** The method switches an override turns on, as written: `enum: true`, or `scopes: true`, … */
1836
+ const methodSwitches = [
1837
+ "enum",
1838
+ "scopes",
1839
+ "instanceMethods"
1840
+ ];
1841
+ /** An override as an object of keys, whatever was written: `{}` for a type name, `false` or none. */
1842
+ function overrideKeys(override) {
1843
+ return typeof override === "object" && override !== null ? override : {};
1844
+ }
1845
+ /**
1846
+ * What to remove from an attribute's override to leave its database enum's methods off again
1847
+ * (`enum: true`), or undefined: no enum from the database, its methods off, or a list of its own.
1848
+ */
1849
+ function methodsOffFix(spec, definition, override) {
1850
+ if (!(spec !== void 0 && specObjectOf(spec).enum !== void 0) || definition.enum === void 0 || typeof override["enum"] === "object") return;
1851
+ const turnedOn = methodSwitches.filter((key) => override[key] === true);
1852
+ return turnedOn.length === 0 ? void 0 : turnedOn.map((key) => `${key}: true`).join(" and ");
1853
+ }
1854
+ /** For each enum whose names the database gave, with its methods on, `methodsOffFix`'s answer (#64). */
1855
+ function methodsOffFixes(model) {
1856
+ const table = model.schema?.tables[model.table]?.attributes ?? {};
1857
+ const overrides = overrideKeys(model.attributes);
1858
+ const fixes = /* @__PURE__ */ new Map();
1859
+ for (const [attribute, definition] of model.attributeDefinitions) {
1860
+ const fix = methodsOffFix(table[attribute], definition, overrideKeys(overrides[attribute]));
1861
+ if (fix !== void 0) fixes.set(attribute, fix);
1862
+ }
1863
+ return fixes;
1864
+ }
1865
+ // src/generated-model.ts
1689
1866
  const noAttributes = /* @__PURE__ */ new Map();
1690
1867
  /**
1691
1868
  * What each generated Model settled on when it was first used, by class (a subclass shares its
@@ -1736,19 +1913,23 @@ function rejectUngenerated(name, table, schema) {
1736
1913
  if (generatedTable === void 0) throw new InvalidModel(`${name} isn't in the generated schema; run active-record schema`);
1737
1914
  if (generatedTable !== table) throw new InvalidModel(`${name}'s table is ${table}, but the generated schema has ${generatedTable}; run active-record schema`);
1738
1915
  }
1739
- /** Finds a generated Model's table in its schema, and its attributes after its overrides. */
1916
+ /**
1917
+ * Finds a generated Model's table in its schema, and its attributes after its overrides. The
1918
+ * schema lists it by its `modelName`, which its table is inferred from too.
1919
+ */
1740
1920
  function find(owner, schema) {
1741
- const table = Object.hasOwn(owner, "table") ? owner.table : tableize(owner.name);
1742
- rejectUngenerated(owner.name, table, schema);
1921
+ const name = modelNameOf(owner);
1922
+ const table = Object.hasOwn(owner, "table") ? owner.table : tableize(name);
1923
+ rejectUngenerated(name, table, schema);
1743
1924
  const tableSchema = Object.hasOwn(schema.tables, table) ? schema.tables[table] : void 0;
1744
1925
  if (tableSchema === void 0) throw new InvalidModel(`${owner.name}'s table, ${table}, isn't in the generated schema`);
1745
- const { specs, ignoresColumns } = specsFor(owner.name, tableSchema, owner.attributes ?? {});
1926
+ const { specs, isIgnoringColumns } = specsFor(owner.name, tableSchema, owner.attributes ?? {});
1746
1927
  const definitions = new Map(Object.entries(specs).map(([name, spec]) => [name, define(name, spec)]));
1747
1928
  return {
1748
1929
  table,
1749
1930
  primaryKey: Object.hasOwn(owner, "primaryKey") ? owner.primaryKey : tableSchema.primaryKey,
1750
1931
  definitions,
1751
- ignoresColumns
1932
+ isIgnoringColumns
1752
1933
  };
1753
1934
  }
1754
1935
  /**
@@ -1774,8 +1955,10 @@ function settleGenerated(model) {
1774
1955
  let found = settled.get(owner);
1775
1956
  if (found === void 0) {
1776
1957
  found = find(owner, place.schema);
1777
- bindTable(owner, found.table, { ignoresColumns: found.ignoresColumns });
1958
+ bindTable(owner, found.table, { isIgnoringColumns: found.isIgnoringColumns });
1778
1959
  defineAttributeAccessors(owner.prototype, found.definitions.keys());
1960
+ defineEnumMethods(owner.prototype, found.definitions);
1961
+ defineEnumStatics(owner, found.definitions);
1779
1962
  settled.set(owner, found);
1780
1963
  }
1781
1964
  settled.set(model, found);
@@ -1784,7 +1967,7 @@ function settleGenerated(model) {
1784
1967
  * Whether a class's attributes are fixed: a hand-declared Model's are when it's defined, and a
1785
1968
  * generated Model's when it's first used. A base class has none, which is fixed too.
1786
1969
  */
1787
- function attributesSettled(model) {
1970
+ function hasSettledAttributes(model) {
1788
1971
  return settled.has(model) || tableOwnerOf(model) === void 0;
1789
1972
  }
1790
1973
  /** Whether a class is a generated Model: built on a base holding a generated schema. */
@@ -1819,16 +2002,22 @@ function defineGeneratedStatics(root) {
1819
2002
  */
1820
2003
  function checked(where, attribute, override) {
1821
2004
  if (override === false) return false;
1822
- if (isAttributeType(override)) return { type: override };
1823
- if (!isSpecOverride(override)) throw new InvalidModel(`${where}.${attribute}: an override is a type name, { ${overridableKeyNames} }, or false`);
1824
- return override;
2005
+ if (isAttributeType(override) || isCustomType(override)) return { change: { type: override } };
2006
+ const { useDatabaseEnum, change } = takeEnumSwitch(override);
2007
+ if (!isSpecOverride(change)) throw new InvalidModel(`${where}.${attribute}: an override is a type name, { ${overridableKeyNames} }, or false`);
2008
+ return {
2009
+ useDatabaseEnum,
2010
+ change
2011
+ };
1825
2012
  }
1826
2013
  /**
1827
2014
  * A generated spec with an override applied, refused if it leaves a spec a type can't have (#99,
1828
2015
  * #73). The merged spec's type isn't known statically, so it's checked here, as a Model's is.
1829
2016
  */
1830
- function checkedOverride(where, spec, change) {
1831
- const changed = applyOverride(typeof spec === "string" ? { type: spec } : spec, change);
2017
+ function checkedOverride(where, spec, override) {
2018
+ const base = generatedEnumBase(where, specObjectOf(spec), override);
2019
+ const { change } = override;
2020
+ const changed = applyOverride(base, change);
1832
2021
  const problem = specProblem(where, changed);
1833
2022
  if (problem !== void 0) throw new InvalidModel(problem);
1834
2023
  return changed;
@@ -1850,8 +2039,7 @@ function specsFor(name, table, overrides) {
1850
2039
  }
1851
2040
  return {
1852
2041
  specs,
1853
- ignoresColumns: [...changes.values()].includes(false)
2042
+ isIgnoringColumns: [...changes.values()].includes(false)
1854
2043
  };
1855
2044
  }
1856
- //#endregion
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 };
2045
+ export { modelNameOf as $, FILTERED as A, define as B, declared as C, castInherited as D, attributeFor as E, isFiltered as F, defineEnumMethods as G, requireDefined as H, shownKey as I, enumScopeNames as J, defineEnumStatics as K, shownValue$1 as L, boundValue as M, defaultFilterAttributes as N, noMatch as O, filteredValues as P, isIgnoringColumns as Q, attributeOf as R, declare as S, seal as T, defineType as U, initialValues as V, specProblem as W, explainMissingTable as X, defineModelName as Y, inferTableNames as Z, inspectCustom as _, isGenerated as a, tableize as at, attributesNamedInMessages as b, methodsOffFixes as c, state as d, ownValueSetter as et, Errors as f, FilteredMark as g, fullMessageOf as h, isBase as i, tableOwnerModelName as it, Filtered as j, withArticle as k, RecordState as l, clearErrors as m, defineGeneratedStatics as n, requireModelName as nt, schemaAdapter as o, ancestors as ot, addFailure as p, enumNameProblem as q, hasSettledAttributes as r, requireTableName as rt, settleGenerated as s, staticBelow as st, defineAttributeAccessors as t, rejectAbstract as tt, linksOf as u, printed as v, declaredByClass as w, humanAttributeName as x, styled as y, attributesForColumn as z };