@forestfuture/active-record 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { C as pluralize, E as underscore } from "./epoch-storage-CDlQZcBB.mjs";
2
- import { a as migrationSql, c as migrationPlan, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-DhNV1mWf.mjs";
3
- import { f as byName, i as attributeName, l as configFileName, n as castDefault, o as exportName, p as byVersion, r as isCastDefaultType, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-n4w1cS_M.mjs";
1
+ import { C as pluralize, E as underscore } from "./identifiers-Dh5DFACX.mjs";
2
+ import { a as migrationSql, c as migrationPlan, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-BbIMUNcz.mjs";
3
+ import { f as byName, i as attributeName, l as configFileName, n as castDefault, o as exportName, p as byVersion, r as isCastDefaultType, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-0ZgeP2sc.mjs";
4
4
  export { attributeName, byName, byVersion, castDefault, configFileName, exportName, generatedSchema, indexName, isCastDefaultType, listed, migrationPlan, migrationSql, namesInList, parseJsonc, pluralize, quotedName, storageOverride, underscore, withDigits, withGeneratedEnum };
package/dist/command.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { _ as importPath, a as classify, c as moduleName, d as projectDatabases, g as migrationsOf, h as leadingNumber, m as hasNestedMigrations, n as castDefault, p as byVersion, s as listed, t as storageOverride, u as parseJsonc, v as shown$1, y as slashed } from "./storage-override-n4w1cS_M.mjs";
3
- import { J as enumScopeNames, at as tableize, c as methodsOffFixes, i as isBase, ot as ancestors, q as enumNameProblem, st as staticBelow } from "./generated-model-g5oWsDKE.mjs";
4
- import { C as pluralize, E as underscore, T as camelize, h as isIdentifier, n as digitsProblem, w as singularize } from "./epoch-storage-CDlQZcBB.mjs";
2
+ import { _ as importPath, a as classify, c as moduleName, d as projectDatabases, g as migrationsOf, h as leadingNumber, m as hasNestedMigrations, n as castDefault, p as byVersion, s as listed, t as storageOverride, u as parseJsonc, v as shown$1, y as slashed } from "./storage-override-0ZgeP2sc.mjs";
3
+ import { at as tableize, c as methodsOffFixes, d as enumNameProblem, f as enumScopeNames, i as isBase, ot as ancestors, st as staticBelow } from "./generated-model-DJA8vmNE.mjs";
4
+ import { C as pluralize, E as underscore, T as camelize, i as digitsProblem, t as isIdentifier, w as singularize } from "./identifiers-Dh5DFACX.mjs";
5
5
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
6
6
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
7
7
  import { inspect, parseArgs, types } from "node:util";
@@ -68,11 +68,11 @@ function helpFor(subcommands) {
68
68
  const adapters = {
69
69
  d1: {
70
70
  entry: "@forestfuture/active-record/d1",
71
- plugin: async () => (await import("./plugin-wOSILvSB.mjs")).cli
71
+ plugin: async () => (await import("./plugin-CZPDqguF.mjs")).cli
72
72
  },
73
73
  postgresql: {
74
74
  entry: "@forestfuture/active-record/postgresql",
75
- plugin: async () => (await import("./plugin-x5-d3TSN.mjs")).cli
75
+ plugin: async () => (await import("./plugin-Cf-5Z0_h.mjs")).cli
76
76
  }
77
77
  };
78
78
  /** The adapters' names, in the registry's order. */
package/dist/d1.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-DHDVV8hB.mjs";
2
- import { i as ActiveRecordError } from "./index-BATasvJa.mjs";
1
+ import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-BSZ5gVeI.mjs";
2
+ import { i as ActiveRecordError } from "./index-D5getfHx.mjs";
3
3
  /** The D1 database a generated schema's Models query: `adapter: d1({ binding: "DB" })`. */
4
4
  export declare function d1({ binding }: {
5
5
  binding: string;
package/dist/d1.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { a as databaseExecutor, i as AnyDatabase, l as DatabaseExecutor, r as withDatabase } from "./batch-ReqVoCfa.mjs";
2
- import { n as onlyRequested, t as workersEnv } from "./for-adapters-CfXMGeOu.mjs";
3
- import { O as ActiveRecordError, p as hexOf, z as NoDatabase } from "./epoch-storage-CDlQZcBB.mjs";
4
- import { M as boundValue } from "./generated-model-g5oWsDKE.mjs";
1
+ import { a as AnyDatabase, g as DatabaseExecutor, i as withDatabase, o as databaseExecutor } from "./batch-Ms5p9lKq.mjs";
2
+ import { n as onlyRequested, t as workersEnv } from "./for-adapters-C-MQxaIx.mjs";
3
+ import { O as ActiveRecordError, x as hexOf, z as NoDatabase } from "./identifiers-Dh5DFACX.mjs";
4
+ import { U as boundValue } from "./generated-model-DJA8vmNE.mjs";
5
5
  // src/adapters/d1/errors.ts
6
6
  /** D1's error for a Session's bookmark it can't use, and the bookmark it repeats (#237). */
7
7
  const rejectedBookmark = /invalid commitToken bookmark provided: (.*)$/s;
@@ -1,4 +1,4 @@
1
- import { O as AnyDatabase } from "./validations-DHDVV8hB.mjs";
1
+ import { O as AnyDatabase } from "./validations-BSZ5gVeI.mjs";
2
2
  /**
3
3
  * Bytes as hex text, two digits each, for SQL that reads bytes from JSON (`unhex`, `\\x…`). The
4
4
  * digits' character codes are written into one array and decoded once: mapping each byte to a
@@ -1,5 +1,5 @@
1
- import { C as pluralize, E as underscore, n as digitsProblem } from "./epoch-storage-CDlQZcBB.mjs";
2
- import { f as byName, o as exportName } from "./storage-override-n4w1cS_M.mjs";
1
+ import { C as pluralize, E as underscore, i as digitsProblem } from "./identifiers-Dh5DFACX.mjs";
2
+ import { f as byName, o as exportName } from "./storage-override-0ZgeP2sc.mjs";
3
3
  // cli/generate/migration-plan.ts
4
4
  /** What to do, read from a migration's name: `create_products`, `add_sku_to_products`, …; else empty. */
5
5
  function migrationPlan(name) {
@@ -1,4 +1,4 @@
1
- import { z as NoDatabase } from "./epoch-storage-CDlQZcBB.mjs";
1
+ import { z as NoDatabase } from "./identifiers-Dh5DFACX.mjs";
2
2
  // src/request-database.ts
3
3
  /**
4
4
  * The request's database for a query on `binding` outside a Worker, or a `NoDatabase` saying what
@@ -1,4 +1,4 @@
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";
1
+ import { C as pluralize, E as underscore, H as RecordDestroyed, I as InvalidModel, R as MissingAttribute, S as isSameCell, Z as UnknownAttribute, b as listedNames, c as castValue, d as uncastable, g as enumProblem, h as enumEntries, i as digitsProblem, l as isInvalidDate, n as reservedWords, o as castCondition, p as writeValue, r as epochStorages, s as castKey, t as isIdentifier, u as readValue, y as isEnumValues, z as NoDatabase } from "./identifiers-Dh5DFACX.mjs";
2
2
  // src/ancestors.ts
3
3
  /** A class and every class (and object) it extends, nearest first. */
4
4
  function ancestors(model) {
@@ -180,169 +180,60 @@ 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/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
- });
206
- }
207
- function affix(attribute, option) {
208
- if (option === true) return methodPart(attribute);
209
- return typeof option === "string" ? methodPart(option) : "";
210
- }
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);
214
- }
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(""));
219
- }
220
- const capitalized = (text) => text.charAt(0).toUpperCase() + text.slice(1);
221
- const uncapitalized = (text) => text.charAt(0).toLowerCase() + text.slice(1);
183
+ // src/filtering.ts
184
+ /** What a listener sees in place of a filtered attribute's value (#83). */
185
+ const FILTERED = "[FILTERED]";
222
186
  /**
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.
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`).
226
189
  */
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
- });
240
- }
241
- }
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
+ ];
242
204
  /**
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.
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.
245
208
  */
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
- });
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);
268
212
  }
