@forestfuture/active-record 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { C as pluralize, E as underscore, H as RecordDestroyed, I as InvalidModel, R as MissingAttribute, S as isSameCell, Z as UnknownAttribute, b as listedNames, c as castValue, d as uncastable, g as enumProblem, h as enumEntries, i as digitsProblem, l as isInvalidDate, n as reservedWords, o as castCondition, p as writeValue, r as epochStorages, s as castKey, t as isIdentifier, u as readValue, y as isEnumValues, z as NoDatabase } from "./identifiers-Dh5DFACX.mjs";
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-C7186hd1.mjs";
2
2
  // src/ancestors.ts
3
3
  /** A class and every class (and object) it extends, nearest first. */
4
4
  function ancestors(model) {
@@ -180,60 +180,227 @@ function tableOwnerModelName(model) {
180
180
  if (base !== void 0) return modelNameBelow(base, model);
181
181
  return modelNameOf(boundTableOf(model)?.owner ?? model);
182
182
  }
183
- // src/filtering.ts
184
- /** What a listener sees in place of a filtered attribute's value (#83). */
185
- const FILTERED = "[FILTERED]";
183
+ // src/declarations.ts
186
184
  /**
187
- * Rails' default `filter_parameters` for a new app: an attribute whose snake_case name holds
188
- * one of these, in any case, is filtered (`passwordDigest`, `apiKey`, `resetToken`, `email`).
185
+ * Per-Model declarations (validations, callbacks, …), keyed by Model class. A subclass starts
186
+ * from a copy of its parent's list, so declaring on it never changes the parent.
187
+ *
188
+ * Module-level, but not request state (ADR-0003): declarations are made once, when a Model
189
+ * class is defined, and only read afterwards.
189
190
  */
190
- const defaultFilterAttributes = [
191
- "passw",
192
- "email",
193
- "secret",
194
- "token",
195
- "_key",
196
- "crypt",
197
- "salt",
198
- "certificate",
199
- "otp",
200
- "ssn",
201
- "cvv",
202
- "cvc"
203
- ];
191
+ const registry = /* @__PURE__ */ new WeakMap();
192
+ /** The declarations each class made itself, without its parent's, for reading class by class. */
193
+ const ownRegistry = /* @__PURE__ */ new WeakMap();
194
+ /** Models that have been used; their declarations can no longer change. */
195
+ const sealed = /* @__PURE__ */ new WeakSet();
204
196
  /**
205
- * Whether `attribute`'s values are hidden from listeners: its snake_case name holds a string
206
- * entry lowercased, or read in snake_case (`"apiKey"` as `api_key`, #397), or a RegExp entry
207
- * matches the attribute or its snake_case name.
197
+ * Called on a Model's first use. From then on, declaring on it throws: declarations belong in
198
+ * the class's `static {}` block, never in request code, where they'd leak into every request.
208
199
  */
209
- function isFiltered(model, attribute) {
210
- const name = underscore(attribute);
211
- return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) || name.includes(underscore(entry)) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
200
+ function seal(model) {
201
+ sealed.add(model);
212
202
  }
213
- /** The values of `attributes` that `model` filters, so a message can tell not to show them. */
214
- function filteredValues(model, attributes) {
215
- return Object.entries(attributes).filter(([name]) => isFiltered(model, name)).map(([, value]) => value);
203
+ /** Whether a Model has been used, so its declarations, and its ancestors', can no longer change. */
204
+ function isSealed(model) {
205
+ return sealed.has(model);
216
206
  }
217
- /** A bound value D1 gets as `value`, and listeners see as `shown`. */
218
- var Filtered = class {
219
- value;
220
- shown;
221
- constructor(value, shown = FILTERED) {
222
- this.value = value;
223
- this.shown = shown;
207
+ /** The declarations of `kind` for `model`: its own, or else its nearest ancestor's. */
208
+ function declared(model, kind) {
209
+ for (const current of ancestors(model)) {
210
+ const list = registry.get(current)?.get(kind);
211
+ if (list !== void 0) return list;
224
212
  }
225
- };
226
- /** A primary key as an error shows it: "[FILTERED]" when the key is a filtered attribute. */
227
- function shownKey(model, key) {
228
- return isFiltered(model, model.primaryKey) ? FILTERED : String(key);
213
+ return [];
229
214
  }
230
- /** The value D1 binds. */
231
- function boundValue(param) {
232
- return param instanceof Filtered ? param.value : param;
215
+ /** The declarations of `kind` that `model` and each class it extends made themselves, nearest first. */
216
+ function declaredByClass(model, kind) {
217
+ return ancestors(model).flatMap((from) => {
218
+ const values = ownRegistry.get(from)?.get(kind);
219
+ return values === void 0 ? [] : [{
220
+ from,
221
+ values
222
+ }];
223
+ });
233
224
  }
234
- /** The value listeners see. */
235
- function shownValue$1(param) {
236
- return param instanceof Filtered ? param.shown : param;
225
+ /** Adds a declaration of `kind` to `model`, copying its inherited list first. */
226
+ function declare(model, kind, entry) {
227
+ if (sealed.has(model)) {
228
+ const { name } = model;
229
+ throw new InvalidModel(`${name} has already been used; declare validations, callbacks and messages in its static {} block`);
230
+ }
231
+ listsOf(registry, model).set(kind, [...declared(model, kind), entry]);
232
+ const own = listsOf(ownRegistry, model);
233
+ own.set(kind, [...own.get(kind) ?? [], entry]);
234
+ }
235
+ /** `model`'s lists in a registry, by kind, made empty the first time. */
236
+ function listsOf(lists, model) {
237
+ const found = lists.get(model) ?? /* @__PURE__ */ new Map();
238
+ lists.set(model, found);
239
+ return found;
240
+ }
241
+ // src/enum-methods.ts
242
+ /** Each name of every enum attribute, with the methods it gives. */
243
+ function enumNames(definitions) {
244
+ return [...definitions].flatMap(([attribute, definition]) => {
245
+ if (definition.enum === void 0) return [];
246
+ const before = affix(attribute, definition.prefix);
247
+ const after = affix(attribute, definition.suffix);
248
+ return enumEntries(definition.enum).map(([name]) => {
249
+ const stem = `${before}${methodPart(name)}${after}`;
250
+ const records = [
251
+ `is${stem}`,
252
+ `saveAs${stem}`,
253
+ `saveAs${stem}OrThrow`
254
+ ];
255
+ const scopes = [uncapitalized(stem), `not${stem}`];
256
+ return {
257
+ attribute,
258
+ name,
259
+ records: definition.instanceMethods === false ? [] : records,
260
+ scopes: definition.scopes === false ? [] : scopes
261
+ };
262
+ });
263
+ });
264
+ }
265
+ function affix(attribute, option) {
266
+ if (option === true) return methodPart(attribute);
267
+ return typeof option === "string" ? methodPart(option) : "";
268
+ }
269
+ /** The scopes the enums of `definitions` give a Model, as `EnumStatics` types them. */
270
+ function enumScopeNames(definitions) {
271
+ return enumNames(definitions).flatMap(({ scopes }) => scopes);
272
+ }
273
+ /** How a word reads inside a method's name, as `MethodPart` types it. */
274
+ function methodPart(word) {
275
+ const [head = "", ...rest] = word.split("_");
276
+ return capitalized(head + rest.map(capitalized).join(""));
277
+ }
278
+ const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
279
+ const uncapitalized = (text) => text.charAt(0).toLowerCase() + text.slice(1);
280
+ /**
281
+ * Defines each enum attribute's methods on `prototype`: `isPublished()` is `status === "published"`,
282
+ * and `saveAsPublished()` is `update({ status: "published" })`, so it saves the record's other
283
+ * changes too, as Rails' `published!` does.
284
+ */
285
+ function defineEnumMethods(prototype, definitions) {
286
+ for (const { attribute, name, records } of enumNames(definitions)) {
287
+ const [predicate, setter, throwingSetter] = records;
288
+ if (predicate === void 0) continue;
289
+ defineMethod(prototype, predicate, function() {
290
+ return this[attribute] === name;
291
+ });
292
+ defineMethod(prototype, setter, function() {
293
+ return this.update({ [attribute]: name });
294
+ });
295
+ defineMethod(prototype, throwingSetter, function() {
296
+ return this.updateOrThrow({ [attribute]: name });
297
+ });
298
+ }
299
+ }
300
+ /**
301
+ * Defines each enum attribute's scopes on `model`, as `this.scope(…)` statics: `published()` is
302
+ * `where({ status: "published" })`, and `notPublished()` is `whereNot(…)`, as Rails' are.
303
+ */
304
+ function defineEnumStatics(model, definitions) {
305
+ const declaring = model;
306
+ for (const { attribute, name, scopes } of enumNames(definitions)) {
307
+ const [only, without] = scopes;
308
+ if (only === void 0) continue;
309
+ const onlyScope = declaring.scope((q) => q.where({ [attribute]: name }));
310
+ const withoutScope = declaring.scope((q) => q.whereNot({ [attribute]: name }));
311
+ enumScopes.add(onlyScope);
312
+ enumScopes.add(withoutScope);
313
+ defineMethod(model, only, onlyScope, { named: false });
314
+ defineMethod(model, without, withoutScope, { named: false });
315
+ }
316
+ }
317
+ /** Puts `method` on `target` as `name`, writable as a declared method is, and names it unless told not to. */
318
+ function defineMethod(target, name, method, { named = true } = {}) {
319
+ if (Object.hasOwn(target, name)) return;
320
+ if (named) Object.defineProperty(method, "name", { value: name });
321
+ Object.defineProperty(target, name, {
322
+ value: method,
323
+ writable: true,
324
+ configurable: true
325
+ });
326
+ }
327
+ /** The scope statics `defineEnumStatics` made, so a static a Model declares itself is told apart. */
328
+ const enumScopes = /* @__PURE__ */ new WeakSet();
329
+ /**
330
+ * Why an enum's method names can't be as they are, or undefined: two enums give one name, or one
331
+ * takes the name of a record method, an attribute, a Relation method, a Model static, or a static
332
+ * the Model declares itself. Rails refuses the same when an enum is declared.
333
+ */
334
+ function enumNameProblem(model, taken, methodsOff = /* @__PURE__ */ new Map()) {
335
+ const checks = {
336
+ ...taken,
337
+ methodsOffFix: (attribute) => methodsOff.get(attribute)
338
+ };
339
+ const givenBy = /* @__PURE__ */ new Map();
340
+ for (const each of enumNames(model.attributeDefinitions)) {
341
+ const { attribute, records, scopes } = each;
342
+ for (const method of [...records, ...scopes]) {
343
+ const other = givenBy.get(method);
344
+ if (other !== void 0) return repeated(model.name, {
345
+ first: other,
346
+ second: attribute,
347
+ method
348
+ }, checks);
349
+ givenBy.set(method, attribute);
350
+ }
351
+ const problem = declarableProblem(model, each, [...records, ...scopes], checks) ?? recordProblem(model, attribute, records, checks) ?? staticProblem(model, attribute, scopes, checks);
352
+ if (problem !== void 0) return problem;
353
+ }
354
+ }
355
+ /**
356
+ * A method name an enum's name gives that TypeScript can't declare (#340): one that isn't an
357
+ * identifier (`isIn-progress`), or a scope that's a reserved word (`new`), which the generated
358
+ * schema couldn't declare as a static.
359
+ */
360
+ function declarableProblem(model, { attribute, name, scopes }, methods, checks) {
361
+ const fix = remedy(attribute, checks);
362
+ const undeclarable = methods.find((method) => !isIdentifier(method));
363
+ if (undeclarable !== void 0) {
364
+ const kind = scopes.includes(undeclarable) ? "scope" : "method";
365
+ const suggested = uncapitalized(methodPart(name.split(/[^\p{L}\p{N}_$]+/u).join("_")));
366
+ const example = isIdentifier(suggested) ? ` ({ ${suggested}: ${JSON.stringify(name)} })` : "";
367
+ 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)}`;
368
+ }
369
+ const reserved = methods.find((method) => reservedWords.has(method));
370
+ return reserved === void 0 ? void 0 : `${model.name}'s enum ${attribute} gives a scope named "${reserved}", which is a reserved word; ${fix}`;
371
+ }
372
+ /** Two of an enum's names, or two enums, giving one method name. */
373
+ function repeated(model, { first, second, method }, checks) {
374
+ 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("")}`;
375
+ const off = offFix(second, checks);
376
+ return `${model}'s enum ${first} gives "${method}" for two of its names; ${off === "" ? "rename one" : "map one to a name of your own"}${off}`;
377
+ }
378
+ /** `offFix`, naming the enum: for a message about two of them. */
379
+ function namedOffFix(attribute, checks) {
380
+ const fix = checks.methodsOffFix(attribute);
381
+ return fix === void 0 ? "" : `, or leave ${attribute}'s methods off (remove ${fix})`;
382
+ }
383
+ /** How to fix an enum whose method name is taken: an affix, or for the database's, its methods off. */
384
+ const remedy = (attribute, checks) => `give ${attribute} a prefix or a suffix${offFix(attribute, checks)}`;
385
+ /** For an enum whose names the database gave (#64): leaving its methods off, as they start. */
386
+ function offFix(attribute, checks) {
387
+ const fix = checks.methodsOffFix(attribute);
388
+ return fix === void 0 ? "" : `, or leave its methods off (remove ${fix})`;
389
+ }
390
+ function recordProblem(model, attribute, methods, checks) {
391
+ for (const method of methods) {
392
+ const what = model.attributeDefinitions.has(method) ? "an attribute" : checks.isRecordName(method) ? "a record method" : void 0;
393
+ if (what !== void 0) return `${model.name}'s enum ${attribute} gives a method named "${method}", which is the name of ${what}; ${remedy(attribute, checks)}`;
394
+ }
395
+ }
396
+ function staticProblem(model, attribute, scopes, checks) {
397
+ for (const scope of scopes) {
398
+ const what = scope in Function.prototype ? "a Function method" : checks.isReservedStatic(scope) ? "a Relation method or a Model static" : void 0;
399
+ if (what !== void 0) return `${model.name}'s enum ${attribute} gives a scope named "${scope}", which is the name of ${what}; ${remedy(attribute, checks)}`;
400
+ const declared = checks.staticOf(scope);
401
+ const isEnumScope = typeof declared?.value === "function" && enumScopes.has(declared.value);
402
+ 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)}`;
403
+ }
237
404
  }
238
405
  // src/spec-keys.ts
239
406
  const attributeTypes = Object.keys({
@@ -553,20 +720,75 @@ function attributeOf(model, name) {
553
720
  function attributesForColumn(model, column) {
554
721
  return [...model.attributeDefinitions].filter(([, definition]) => definition.column === column).map(([name]) => name);
555
722
  }
556
- /** `undefined` would silently store NULL, so writing it throws `TypeError` (use `null`). */
557
- function requireDefined(model, name, value) {
558
- if (value === void 0) throw new TypeError(`${model.name}: got undefined for "${name}"; use null to store NULL`);
723
+ /** `undefined` would silently store NULL, so writing it throws `TypeError` (use `null`). */
724
+ function requireDefined(model, name, value) {
725
+ if (value === void 0) throw new TypeError(`${model.name}: got undefined for "${name}"; use null to store NULL`);
726
+ }
727
+ /**
728
+ * The initial values of every attribute not in `given` that has one, made now: each one's
729
+ * `default`, or for a generated id, the Model's `generateId(name)`.
730
+ */
731
+ function initialValues(model, given = {}) {
732
+ return [...model.attributeDefinitions].filter(([name, definition]) => !(name in given) && hasInitialValue(definition)).map(([name, definition]) => [name, definition.generateId ? model.generateId(name) : definition.default()]);
733
+ }
734
+ /** Whether an attribute gets a value when none is given: from its `default`, or `generateId`. */
735
+ function hasInitialValue(definition) {
736
+ return definition.generateId === true || definition.default !== void 0;
737
+ }
738
+ // src/filtering.ts
739
+ /** What a listener sees in place of a filtered attribute's value (#83). */
740
+ const FILTERED = "[FILTERED]";
741
+ /**
742
+ * Rails' default `filter_parameters` for a new app: an attribute whose snake_case name holds
743
+ * one of these, in any case, is filtered (`passwordDigest`, `apiKey`, `resetToken`, `email`).
744
+ */
745
+ const defaultFilterAttributes = [
746
+ "passw",
747
+ "email",
748
+ "secret",
749
+ "token",
750
+ "_key",
751
+ "crypt",
752
+ "salt",
753
+ "certificate",
754
+ "otp",
755
+ "ssn",
756
+ "cvv",
757
+ "cvc"
758
+ ];
759
+ /**
760
+ * Whether `attribute`'s values are hidden from listeners: its snake_case name holds a string
761
+ * entry lowercased, or read in snake_case (`"apiKey"` as `api_key`, #397), or a RegExp entry
762
+ * matches the attribute or its snake_case name.
763
+ */
764
+ function isFiltered(model, attribute) {
765
+ const name = underscore(attribute);
766
+ return model.filterAttributes.some((entry) => typeof entry === "string" ? name.includes(entry.toLowerCase()) || name.includes(underscore(entry)) : attribute.search(entry) !== -1 || name.search(entry) !== -1);
767
+ }
768
+ /** The values of `attributes` that `model` filters, so a message can tell not to show them. */
769
+ function filteredValues(model, attributes) {
770
+ return Object.entries(attributes).filter(([name]) => isFiltered(model, name)).map(([, value]) => value);
771
+ }
772
+ /** A bound value D1 gets as `value`, and listeners see as `shown`. */
773
+ var Filtered = class {
774
+ value;
775
+ shown;
776
+ constructor(value, shown = FILTERED) {
777
+ this.value = value;
778
+ this.shown = shown;
779
+ }
780
+ };
781
+ /** A primary key as an error shows it: "[FILTERED]" when the key is a filtered attribute. */
782
+ function shownKey(model, key) {
783
+ return isFiltered(model, model.primaryKey) ? FILTERED : String(key);
559
784
  }
560
- /**
561
- * The initial values of every attribute not in `given` that has one, made now: each one's
562
- * `default`, or for a generated id, the Model's `generateId(name)`.
563
- */
564
- function initialValues(model, given = {}) {
565
- return [...model.attributeDefinitions].filter(([name, definition]) => !(name in given) && hasInitialValue(definition)).map(([name, definition]) => [name, definition.generateId ? model.generateId(name) : definition.default()]);
785
+ /** The value D1 binds. */
786
+ function boundValue(param) {
787
+ return param instanceof Filtered ? param.value : param;
566
788
  }
567
- /** Whether an attribute gets a value when none is given: from its `default`, or `generateId`. */
568
- function hasInitialValue(definition) {
569
- return definition.generateId === true || definition.default !== void 0;
789
+ /** The value listeners see. */
790
+ function shownValue$1(param) {
791
+ return param instanceof Filtered ? param.shown : param;
570
792
  }
571
793
  // src/attribute.ts
572
794
  /** What `condition()` and `conditionCell()` give for a value that can't match anything. */
@@ -806,64 +1028,6 @@ function plainText(value) {
806
1028
  return Object.prototype.toString.call(value);
807
1029
  }
808
1030
  }
809
- // src/declarations.ts
810
- /**
811
- * Per-Model declarations (validations, callbacks, …), keyed by Model class. A subclass starts
812
- * from a copy of its parent's list, so declaring on it never changes the parent.
813
- *
814
- * Module-level, but not request state (ADR-0003): declarations are made once, when a Model
815
- * class is defined, and only read afterwards.
816
- */
817
- const registry = /* @__PURE__ */ new WeakMap();
818
- /** The declarations each class made itself, without its parent's, for reading class by class. */
819
- const ownRegistry = /* @__PURE__ */ new WeakMap();
820
- /** Models that have been used; their declarations can no longer change. */
821
- const sealed = /* @__PURE__ */ new WeakSet();
822
- /**
823
- * Called on a Model's first use. From then on, declaring on it throws: declarations belong in
824
- * the class's `static {}` block, never in request code, where they'd leak into every request.
825
- */
826
- function seal(model) {
827
- sealed.add(model);
828
- }
829
- /** Whether a Model has been used, so its declarations, and its ancestors', can no longer change. */
830
- function isSealed(model) {
831
- return sealed.has(model);
832
- }
833
- /** The declarations of `kind` for `model`: its own, or else its nearest ancestor's. */
834
- function declared(model, kind) {
835
- for (const current of ancestors(model)) {
836
- const list = registry.get(current)?.get(kind);
837
- if (list !== void 0) return list;
838
- }
839
- return [];
840
- }
841
- /** The declarations of `kind` that `model` and each class it extends made themselves, nearest first. */
842
- function declaredByClass(model, kind) {
843
- return ancestors(model).flatMap((from) => {
844
- const values = ownRegistry.get(from)?.get(kind);
845
- return values === void 0 ? [] : [{
846
- from,
847
- values
848
- }];
849
- });
850
- }
851
- /** Adds a declaration of `kind` to `model`, copying its inherited list first. */
852
- function declare(model, kind, entry) {
853
- if (sealed.has(model)) {
854
- const { name } = model;
855
- throw new InvalidModel(`${name} has already been used; declare validations, callbacks and messages in its static {} block`);
856
- }
857
- listsOf(registry, model).set(kind, [...declared(model, kind), entry]);
858
- const own = listsOf(ownRegistry, model);
859
- own.set(kind, [...own.get(kind) ?? [], entry]);
860
- }
861
- /** `model`'s lists in a registry, by kind, made empty the first time. */
862
- function listsOf(lists, model) {
863
- const found = lists.get(model) ?? /* @__PURE__ */ new Map();
864
- lists.set(model, found);
865
- return found;
866
- }
867
1031
  // src/error-messages.ts
868
1032
  /** @internal Rails' English messages, used where no class has its own (listed in the guide). */
869
1033
  const builtInMessages = {
@@ -1347,6 +1511,10 @@ var RecordState = class {
1347
1511
  const { name, primaryKey } = this.#model;
1348
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}`);
1349
1513
  }
1514
+ /** Whether `name` is one of the Model's attributes and loaded: not left out of `select(...)`. */
1515
+ hasAttribute(name) {
1516
+ return this.#model.attributeDefinitions.has(name) && Object.hasOwn(this.#values, name);
1517
+ }
1350
1518
  /** An attribute's value; `MissingAttribute` if it wasn't loaded (left out of `select`). */
1351
1519
  read(name) {
1352
1520
  this.#requireAttribute(name);
@@ -1641,170 +1809,6 @@ var RecordState = class {
1641
1809
  return this.#snapshotRow !== void 0 && this.#definition(name).column in this.#snapshotRow;
1642
1810
  }
1643
1811
  };
1644
- // src/enum-methods.ts
1645
- /** Each name of every enum attribute, with the methods it gives. */
1646
- function enumNames(definitions) {
1647
- return [...definitions].flatMap(([attribute, definition]) => {
1648
- if (definition.enum === void 0) return [];
1649
- const before = affix(attribute, definition.prefix);
1650
- const after = affix(attribute, definition.suffix);
1651
- return enumEntries(definition.enum).map(([name]) => {
1652
- const stem = `${before}${methodPart(name)}${after}`;
1653
- const records = [
1654
- `is${stem}`,
1655
- `saveAs${stem}`,
1656
- `saveAs${stem}OrThrow`
1657
- ];
1658
- const scopes = [uncapitalized(stem), `not${stem}`];
1659
- return {
1660
- attribute,
1661
- name,
1662
- records: definition.instanceMethods === false ? [] : records,
1663
- scopes: definition.scopes === false ? [] : scopes
1664
- };
1665
- });
1666
- });
1667
- }
1668
- function affix(attribute, option) {
1669
- if (option === true) return methodPart(attribute);
1670
- return typeof option === "string" ? methodPart(option) : "";
1671
- }
1672
- /** The scopes the enums of `definitions` give a Model, as `EnumStatics` types them. */
1673
- function enumScopeNames(definitions) {
1674
- return enumNames(definitions).flatMap(({ scopes }) => scopes);
1675
- }
1676
- /** How a word reads inside a method's name, as `MethodPart` types it. */
1677
- function methodPart(word) {
1678
- const [head = "", ...rest] = word.split("_");
1679
- return capitalized(head + rest.map(capitalized).join(""));
1680
- }
1681
- const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
1682
- const uncapitalized = (text) => text.charAt(0).toLowerCase() + text.slice(1);
1683
- /**
1684
- * Defines each enum attribute's methods on `prototype`: `isPublished()` is `status === "published"`,
1685
- * and `saveAsPublished()` is `update({ status: "published" })`, so it saves the record's other
1686
- * changes too, as Rails' `published!` does.
1687
- */
1688
- function defineEnumMethods(prototype, definitions) {
1689
- for (const { attribute, name, records } of enumNames(definitions)) {
1690
- const [predicate, setter, throwingSetter] = records;
1691
- if (predicate === void 0) continue;
1692
- defineMethod(prototype, predicate, function() {
1693
- return this[attribute] === name;
1694
- });
1695
- defineMethod(prototype, setter, function() {
1696
- return this.update({ [attribute]: name });
1697
- });
1698
- defineMethod(prototype, throwingSetter, function() {
1699
- return this.updateOrThrow({ [attribute]: name });
1700
- });
1701
- }
1702
- }
1703
- /**
1704
- * Defines each enum attribute's scopes on `model`, as `this.scope(…)` statics: `published()` is
1705
- * `where({ status: "published" })`, and `notPublished()` is `whereNot(…)`, as Rails' are.
1706
- */
1707
- function defineEnumStatics(model, definitions) {
1708
- const declaring = model;
1709
- for (const { attribute, name, scopes } of enumNames(definitions)) {
1710
- const [only, without] = scopes;
1711
- if (only === void 0) continue;
1712
- const onlyScope = declaring.scope((q) => q.where({ [attribute]: name }));
1713
- const withoutScope = declaring.scope((q) => q.whereNot({ [attribute]: name }));
1714
- enumScopes.add(onlyScope);
1715
- enumScopes.add(withoutScope);
1716
- defineMethod(model, only, onlyScope, { named: false });
1717
- defineMethod(model, without, withoutScope, { named: false });
1718
- }
1719
- }
1720
- /** Puts `method` on `target` as `name`, writable as a declared method is, and names it unless told not to. */
1721
- function defineMethod(target, name, method, { named = true } = {}) {
1722
- if (Object.hasOwn(target, name)) return;
1723
- if (named) Object.defineProperty(method, "name", { value: name });
1724
- Object.defineProperty(target, name, {
1725
- value: method,
1726
- writable: true,
1727
- configurable: true
1728
- });
1729
- }
1730
- /** The scope statics `defineEnumStatics` made, so a static a Model declares itself is told apart. */
1731
- const enumScopes = /* @__PURE__ */ new WeakSet();
1732
- /**
1733
- * Why an enum's method names can't be as they are, or undefined: two enums give one name, or one
1734
- * takes the name of a record method, an attribute, a Relation method, a Model static, or a static
1735
- * the Model declares itself. Rails refuses the same when an enum is declared.
1736
- */
1737
- function enumNameProblem(model, taken, methodsOff = /* @__PURE__ */ new Map()) {
1738
- const checks = {
1739
- ...taken,
1740
- methodsOffFix: (attribute) => methodsOff.get(attribute)
1741
- };
1742
- const givenBy = /* @__PURE__ */ new Map();
1743
- for (const each of enumNames(model.attributeDefinitions)) {
1744
- const { attribute, records, scopes } = each;
1745
- for (const method of [...records, ...scopes]) {
1746
- const other = givenBy.get(method);
1747
- if (other !== void 0) return repeated(model.name, {
1748
- first: other,
1749
- second: attribute,
1750
- method
1751
- }, checks);
1752
- givenBy.set(method, attribute);
1753
- }
1754
- const problem = declarableProblem(model, each, [...records, ...scopes], checks) ?? recordProblem(model, attribute, records, checks) ?? staticProblem(model, attribute, scopes, checks);
1755
- if (problem !== void 0) return problem;
1756
- }
1757
- }
1758
- /**
1759
- * A method name an enum's name gives that TypeScript can't declare (#340): one that isn't an
1760
- * identifier (`isIn-progress`), or a scope that's a reserved word (`new`), which the generated
1761
- * schema couldn't declare as a static.
1762
- */
1763
- function declarableProblem(model, { attribute, name, scopes }, methods, checks) {
1764
- const fix = remedy(attribute, checks);
1765
- const undeclarable = methods.find((method) => !isIdentifier(method));
1766
- if (undeclarable !== void 0) {
1767
- const kind = scopes.includes(undeclarable) ? "scope" : "method";
1768
- const suggested = uncapitalized(methodPart(name.split(/[^\p{L}\p{N}_$]+/u).join("_")));
1769
- const example = isIdentifier(suggested) ? ` ({ ${suggested}: ${JSON.stringify(name)} })` : "";
1770
- return `${model.name}'s enum ${attribute} gives a ${kind} named "${undeclarable}", which isn't a name TypeScript can declare; name it with letters, digits, _ and $, and map it to the value it's stored as${example}${offFix(attribute, checks)}`;
1771
- }
1772
- const reserved = methods.find((method) => reservedWords.has(method));
1773
- return reserved === void 0 ? void 0 : `${model.name}'s enum ${attribute} gives a scope named "${reserved}", which is a reserved word; ${fix}`;
1774
- }
1775
- /** Two of an enum's names, or two enums, giving one method name. */
1776
- function repeated(model, { first, second, method }, checks) {
1777
- if (first !== second) return `${model}'s enums ${first} and ${second} both give a method named "${method}"; give one a prefix or a suffix${[first, second].map((attribute) => namedOffFix(attribute, checks)).join("")}`;
1778
- const off = offFix(second, checks);
1779
- return `${model}'s enum ${first} gives "${method}" for two of its names; ${off === "" ? "rename one" : "map one to a name of your own"}${off}`;
1780
- }
1781
- /** `offFix`, naming the enum: for a message about two of them. */
1782
- function namedOffFix(attribute, checks) {
1783
- const fix = checks.methodsOffFix(attribute);
1784
- return fix === void 0 ? "" : `, or leave ${attribute}'s methods off (remove ${fix})`;
1785
- }
1786
- /** How to fix an enum whose method name is taken: an affix, or for the database's, its methods off. */
1787
- const remedy = (attribute, checks) => `give ${attribute} a prefix or a suffix${offFix(attribute, checks)}`;
1788
- /** For an enum whose names the database gave (#64): leaving its methods off, as they start. */
1789
- function offFix(attribute, checks) {
1790
- const fix = checks.methodsOffFix(attribute);
1791
- return fix === void 0 ? "" : `, or leave its methods off (remove ${fix})`;
1792
- }
1793
- function recordProblem(model, attribute, methods, checks) {
1794
- for (const method of methods) {
1795
- const what = model.attributeDefinitions.has(method) ? "an attribute" : checks.isRecordName(method) ? "a record method" : void 0;
1796
- if (what !== void 0) return `${model.name}'s enum ${attribute} gives a method named "${method}", which is the name of ${what}; ${remedy(attribute, checks)}`;
1797
- }
1798
- }
1799
- function staticProblem(model, attribute, scopes, checks) {
1800
- for (const scope of scopes) {
1801
- const what = scope in Function.prototype ? "a Function method" : checks.isReservedStatic(scope) ? "a Relation method or a Model static" : void 0;
1802
- if (what !== void 0) return `${model.name}'s enum ${attribute} gives a scope named "${scope}", which is the name of ${what}; ${remedy(attribute, checks)}`;
1803
- const declared = checks.staticOf(scope);
1804
- const isEnumScope = typeof declared?.value === "function" && enumScopes.has(declared.value);
1805
- if (declared !== void 0 && !isEnumScope) return `${model.name} declares "${scope}", which is also the name of a scope its enum ${attribute} gives; rename it, or ${remedy(attribute, checks)}`;
1806
- }
1807
- }
1808
1812
  // src/enum-switch.ts
1809
1813
  /** Takes an override's `enum: true` or `false` out of it, so its other changes are checked as any override's. */
1810
1814
  function takeEnumSwitch(override) {
@@ -2051,4 +2055,4 @@ function specsFor(name, table, overrides) {
2051
2055
  isIgnoringColumns: [...changes.values()].includes(false)
2052
2056
  };
2053
2057
  }
2054
- export { modelNameOf as $, attributeFor as A, specProblem as B, styled as C, declared as D, declare as E, attributesForColumn as F, filteredValues as G, Filtered as H, define as I, shownValue$1 as J, isFiltered as K, initialValues as L, noMatch as M, withArticle as N, declaredByClass as O, attributeOf as P, isIgnoringColumns as Q, requireDefined as R, printed as S, humanAttributeName as T, boundValue as U, FILTERED as V, defaultFilterAttributes as W, explainMissingTable as X, defineModelName as Y, inferTableNames as Z, addFailure as _, isGenerated as a, tableize as at, FilteredMark as b, methodsOffFixes as c, enumNameProblem as d, ownValueSetter as et, enumScopeNames as f, Errors as g, state as h, isBase as i, tableOwnerModelName as it, castInherited as j, seal as k, defineEnumMethods as l, linksOf as m, defineGeneratedStatics as n, requireModelName as nt, schemaAdapter as o, ancestors as ot, RecordState as p, shownKey as q, hasSettledAttributes as r, requireTableName as rt, settleGenerated as s, staticBelow as st, defineAttributeAccessors as t, rejectAbstract as tt, defineEnumStatics as u, clearErrors as v, attributesNamedInMessages as w, inspectCustom as x, fullMessageOf as y, defineType as z };
2058
+ export { modelNameOf as $, filteredValues as A, specProblem as B, castInherited as C, Filtered as D, FILTERED as E, attributesForColumn as F, declare as G, defineEnumStatics as H, define as I, seal as J, declared as K, initialValues as L, shownKey as M, shownValue$1 as N, boundValue as O, attributeOf as P, isIgnoringColumns as Q, requireDefined as R, attributeFor as S, withArticle as T, enumNameProblem as U, defineEnumMethods as V, enumScopeNames 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, isFiltered as j, defaultFilterAttributes as k, RecordState as l, clearErrors as m, defineGeneratedStatics as n, requireModelName as nt, schemaAdapter as o, ancestors as ot, addFailure as p, declaredByClass 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, noMatch as w, humanAttributeName as x, styled as y, defineType as z };