269
- /** The scope statics `defineEnumStatics` made, so a static a Model declares itself is told apart. */
270
- const enumScopes = /* @__PURE__ */ new WeakSet();
271
- /**
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.
275
- */
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
- }
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);
296
216
  }
297
- /**
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.
301
- */
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)}`;
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;
310
224
  }
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})`;
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);
331
229
  }
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
- }
230
+ /** The value D1 binds. */
231
+ function boundValue(param) {
232
+ return param instanceof Filtered ? param.value : param;
337
233
  }
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
- }
234
+ /** The value listeners see. */
235
+ function shownValue$1(param) {
236
+ return param instanceof Filtered ? param.shown : param;
346
237
  }
347
238
  // src/spec-keys.ts
348
239
  const attributeTypes = Object.keys({
@@ -677,61 +568,6 @@ function initialValues(model, given = {}) {
677
568
  function hasInitialValue(definition) {
678
569
  return definition.generateId === true || definition.default !== void 0;
679
570
  }
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
571
  // src/attribute.ts
736
572
  /** What `condition()` and `conditionCell()` give for a value that can't match anything. */
737
573
  const noMatch = uncastable;
@@ -1712,6 +1548,15 @@ var RecordState = class {
1712
1548
  this.#snapshot.set(name, this.#storedForm(name));
1713
1549
  }
1714
1550
  }
1551
+ /**
1552
+ * After a touch (#50): as `commitColumns`, and `savedChanges` holds only the touched
1553
+ * attributes' changes, as Rails' `touch` applies them. The record's other changes stay unsaved.
1554
+ */
1555
+ commitTouch(names) {
1556
+ const changes = this.changes();
1557
+ this.commitColumns(names);
1558
+ this.#savedChanges = Object.fromEntries(names.filter((name) => Object.hasOwn(changes, name)).map((name) => [name, changes[name]]));
1559
+ }
1715
1560
  /** A save with nothing to write: nothing changes but `savedChanges`. */
1716
1561
  commitClean() {
1717
1562
  this.#savedChanges = {};
@@ -1796,6 +1641,170 @@ var RecordState = class {
1796
1641
  return this.#snapshotRow !== void 0 && this.#definition(name).column in this.#snapshotRow;
1797
1642
  }
1798
1643
  };
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
+ }
1799
1808
  // src/enum-switch.ts
1800
1809
  /** Takes an override's `enum: true` or `false` out of it, so its other changes are checked as any override's. */
1801
1810
  function takeEnumSwitch(override) {
@@ -2042,4 +2051,4 @@ function specsFor(name, table, overrides) {
2042
2051
  isIgnoringColumns: [...changes.values()].includes(false)
2043
2052
  };
2044
2053
  }
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 };
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 };