@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
package/dist/command.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { J as tableize, Y as ancestors, i as isBase } from "./generated-model-Cnt0Ot9q.mjs";
3
- import { a as underscore, i as camelize, n as pluralize, r as singularize } from "./epoch-storage-o2aoOH7H.mjs";
4
- import { _ as shown$1, a as isIdentifier, f as byVersion, g as importPath, h as migrationsOf, l as parseJsonc, m as leadingNumber, o as listed, p as hasNestedMigrations, r as classify, s as moduleName, t as storageOverride, u as projectDatabases, v as slashed } from "./storage-override-CpbkdIqE.mjs";
5
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
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";
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";
8
8
  import { WriteStream } from "node:tty";
@@ -13,7 +13,7 @@ import { PassThrough, Readable, Writable } from "node:stream";
13
13
  import { AsyncLocalStorage } from "node:async_hooks";
14
14
  import repl from "node:repl";
15
15
  import { createHash } from "node:crypto";
16
- //#region cli/subcommand.ts
16
+ // cli/subcommand.ts
17
17
  /** The flags every subcommand takes. */
18
18
  const sharedOptions = {
19
19
  config: { type: "string" },
@@ -63,17 +63,16 @@ function helpFor(subcommands) {
63
63
  sharedFlagHelp
64
64
  ].join("\n\n");
65
65
  }
66
- //#endregion
67
- //#region cli/project/adapters.ts
66
+ // cli/project/adapters.ts
68
67
  /** Each adapter a database's `adapter` names. Its plugin ships with the command, loaded when it's used. */
69
68
  const adapters = {
70
69
  d1: {
71
70
  entry: "@forestfuture/active-record/d1",
72
- plugin: async () => (await import("./plugin-Cyoej7qV.mjs")).cli
71
+ plugin: async () => (await import("./plugin-wOSILvSB.mjs")).cli
73
72
  },
74
73
  postgresql: {
75
74
  entry: "@forestfuture/active-record/postgresql",
76
- plugin: async () => (await import("./plugin-XOHYndhP.mjs")).cli
75
+ plugin: async () => (await import("./plugin-x5-d3TSN.mjs")).cli
77
76
  }
78
77
  };
79
78
  /** The adapters' names, in the registry's order. */
@@ -91,44 +90,120 @@ function adapterError(binding, adapter) {
91
90
  if (typeof adapter === "string" && Object.hasOwn(adapters, adapter)) return void 0;
92
91
  return `databases.${binding} has the adapter ${JSON.stringify(adapter)}, which isn't ${listed(adapterNames)}`;
93
92
  }
94
- /** The one adapter the project's databases name, or why there isn't one (#305). */
95
- function adapterNamed(project) {
93
+ /** The adapters the project's databases name, each once, in the file's order; or why one won't do. */
94
+ function adaptersNamed(project) {
96
95
  const file = basename(project.file);
97
- const entries = Object.entries(project.databases);
98
- for (const [binding, entry] of entries) {
96
+ const names = [];
97
+ for (const [binding, entry] of Object.entries(project.databases)) {
99
98
  const error = adapterError(binding, entry.adapter);
100
99
  if (error !== void 0) return `${file}: ${error}`;
100
+ if (!names.includes(entry.adapter)) names.push(entry.adapter);
101
101
  }
102
- const named = new Set(entries.map(([, entry]) => entry.adapter));
103
- if (named.size === 1) return { name: [...named][0] };
104
- return `${file} names more than one adapter (${entries.map(([binding, entry]) => `${String(entry.adapter)} for ${binding}`).join(", ")}); a project uses one, for now`;
105
- }
106
- /** The notes the project's adapter has about its databases, as the command prints them. */
107
- function configNotes(adapter) {
108
- const config = adapter.databases();
109
- return config.ok ? (config.notes ?? []).map((note) => `Note: ${note}`) : [];
102
+ return names;
110
103
  }
111
104
  /** The plugin of the adapter `name`. */
112
105
  function pluginOf(name) {
113
106
  return adapters[name].plugin();
114
107
  }
115
108
  /**
116
- * The project's adapter, as its `active-record.jsonc` (or the file `configPath` names) names it, with
117
- * its plugin reading the databases there; or a message saying what to do.
109
+ * The adapters the project's `active-record.jsonc` (or the file `configPath` names) names, each
110
+ * one's plugin loaded and able to run on this Node; or a message saying what to do.
118
111
  */
119
- async function loadAdapter(cwd, configPath) {
112
+ async function loadAdapters(cwd, configPath) {
120
113
  const project = projectDatabases(cwd, configPath);
121
114
  if (typeof project === "string") return project;
122
- const named = adapterNamed(project);
123
- if (typeof named === "string") return named;
124
- const plugin = await pluginOf(named.name);
125
- return plugin.unsupported?.() ?? {
126
- ...plugin,
127
- databases: () => plugin.databases(project)
115
+ const names = adaptersNamed(project);
116
+ if (typeof names === "string") return names;
117
+ const plugins = await Promise.all(names.map((name) => pluginOf(name)));
118
+ return plugins.map((plugin) => plugin.unsupported?.()).find(Boolean) ?? {
119
+ project,
120
+ plugins
121
+ };
122
+ }
123
+ // cli/project/databases.ts
124
+ /** The entries the project's file has for one adapter, as its plugin reads them. */
125
+ function entriesFor(project, name) {
126
+ const own = Object.entries(project.databases).filter(([, entry]) => entry.adapter === name);
127
+ return {
128
+ ...project,
129
+ databases: Object.fromEntries(own)
130
+ };
131
+ }
132
+ /** A database's migrations folder, as an absolute path: its config's, beside its config file. */
133
+ function migrationsFolderOf({ configDir, database }) {
134
+ return resolve(configDir, database.migrationsDir);
135
+ }
136
+ /** Each adapter's databases, read by its plugin from the entries the file has for it. */
137
+ function databasesOf({ project, plugins }) {
138
+ const loaded = {
139
+ databases: [],
140
+ notes: []
128
141
  };
142
+ for (const adapter of plugins) {
143
+ const config = adapter.databases(entriesFor(project, adapter.name));
144
+ if (!config.ok) return config.error;
145
+ for (const database of config.databases) {
146
+ const configFile = database.configFile ?? config.file;
147
+ const configDir = database.configFile === void 0 ? config.dir : dirname(configFile);
148
+ loaded.databases.push({
149
+ adapter,
150
+ database,
151
+ configFile,
152
+ configDir
153
+ });
154
+ }
155
+ loaded.notes.push(...config.notes ?? []);
156
+ }
157
+ const order = Object.keys(project.databases);
158
+ const at = (each) => order.indexOf(each.database.binding);
159
+ loaded.databases.sort((a, b) => at(a) - at(b));
160
+ return loaded;
161
+ }
162
+ /** A folder with its links followed, when it exists, so a linked folder is the one it links to. */
163
+ function onDisk(folder) {
164
+ return existsSync(folder) ? realpathSync.native(folder) : folder;
165
+ }
166
+ /**
167
+ * Two databases on different adapters reading one migrations folder, as an error: one folder can't
168
+ * hold each adapter's SQL, and the adapters may default to the same folder.
169
+ */
170
+ function sharedMigrations(cwd, databases) {
171
+ const seen = /* @__PURE__ */ new Map();
172
+ for (const each of databases) {
173
+ const other = seen.get(onDisk(migrationsFolderOf(each)));
174
+ if (other !== void 0 && other.adapter.name !== each.adapter.name) return `${sharing(cwd, other, each)}, on different adapters (${other.adapter.name} and ${each.adapter.name}); give each its own migrations folder`;
175
+ seen.set(onDisk(migrationsFolderOf(each)), each);
176
+ }
177
+ }
178
+ /** That two databases both read one folder, or each one's path when a link makes them one. */
179
+ function sharing(cwd, first, second) {
180
+ const [one, two] = [first, second].map((each) => `${shown$1(cwd, migrationsFolderOf(each))}/`);
181
+ const [a, b] = [first.database.binding, second.database.binding];
182
+ return one === two ? `${a} and ${b} both read ${one}` : `${a}'s ${one} and ${b}'s ${two} are one folder`;
183
+ }
184
+ /**
185
+ * The project's databases, each with its own adapter, as its `active-record.jsonc` (or the file
186
+ * `configPath` names) names it (#305); or a message saying what to do.
187
+ */
188
+ async function loadDatabases(cwd, configPath) {
189
+ const named = await loadAdapters(cwd, configPath);
190
+ const loaded = typeof named === "string" ? named : databasesOf(named);
191
+ if (typeof loaded === "string") return loaded;
192
+ return sharedMigrations(cwd, loaded.databases) ?? loaded;
193
+ }
194
+ /**
195
+ * The project's databases, as a command loads them: having printed what their adapters note about
196
+ * them, or, when they can't be loaded, `undefined`, having printed why.
197
+ */
198
+ async function loadForCommand(cwd, options, print) {
199
+ const loaded = await loadDatabases(cwd, options.config);
200
+ if (typeof loaded === "string") {
201
+ print(loaded);
202
+ return;
203
+ }
204
+ for (const note of loaded.notes) print(`Note: ${note}`);
205
+ return loaded;
129
206
  }
130
- //#endregion
131
- //#region cli/project/databases.ts
132
207
  /**
133
208
  * The database a command works on: the only one, or the one `--database` names; or, as a message
134
209
  * to print, why there isn't one (several and none named, or a name no binding has).
@@ -141,23 +216,41 @@ function chooseDatabase(databases, named) {
141
216
  }
142
217
  return databases.find((database) => database.binding === named) ?? `No database is bound as ${named}; this config has ${bindings}`;
143
218
  }
144
- /** The database for `--database` (and `--config`), with its config file, or why there isn't one. */
145
- function chosenDatabase(adapter, cwd, options) {
146
- const config = adapter.databases();
147
- if (!config.ok) return config.error;
148
- const chosen = chooseDatabase(config.databases, options.database);
149
- if (typeof chosen === "string") return chosen;
150
- const { binding, entry } = chosen;
151
- const migrationsDir = resolve(config.dir, chosen.migrationsDir);
219
+ /** The database `--database` names (or the only one), with its adapter, or why there isn't one. */
220
+ function chosenDatabase(project, options) {
221
+ const found = chooseDatabase(project.databases.map((each) => ({
222
+ ...each,
223
+ binding: each.database.binding
224
+ })), options.database);
225
+ if (typeof found === "string") return found;
226
+ const { adapter, database, configFile } = found;
227
+ const migrationsDir = migrationsFolderOf(found);
152
228
  return {
153
- binding,
154
- entry,
155
- configFile: config.file,
156
- migrationsDir
229
+ adapter,
230
+ chosen: {
231
+ binding: database.binding,
232
+ entry: database.entry,
233
+ configFile,
234
+ migrationsDir
235
+ }
157
236
  };
158
237
  }
159
- //#endregion
160
- //#region cli/console/verbose.ts
238
+ // cli/console/verbose.ts
239
+ /**
240
+ * `sql` on one line: each line break, with the spaces around it, as one space. Split rather than
241
+ * matched by a regex of spaces, a line break and spaces, which rescans a long run of spaces from
242
+ * each place in it.
243
+ */
244
+ function oneLine(sql) {
245
+ const lines = sql.split("\n");
246
+ if (lines.length === 1) return sql;
247
+ const middle = lines.slice(1, -1).map((line) => line.trim());
248
+ return [
249
+ lines[0].trimEnd(),
250
+ ...middle.filter((line) => line !== ""),
251
+ lines.at(-1).trimStart()
252
+ ].join(" ");
253
+ }
161
254
  /**
162
255
  * One line for a statement, as `onQuery` saw it (filtered values are already `[FILTERED]`):
163
256
  * ` User 1.2ms SELECT … WHERE "id" = ? [ 1 ]`, or `failed` and the reason in place of the time
@@ -165,7 +258,7 @@ function chosenDatabase(adapter, cwd, options) {
165
258
  */
166
259
  function statementLine(event, dim) {
167
260
  const { model, params, durationMs, error } = event;
168
- const sql = event.sql.replace(/\s*\n\s*/g, " ");
261
+ const sql = oneLine(event.sql);
169
262
  let line = ` ${model} `;
170
263
  if (error !== void 0) line += `failed ${sql} ${error instanceof Error ? error.message : inspect(error)}`;
171
264
  else {
@@ -174,8 +267,7 @@ function statementLine(event, dim) {
174
267
  }
175
268
  return dim ? `\u001b[2m${line}\u001b[22m` : line;
176
269
  }
177
- //#endregion
178
- //#region cli/console/commands.ts
270
+ // cli/console/commands.ts
179
271
  /**
180
272
  * The commands, and the `onQuery` the console's database is connected with. They share one
181
273
  * switch: `.verbose` flips what the listener does.
@@ -212,8 +304,7 @@ function consoleCommands(project, { verbose, write, dim }) {
212
304
  }
213
305
  };
214
306
  }
215
- //#endregion
216
- //#region cli/console/confirm.ts
307
+ // cli/console/confirm.ts
217
308
  /** How long input must stay quiet, once released, for what was already on its way to have arrived. */
218
309
  const QUIET_MS = 50;
219
310
  /** Reads and drops everything on `input` until the returned function is called and it is quiet. */
@@ -250,8 +341,7 @@ async function confirmRemote({ input, output, target, consequence = "What you ch
250
341
  release
251
342
  };
252
343
  }
253
- //#endregion
254
- //#region cli/project/targets.ts
344
+ // cli/project/targets.ts
255
345
  /**
256
346
  * A database's base class: `ApplicationRecord` when there's one database, as in Rails, and one
257
347
  * per binding when there are several (`LOGS` → `LogsRecord`), as Rails names them.
@@ -270,13 +360,13 @@ function baseFor(modelsDir, binding, several) {
270
360
  /** Where Models and their base class go without `--models`. */
271
361
  const defaultModels = "src/models";
272
362
  /** Whether `--models` names one file all Models go in (`src/models.ts`), not a folder. */
273
- function oneModelsFile(models) {
363
+ function isOneModelsFile(models) {
274
364
  return models.endsWith(".ts");
275
365
  }
276
366
  /** The folder Models and their base class live in: `--models`, or `src/models`. */
277
367
  function modelsDirOf(cwd, models = defaultModels) {
278
368
  const path = resolve(cwd, models);
279
- return oneModelsFile(models) ? dirname(path) : path;
369
+ return isOneModelsFile(models) ? dirname(path) : path;
280
370
  }
281
371
  /** The Model folder to watch, when it exists: `--models`'s, or the one holding its one file. */
282
372
  function modelsFolders(cwd, models = defaultModels) {
@@ -292,20 +382,17 @@ function sharedBase(targets) {
292
382
  seen.set(base.className, database.binding);
293
383
  }
294
384
  }
295
- /** The databases to generate, from the adapter's config and the options; or why there are none. */
296
- function targetsOf(adapter, cwd, options) {
297
- const config = adapter.databases();
298
- if (!config.ok) return config.error;
299
- const { databases, dir, file } = config;
385
+ /** The databases to generate, from the project's databases and the options; or why there are none. */
386
+ function targetsOf(project, cwd, options) {
387
+ const { databases } = project;
300
388
  if (options.migrations !== void 0 && databases.length > 1) return `--migrations needs a single database; this config has ${databases.length}`;
301
- const targets = databases.map((database) => {
302
- const migrationsDir = resolve(cwd, options.migrations ?? join(dir, database.migrationsDir));
389
+ const targets = databases.map((each) => {
390
+ const { database, configDir } = each;
391
+ const migrationsDir = resolve(cwd, options.migrations ?? join(configDir, database.migrationsDir));
303
392
  const out = databases.length === 1 ? resolve(cwd, options.out ?? "src/db/schema.ts") : resolve(cwd, options.out ?? "src/db", `${database.binding}.ts`);
304
393
  const base = baseFor(modelsDirOf(cwd, options.models), database.binding, databases.length > 1);
305
394
  return {
306
- database,
307
- configFile: file,
308
- configDir: dir,
395
+ ...each,
309
396
  migrationsDir,
310
397
  out,
311
398
  base
@@ -313,17 +400,22 @@ function targetsOf(adapter, cwd, options) {
313
400
  });
314
401
  return sharedBase(targets) ?? targets;
315
402
  }
316
- //#endregion
317
- //#region cli/project/load.ts
403
+ // cli/project/load.ts
318
404
  /**
319
405
  * A jiti based in the project: it reads TypeScript, extensionless imports and `tsconfig.json`
320
406
  * paths, and resolves the library (`@forestfuture/active-record` and its adapter's package)
321
407
  * from the project's `node_modules`, so the Models and the command share a single copy of it.
408
+ * What it compiles is cached by content in the project's `node_modules/.cache/jiti`, so a run
409
+ * after the first loads the library about ten times faster, and an edited file is compiled again
410
+ * (#251). Without `node_modules` it isn't cached: jiti would use the system's temporary folder,
411
+ * which on a shared machine another user could write compiled code into for this one to run.
322
412
  */
323
413
  function projectJiti(cwd) {
414
+ const modules = join(cwd, "node_modules");
415
+ const fsCache = existsSync(modules) ? join(modules, ".cache/jiti") : false;
324
416
  return createJiti(`${cwd}/`, {
325
417
  tsconfigPaths: true,
326
- fsCache: false,
418
+ fsCache,
327
419
  moduleCache: true
328
420
  });
329
421
  }
@@ -331,7 +423,7 @@ function projectJiti(cwd) {
331
423
  function modelFiles(cwd, models) {
332
424
  const path = resolve(cwd, models);
333
425
  if (!existsSync(path)) return `No Models at ${shown$1(cwd, path)} (run active-record g model, or pass --models)`;
334
- if (oneModelsFile(models) || statSync(path).isFile()) return [path];
426
+ if (isOneModelsFile(models) || statSync(path).isFile()) return [path];
335
427
  return readdirSync(path).filter((name) => name.endsWith(".ts") && !name.endsWith(".d.ts")).sort().map((name) => join(path, name));
336
428
  }
337
429
  /** The core, which every command loads from the project, beside the adapter some need. */
@@ -377,8 +469,7 @@ function forgetProjectFiles(cwd, jiti, keep) {
377
469
  if (name.startsWith(folder) && !name.includes("/node_modules/") && !keep.has(file)) delete jiti.cache[file];
378
470
  }
379
471
  }
380
- //#endregion
381
- //#region cli/console/project.ts
472
+ // cli/console/project.ts
382
473
  /** The Model classes the files export, by name; or the file that couldn't be loaded. */
383
474
  async function loadModels(cwd, jiti, files, library) {
384
475
  const found = {};
@@ -434,12 +525,14 @@ async function loadProject(adapterPackage, cwd, models = defaultModels) {
434
525
  };
435
526
  return project;
436
527
  }
437
- //#endregion
438
- //#region cli/console/session.ts
439
- /** A line that is just `quit` or `exit`: leaves the console, as `.exit` does. */
440
- const leaving = /^\s*(?:quit|exit)\s*;?\s*$/;
441
- /** A line that is just `name!`: one of the console's commands, as a bare word. */
442
- const bangLine = /^\s*([A-Za-z_]\w*)!\s*;?\s*$/;
528
+ // cli/console/session.ts
529
+ /**
530
+ * A line that is just `quit` or `exit`, once trimmed: leaves the console, as `.exit` does. Its
531
+ * spaces are trimmed first, as two `\s*` either side of `;?` backtrack polynomially.
532
+ */
533
+ const leaving = /^(?:quit|exit)(?:\s*;)?$/;
534
+ /** A line that is just `name!`, once trimmed: one of the console's commands, as a bare word. */
535
+ const bangLine = /^([A-Za-z_]\w*)!(?:\s*;)?$/;
443
536
  /**
444
537
  * Runs a task inside the project's database. While a line awaits, the REPL holds the next one back
445
538
  * and then runs it from inside that line's async context, where the database is already
@@ -549,7 +642,7 @@ function lineQueue() {
549
642
  ran.then(done);
550
643
  return;
551
644
  }
552
- if (leaving.test(code)) {
645
+ if (leaving.test(code.trim())) {
553
646
  stopped = true;
554
647
  server.close();
555
648
  return done();
@@ -604,7 +697,7 @@ function defineCommands(server, commands, lines, output) {
604
697
  }
605
698
  });
606
699
  return (line) => {
607
- const name = bangLine.exec(line)?.[1];
700
+ const name = bangLine.exec(line.trim())?.[1];
608
701
  return name !== void 0 && commands[name]?.bang ? runCommand(name, "") : void 0;
609
702
  };
610
703
  }
@@ -642,8 +735,7 @@ function startSession({ input, output, terminal = false, historyFile, prompt = "
642
735
  lines.attach(server, withDatabase, bang, script);
643
736
  return { closed: new Promise((resolve) => server.on("exit", () => void lines.pending().then(resolve))) };
644
737
  }
645
- //#endregion
646
- //#region cli/console/script.ts
738
+ // cli/console/script.ts
647
739
  /** A stream that collects what is written to it, as text. */
648
740
  function collecting(into) {
649
741
  return new Writable({ write(chunk, _encoding, done) {
@@ -699,8 +791,7 @@ async function runScript({ code, scope, commands, withDatabase, colors = {
699
791
  stderr
700
792
  };
701
793
  }
702
- //#endregion
703
- //#region cli/console/command.ts
794
+ // cli/console/command.ts
704
795
  /** Where the console reads and writes: the person's terminal. */
705
796
  function standardIo$1() {
706
797
  const terminal = process.stdin.isTTY === true && process.stdout.isTTY === true;
@@ -769,13 +860,11 @@ function runOnce(code, opened, io, errors) {
769
860
  }
770
861
  });
771
862
  }
772
- /** Everything that has to be true before a session starts, or why it isn't. */
773
- async function prepare(options, io) {
774
- const cwd = options.cwd ?? process.cwd();
775
- const adapter = await loadAdapter(cwd, options.config);
776
- if (typeof adapter === "string") return adapter;
777
- const chosen = chosenDatabase(adapter, cwd, options);
778
- if (typeof chosen === "string") return chosen;
863
+ /** Everything else that has to be true before a session starts, or why it isn't. */
864
+ async function prepare(loaded, cwd, options, io) {
865
+ const found = chosenDatabase(loaded, options);
866
+ if (typeof found === "string") return found;
867
+ const { adapter, chosen } = found;
779
868
  const project = await loadProject(adapterEntry(adapter), cwd, options.models);
780
869
  if (typeof project === "string") return project;
781
870
  const opened = await (options.remote === true ? openRemote(adapter, {
@@ -785,13 +874,12 @@ async function prepare(options, io) {
785
874
  if (typeof opened === "string") return opened;
786
875
  return {
787
876
  stateFolder: adapter.stateFolder(chosen),
788
- notes: configNotes(adapter),
789
877
  project,
790
878
  opened
791
879
  };
792
880
  }
793
881
  /** The session, or the one piece of code, on the open database; the exit code. */
794
- async function converse(options, { stateFolder, notes, project, opened }, { io, say, errors }) {
882
+ async function converse(options, { stateFolder, project, opened }, { io, say, errors }) {
795
883
  const scripted = options.eval !== void 0;
796
884
  const remote = options.remote === true;
797
885
  const { library, models } = project;
@@ -803,7 +891,6 @@ async function converse(options, { stateFolder, notes, project, opened }, { io,
803
891
  const database = library.connect(opened.binding, { onQuery });
804
892
  say(opened.description);
805
893
  say(`Models: ${Object.keys(models).join(", ")}`);
806
- for (const note of notes) say(note);
807
894
  const inside = {
808
895
  scope: {
809
896
  ...models,
@@ -829,7 +916,10 @@ async function converse(options, { stateFolder, notes, project, opened }, { io,
829
916
  async function runConsole(options, print, io = standardIo$1()) {
830
917
  const errors = io.error ?? process.stderr;
831
918
  const say = options.eval === void 0 ? print : (line) => void errors.write(`${line}\n`);
832
- const prepared = await prepare(options, io);
919
+ const cwd = options.cwd ?? process.cwd();
920
+ const loaded = await loadForCommand(cwd, options, say);
921
+ if (loaded === void 0) return 1;
922
+ const prepared = await prepare(loaded, cwd, options, io);
833
923
  if (typeof prepared === "string") return refused$1(say, prepared);
834
924
  let finished;
835
925
  let closing;
@@ -850,8 +940,7 @@ async function runConsole(options, print, io = standardIo$1()) {
850
940
  errors.write(finished.stderr);
851
941
  return finished.exitCode;
852
942
  }
853
- //#endregion
854
- //#region cli/console/flags.ts
943
+ // cli/console/flags.ts
855
944
  const options = {
856
945
  database: { type: "string" },
857
946
  models: { type: "string" },
@@ -903,8 +992,7 @@ const consoleSubcommand = defineSubcommand({
903
992
  return runConsole(consoleChoices(values), print);
904
993
  }
905
994
  });
906
- //#endregion
907
- //#region cli/plan.ts
995
+ // cli/plan.ts
908
996
  /** A line printed with no file. */
909
997
  function printed(line) {
910
998
  return { line };
@@ -960,8 +1048,7 @@ function apply(plan, cwd, print) {
960
1048
  }
961
1049
  return plan.code;
962
1050
  }
963
- //#endregion
964
- //#region cli/project/tools.ts
1051
+ // cli/project/tools.ts
965
1052
  const tools = ["Drizzle", "Prisma"];
966
1053
  /** Each tool's files in a project, and the marker it writes into its SQL. */
967
1054
  const signs = {
@@ -1010,8 +1097,7 @@ function toolsWithFiles(projectDir) {
1010
1097
  function migrationTool(toolsFound, migrations) {
1011
1098
  return tools.find((tool) => toolsFound.includes(tool) || migrations.some((migration) => signs[tool].marker.test(migration.sql)));
1012
1099
  }
1013
- //#endregion
1014
- //#region cli/project/snapshot.ts
1100
+ // cli/project/snapshot.ts
1015
1101
  /** A file's contents, or undefined when there's no such file. */
1016
1102
  function contents(path) {
1017
1103
  return existsSync(path) ? readFileSync(path, "utf8") : void 0;
@@ -1035,23 +1121,28 @@ function databaseSnapshot(target, toolsFound) {
1035
1121
  * Reads a project's databases from its config, and the other `files` a command needs
1036
1122
  * (a Model file, for `g model`); or why it can't, such as a missing config.
1037
1123
  */
1038
- function readProject(adapter, cwd, options, files = []) {
1039
- const targets = targetsOf(adapter, cwd, options);
1124
+ function readProject(project, cwd, options, files = []) {
1125
+ const targets = targetsOf(project, cwd, options);
1040
1126
  if (typeof targets === "string") return targets;
1041
- const toolsFound = targets.length === 0 ? [] : toolsWithFiles(targets[0].configDir);
1127
+ const toolsByFolder = /* @__PURE__ */ new Map();
1128
+ const toolsFor = ({ configDir }) => {
1129
+ const known = toolsByFolder.get(configDir);
1130
+ if (known !== void 0) return known;
1131
+ const found = toolsWithFiles(configDir);
1132
+ toolsByFolder.set(configDir, found);
1133
+ return found;
1134
+ };
1042
1135
  const read = files.flatMap((path) => {
1043
1136
  const text = contents(path);
1044
1137
  return text === void 0 ? [] : [[path, text]];
1045
1138
  });
1046
1139
  return {
1047
- adapter,
1048
1140
  cwd,
1049
- databases: targets.map((target) => databaseSnapshot(target, toolsFound)),
1141
+ databases: targets.map((target) => databaseSnapshot(target, toolsFor(target))),
1050
1142
  files: new Map(read)
1051
1143
  };
1052
1144
  }
1053
- //#endregion
1054
- //#region cli/source.ts
1145
+ // cli/source.ts
1055
1146
  /**
1056
1147
  * Text as a string literal in generated TypeScript, quotes and backslashes escaped: for values
1057
1148
  * that come from a project's config or paths (#85).
@@ -1061,13 +1152,12 @@ function stringLiteral(text) {
1061
1152
  }
1062
1153
  /** A double-quoted string literal in generated source, read back: `stringLiteral`'s pattern. */
1063
1154
  const stringLiteralPattern = String.raw`"(?:[^"\\]|\\.)*"`;
1064
- //#endregion
1065
- //#region cli/schema/render.ts
1155
+ // cli/schema/render.ts
1066
1156
  /**
1067
1157
  * The generated file's format. Bump it when the output changes, so `--check` reports files an
1068
1158
  * older version of the command wrote (its fingerprint covers the format as well as the schema).
1069
1159
  */
1070
- const format = 6;
1160
+ const format = 7;
1071
1161
  /**
1072
1162
  * An object key: bare when it's an identifier, quoted otherwise (`"first name"`). `__proto__` is
1073
1163
  * computed, since in an object literal a bare or quoted one sets the prototype and the key is
@@ -1091,6 +1181,20 @@ function defaultSource(value) {
1091
1181
  const source = valueSource(value.literal);
1092
1182
  return `() => ${source.startsWith("{") ? `(${source})` : source}`;
1093
1183
  }
1184
+ /** A generated enum's names, and the switches that keep its methods off until an override (#64). */
1185
+ function generatedEnumSource(spec) {
1186
+ const parts = [`enum: ${valueSource(spec.enum)}`];
1187
+ if (spec.scopes === false) parts.push("scopes: false");
1188
+ if (spec.instanceMethods === false) parts.push("instanceMethods: false");
1189
+ return parts;
1190
+ }
1191
+ /** A decimal's precision and scale, as its spec writes them (#398). */
1192
+ function digitsSource({ precision, scale }) {
1193
+ const parts = [];
1194
+ if (precision !== void 0) parts.push(`precision: ${precision}`);
1195
+ if (scale !== void 0) parts.push(`scale: ${scale}`);
1196
+ return parts;
1197
+ }
1094
1198
  /** An attribute's spec: just its type when that's all it has, as Models are written by hand. */
1095
1199
  function specSource(spec) {
1096
1200
  const parts = [`type: ${JSON.stringify(spec.type)}`];
@@ -1098,6 +1202,8 @@ function specSource(spec) {
1098
1202
  if (spec.column !== void 0) parts.push(`column: ${JSON.stringify(spec.column)}`);
1099
1203
  if (spec.default !== void 0) parts.push(`default: ${defaultSource(spec.default)}`);
1100
1204
  if (spec.generateId) parts.push("generateId: true");
1205
+ parts.push(...digitsSource(spec));
1206
+ if (spec.enum !== void 0) parts.push(...generatedEnumSource(spec));
1101
1207
  return parts.length === 1 ? JSON.stringify(spec.type) : `{ ${parts.join(", ")} }`;
1102
1208
  }
1103
1209
  /** Text safe inside a `/** … *\/` comment. */
@@ -1113,7 +1219,23 @@ ${attributes}
1113
1219
  }
1114
1220
  /** A short hash of the schema itself, so `--check` ignores how the file is formatted. */
1115
1221
  function fingerprintOf({ adapter, tables, binding, models }) {
1116
- const listed = byName(models, (model) => model.className);
1222
+ const listed = byName(models, (model) => model.className).map((model) => {
1223
+ const { className, table, module, enumScopes = [] } = model;
1224
+ const modelName = listedName(model);
1225
+ const scopes = enumScopes.length === 0 ? {} : { enumScopes };
1226
+ return modelName === className ? {
1227
+ className,
1228
+ table,
1229
+ module,
1230
+ ...scopes
1231
+ } : {
1232
+ className,
1233
+ modelName,
1234
+ table,
1235
+ module,
1236
+ ...scopes
1237
+ };
1238
+ });
1117
1239
  return createHash("sha256").update(JSON.stringify({
1118
1240
  format,
1119
1241
  adapter,
@@ -1122,31 +1244,43 @@ function fingerprintOf({ adapter, tables, binding, models }) {
1122
1244
  models: listed
1123
1245
  })).digest("hex").slice(0, 12);
1124
1246
  }
1247
+ /** The name the schema lists a Model by: its `modelName`, or else its class name. */
1248
+ function listedName(model) {
1249
+ return model.modelName ?? model.className;
1250
+ }
1125
1251
  /** Items sorted by a name, as `localeCompare` doesn't: the same on every machine. */
1126
1252
  function byName(items, name) {
1127
1253
  return [...items].sort((a, b) => name(a) < name(b) ? -1 : name(a) > name(b) ? 1 : 0);
1128
1254
  }
1129
- /** The Models' entries as an object: on one line, or one a line when that would be too long. */
1130
- function modelsSource(entries) {
1255
+ /** The entries of the schema's `key` as an object: on one line, or one a line when that would be too long. */
1256
+ function objectSource(entries, key) {
1131
1257
  const line = entries.length === 0 ? "{}" : `{ ${entries.join(", ")} }`;
1132
- if (` models: ${line},`.length <= 100) return line;
1258
+ if (` ${key}: ${line},`.length <= 100) return line;
1133
1259
  return `{\n${entries.map((entry) => ` ${entry},`).join("\n")}\n }`;
1134
1260
  }
1135
- /** The `schema` value: its adapter and binding, every table by name, and every Model's table by class. */
1261
+ /** Each Model's enum scopes, by the name it's listed by, if any has some (#340). */
1262
+ function enumScopesSource(models) {
1263
+ const entries = byName(models, listedName).filter((model) => (model.enumScopes ?? []).length > 0).map((model) => `${keySource(listedName(model))}: ${valueSource(model.enumScopes)}`);
1264
+ return entries.length === 0 ? "" : `\n enumScopes: ${objectSource(entries, "enumScopes")},`;
1265
+ }
1266
+ /**
1267
+ * The `schema` value: its adapter and binding, every table by name, every Model's table by
1268
+ * modelName, and their enum scopes, through `defineSchema`, which makes those statics (#340).
1269
+ */
1136
1270
  function schemaValueSource({ adapter, tables, binding, models }) {
1137
1271
  const entries = tables.map((table) => {
1138
1272
  const primaryKey = JSON.stringify(table.primaryKey);
1139
1273
  return ` ${keySource(table.name)}: { attributes: ${table.exportName}, primaryKey: ${primaryKey} },`;
1140
1274
  }).join("\n");
1141
- const listed = byName(models, (model) => model.className).map((model) => `${keySource(model.className)}: ${JSON.stringify(model.table)}`);
1275
+ const listed = byName(models, listedName).map((model) => `${keySource(listedName(model))}: ${JSON.stringify(model.table)}`);
1142
1276
  return `/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
1143
- export const schema = {
1277
+ export const schema = defineSchema({
1144
1278
  adapter: ${adapter.factory}({ binding: ${stringLiteral(binding)} }),
1145
1279
  tables: {
1146
1280
  ${entries}
1147
1281
  },
1148
- models: ${modelsSource(listed)},
1149
- } as const;`;
1282
+ models: ${objectSource(listed, "models")},${enumScopesSource(models)}
1283
+ });`;
1150
1284
  }
1151
1285
  /** A Model's declaration: its class, with its table's attributes after its own overrides. */
1152
1286
  function interfaceSource(model, exportName) {
@@ -1155,13 +1289,24 @@ function interfaceSource(model, exportName) {
1155
1289
  const line = ` interface ${name} ${heritage}`;
1156
1290
  return line.length <= 100 ? line : ` interface ${name}\n ${heritage}`;
1157
1291
  }
1292
+ /** A Model's enum scopes as statics, typed (#340): a namespace merged with its class. */
1293
+ function namespaceLines(model) {
1294
+ const scopes = model.enumScopes ?? [];
1295
+ if (scopes.length === 0) return [];
1296
+ const statics = scopes.map((scope) => ` export const ${scope}: ScopeStatic<[]>;`);
1297
+ return [
1298
+ ` namespace ${model.className} {`,
1299
+ ...statics,
1300
+ " }"
1301
+ ];
1302
+ }
1158
1303
  /** One `declare module` block per Model file, adding each class's attributes to it. */
1159
1304
  function declarationsSource({ tables, models }) {
1160
1305
  const exportNames = new Map(tables.map((table) => [table.name, table.exportName]));
1161
1306
  const modules = /* @__PURE__ */ new Map();
1162
1307
  for (const model of byName(models, (each) => each.className)) modules.set(model.module, [...modules.get(model.module) ?? [], model]);
1163
1308
  return byName([...modules], ([module]) => module).map(([module, inModule]) => {
1164
- const lines = inModule.map((model) => interfaceSource(model, exportNames.get(model.table)));
1309
+ const lines = inModule.flatMap((model) => [interfaceSource(model, exportNames.get(model.table)), ...namespaceLines(model)]);
1165
1310
  return `declare module ${stringLiteral(module)} {\n${lines.join("\n")}\n}`;
1166
1311
  }).join("\n\n");
1167
1312
  }
@@ -1172,7 +1317,11 @@ function declarationsSource({ tables, models }) {
1172
1317
  */
1173
1318
  function renderSchema(schema, source) {
1174
1319
  const hasModels = schema.models.length > 0;
1175
- const imports = (hasModels ? "import type { TableAttributes } from \"@forestfuture/active-record\";\n" : "") + `import { ${schema.adapter.factory} } from ${stringLiteral(schema.adapter.from)};\n\n`;
1320
+ const imports = `import { ${[
1321
+ "defineSchema",
1322
+ ...schema.models.some((model) => (model.enumScopes ?? []).length > 0) ? ["type ScopeStatic"] : [],
1323
+ ...hasModels ? ["type TableAttributes"] : []
1324
+ ].join(", ")} } from "@forestfuture/active-record";\nimport { ${schema.adapter.factory} } from ${stringLiteral(schema.adapter.from)};\n\n`;
1176
1325
  const declarations = hasModels ? `\n\n${declarationsSource(schema)}` : "";
1177
1326
  return `// Generated by \`active-record schema\` from ${source} — don't edit.
1178
1327
  // schema: ${fingerprintOf(schema)}
@@ -1241,8 +1390,7 @@ export abstract class ${className} extends Model {
1241
1390
  function fingerprintIn(source) {
1242
1391
  return /^\/\/ schema: ([0-9a-f]{12})$/m.exec(source)?.[1];
1243
1392
  }
1244
- //#endregion
1245
- //#region cli/schema/origin.ts
1393
+ // cli/schema/origin.ts
1246
1394
  const issue = "https://github.com/forestfuture/active-record/issues/73";
1247
1395
  /** Column names (as snake_case words) that suggest a `TEXT` column holds JSON. */
1248
1396
  const jsonish = /(^|_)(json|metadata|settings|payload|properties)$/;
@@ -1284,8 +1432,7 @@ function originNotes(tool, tables, textDates) {
1284
1432
  ...textDates.map(textDateNote)
1285
1433
  ];
1286
1434
  }
1287
- //#endregion
1288
- //#region cli/schema/writes.ts
1435
+ // cli/schema/writes.ts
1289
1436
  /** The app's base class for the database (`ApplicationRecord`), when it's missing; never over it. */
1290
1437
  function baseWrites(cwd, db) {
1291
1438
  const { target } = db;
@@ -1316,15 +1463,17 @@ function schemaAdapterOf(adapter) {
1316
1463
  };
1317
1464
  }
1318
1465
  /** What a database's schema is rendered from: its adapter, tables and binding, and the Models found. */
1319
- function schemaSourceOf(project, db, tables) {
1466
+ function schemaSourceOf(db, tables) {
1320
1467
  const { target } = db;
1321
- const models = db.models.map(({ className, table, file }) => ({
1468
+ const models = db.models.map(({ className, modelName, table, file, enumScopes }) => ({
1322
1469
  className,
1470
+ modelName,
1323
1471
  table,
1324
- module: importPath(dirname(target.out), file)
1472
+ module: importPath(dirname(target.out), file),
1473
+ enumScopes
1325
1474
  }));
1326
1475
  return {
1327
- adapter: schemaAdapterOf(project.adapter),
1476
+ adapter: schemaAdapterOf(target.adapter),
1328
1477
  tables,
1329
1478
  binding: target.database.binding,
1330
1479
  models
@@ -1339,9 +1488,9 @@ function schemaWrites(project, db, result) {
1339
1488
  const { target } = db;
1340
1489
  const out = shown$1(cwd, target.out);
1341
1490
  const source = `${shown$1(cwd, target.migrationsDir)}/`;
1342
- const rendered = renderSchema(schemaSourceOf(project, db, result.tables), source);
1491
+ const rendered = renderSchema(schemaSourceOf(db, result.tables), source);
1343
1492
  const count = `${result.tables.length} table${result.tables.length === 1 ? "" : "s"}`;
1344
- const setting = project.adapter.patternSetting;
1493
+ const setting = target.adapter.patternSetting;
1345
1494
  const notes = db.nestedMigrations ? [layoutNote(cwd, target, setting)] : [];
1346
1495
  const steps = [];
1347
1496
  if (rendered === db.schema) steps.push({ line: `${out} is up to date (${count})` });
@@ -1359,8 +1508,7 @@ function schemaWrites(project, db, result) {
1359
1508
  code: 0
1360
1509
  };
1361
1510
  }
1362
- //#endregion
1363
- //#region cli/schema/models.ts
1511
+ // cli/schema/models.ts
1364
1512
  /**
1365
1513
  * Writes a schema file that's missing, for while the Models load: an import finds a module only
1366
1514
  * when its file exists. The plan writes the real one. Returns its path, to remove afterwards.
@@ -1380,13 +1528,13 @@ async function freshSchemas(jiti, project, placeholders) {
1380
1528
  for (const db of project.databases) {
1381
1529
  const { database, out } = db.target;
1382
1530
  const { migrationsTable, entry } = database;
1383
- const result = await project.adapter.readSchema(db.migrations ?? [], {
1531
+ const result = await db.target.adapter.readSchema(db.migrations ?? [], {
1384
1532
  migrationsTable,
1385
1533
  entry
1386
1534
  });
1387
1535
  if (db.migrations === void 0 || !result.ok) continue;
1388
1536
  const source = renderSchema({
1389
- adapter: schemaAdapterOf(project.adapter),
1537
+ adapter: schemaAdapterOf(db.target.adapter),
1390
1538
  tables: result.tables,
1391
1539
  binding: database.binding,
1392
1540
  models: []
@@ -1407,11 +1555,48 @@ function databaseOf(value, schemas) {
1407
1555
  return holder === void 0 ? void 0 : schemas.get(holder.schema);
1408
1556
  }
1409
1557
  /** Whether `file` declares the class itself, rather than exporting it from another file. */
1410
- function declares(file, name) {
1558
+ function isDeclaredIn(file, name) {
1411
1559
  return new RegExp(`\\bclass\\s+${name}\\b`).test(readFileSync(file, "utf8"));
1412
1560
  }
1561
+ /**
1562
+ * What's wrong with a Model's `modelName`, which the schema lists it by, if anything: one that
1563
+ * isn't a string, or one another Model found already has.
1564
+ */
1565
+ function modelNameProblem(cwd, found, { model, database }) {
1566
+ if (typeof model.modelName !== "string") return `${model.name}'s modelName must be a string; remove it to use the class name`;
1567
+ for (const [other, each] of found.models) {
1568
+ const sameDatabase = found.databases.get(other) === database;
1569
+ if (other !== model && sameDatabase && each.modelName === model.modelName) return `${model.name} and ${each.className} (${shown$1(cwd, each.file)}) both have the modelName ${model.modelName}; give each Model its own`;
1570
+ }
1571
+ }
1572
+ /**
1573
+ * The names a Model's enum methods mustn't take (#340), from the project's own library: a record
1574
+ * method, a Model static (which the Relation methods are too), or a static the app declares.
1575
+ * Its enum scopes aren't defined yet while the schema is generated, so any static is the app's.
1576
+ */
1577
+ function takenNames(model, library) {
1578
+ const base = library.Model;
1579
+ return {
1580
+ isRecordName: (name) => name in base.prototype,
1581
+ isReservedStatic: (name) => name === "then" || name in library.Relation.prototype || name in base,
1582
+ staticOf: (name) => staticBelow(model, base, name)
1583
+ };
1584
+ }
1585
+ /**
1586
+ * A Model's enum scopes, read from its attributes as overridden, or why they can't be: an
1587
+ * override that isn't one, or an enum whose method names clash (#340).
1588
+ */
1589
+ function enumScopesOf({ model, library }) {
1590
+ try {
1591
+ const scopes = enumScopeNames(model.attributeDefinitions);
1592
+ return enumNameProblem(model, takenNames(model, library), methodsOffFixes(model)) ?? scopes;
1593
+ } catch (error) {
1594
+ return error.message;
1595
+ }
1596
+ }
1413
1597
  /** Adds a class from `file` if it's a Model directly below a base: one whose table it is. */
1414
- function addModel(cwd, file, { name, model }, found) {
1598
+ function addModel(cwd, file, exported, found) {
1599
+ const { name, model } = exported;
1415
1600
  if (isBase(model) || !isBase(Object.getPrototypeOf(model))) return;
1416
1601
  if (name === "default") {
1417
1602
  found.errors.push(`${shown$1(cwd, file)} exports ${model.name} as its default; export it by name (export class ${model.name} …), so active-record schema can add its attributes`);
@@ -1421,18 +1606,25 @@ function addModel(cwd, file, { name, model }, found) {
1421
1606
  found.errors.push(`${shown$1(cwd, file)} exports a Model named ${JSON.stringify(model.name)}, which isn't a name active-record schema can write as code; name the class with letters, digits, _ and \$`);
1422
1607
  return;
1423
1608
  }
1424
- if (found.models.get(model) !== void 0 && !declares(file, model.name)) return;
1425
- try {
1426
- model.attributeDefinitions;
1427
- } catch (error) {
1428
- found.errors.push(`${shown$1(cwd, file)}: ${error.message}`);
1609
+ if (found.models.get(model) !== void 0 && !isDeclaredIn(file, model.name)) return;
1610
+ const problem = modelNameProblem(cwd, found, exported);
1611
+ if (problem !== void 0) {
1612
+ found.errors.push(`${shown$1(cwd, file)}: ${problem}`);
1613
+ return;
1614
+ }
1615
+ const enumScopes = enumScopesOf(exported);
1616
+ if (typeof enumScopes === "string") {
1617
+ found.errors.push(`${shown$1(cwd, file)}: ${enumScopes}`);
1429
1618
  return;
1430
1619
  }
1431
1620
  found.models.set(model, {
1432
1621
  className: model.name,
1622
+ modelName: model.modelName,
1433
1623
  table: model.table,
1434
- file
1624
+ file,
1625
+ ...enumScopes.length === 0 ? {} : { enumScopes }
1435
1626
  });
1627
+ found.databases.set(model, exported.database);
1436
1628
  }
1437
1629
  /** Imports a Model file, or says why it couldn't be loaded. */
1438
1630
  async function importFile(cwd, jiti, file) {
@@ -1445,15 +1637,21 @@ async function importFile(cwd, jiti, file) {
1445
1637
  }
1446
1638
  /** Adds the Models a file exports that are built on a schema being generated. */
1447
1639
  function addExported(cwd, file, exported, context) {
1448
- for (const [name, value] of Object.entries(exported)) if (typeof value === "function" && value.prototype instanceof context.library.Model && databaseOf(value, context.schemas) !== void 0) addModel(cwd, file, {
1449
- name,
1450
- model: value
1451
- }, context.found);
1640
+ for (const [name, value] of Object.entries(exported)) {
1641
+ const database = typeof value === "function" && value.prototype instanceof context.library.Model ? databaseOf(value, context.schemas) : void 0;
1642
+ if (database !== void 0) addModel(cwd, file, {
1643
+ name,
1644
+ model: value,
1645
+ database,
1646
+ library: context.library
1647
+ }, context.found);
1648
+ }
1452
1649
  }
1453
1650
  /** Loads the Model files, finding the Models built on the schemas being generated. */
1454
1651
  async function modelsIn(cwd, jiti, files, schemas) {
1455
1652
  const found = {
1456
1653
  models: /* @__PURE__ */ new Map(),
1654
+ databases: /* @__PURE__ */ new Map(),
1457
1655
  errors: []
1458
1656
  };
1459
1657
  const library = await loadLibrary(cwd, jiti, {
@@ -1508,52 +1706,100 @@ async function withModels(project, { models = defaultModels, check = false } = {
1508
1706
  forgetProjectFiles(cwd, jiti, loadedBefore);
1509
1707
  }
1510
1708
  }
1511
- //#endregion
1512
- //#region cli/generate/columns.ts
1709
+ // cli/generate/columns.ts
1513
1710
  const types$1 = [
1514
1711
  "string",
1515
1712
  "integer",
1516
1713
  "real",
1714
+ "decimal",
1517
1715
  "boolean",
1518
1716
  "datetime",
1717
+ "date",
1718
+ "time",
1519
1719
  "json",
1720
+ "binary",
1520
1721
  "references"
1521
1722
  ];
1522
- const syntax = /^([A-Za-z_]\w*)(?::(?!(?:unique|index)\b)(\w+))?(!)?(?:=(.*?))?((?::(?:unique|index))*)$/;
1723
+ /** The types, as a message lists them: `string, integer, … or references`. */
1724
+ const typeList = `${types$1.slice(0, -1).join(", ")} or ${types$1.at(-1)}`;
1725
+ const syntax = /^([A-Za-z_]\w*)(?::(?!(?:unique|index)\b)(\w+)(?:\{(\d+)(?:,(\d+))?\})?)?(!)?(?:=(.*?))?((?::(?:unique|index))*)$/;
1726
+ /** A decimal's, a date's or a time's default, in its one form (`1.50` → `"1.5"`, #391). */
1727
+ const castParser = (type) => (value, digits) => {
1728
+ const cast = castDefault(type, value, digits);
1729
+ if (cast !== void 0) return {
1730
+ ok: true,
1731
+ value: cast.literal
1732
+ };
1733
+ return {
1734
+ ok: false,
1735
+ error: defaultRefusal(type, value, digits)
1736
+ };
1737
+ };
1738
+ /**
1739
+ * Why a default can't be cast: past a decimal's precision, when it's a decimal at its scale
1740
+ * without the precision; else that it isn't one (rounding can carry it past a double, too).
1741
+ */
1742
+ function defaultRefusal(type, value, digits) {
1743
+ const scaled = {
1744
+ ...digits,
1745
+ precision: void 0,
1746
+ scale: digits.scale ?? 0
1747
+ };
1748
+ if (digits.precision === void 0 || castDefault(type, value, scaled) === void 0) return `${value} isn't a ${type}`;
1749
+ return `${value} has more digits before the point than decimal{${[digits.precision, digits.scale].filter((digit) => digit !== void 0).join(",")}} holds`;
1750
+ }
1751
+ /** How each type that can have a default reads a `=value` as its literal. */
1752
+ const defaultParsers = {
1753
+ string: (value) => ({
1754
+ ok: true,
1755
+ value
1756
+ }),
1757
+ boolean: (value) => value === "true" || value === "false" ? {
1758
+ ok: true,
1759
+ value: value === "true"
1760
+ } : {
1761
+ ok: false,
1762
+ error: `${value} isn't true or false`
1763
+ },
1764
+ integer: (value) => /^-?\d+$/.test(value) && Number.isSafeInteger(Number(value)) ? {
1765
+ ok: true,
1766
+ value: Number(value)
1767
+ } : {
1768
+ ok: false,
1769
+ error: `${value} isn't an integer`
1770
+ },
1771
+ real: (value) => /^-?\d+(\.\d+)?$/.test(value) ? {
1772
+ ok: true,
1773
+ value: Number(value)
1774
+ } : {
1775
+ ok: false,
1776
+ error: `${value} isn't a number`
1777
+ },
1778
+ decimal: castParser("decimal"),
1779
+ date: castParser("date"),
1780
+ time: castParser("time")
1781
+ };
1782
+ /** The types that can have a default, as a message lists them: `string, integer, … and time`. */
1783
+ const defaultTypes = types$1.filter((type) => defaultParsers[type] !== void 0);
1784
+ const defaultTypeList = `${defaultTypes.slice(0, -1).join(", ")} and ${defaultTypes.at(-1)}`;
1523
1785
  /** A `=value` default as its type's literal, or why it can't be one. */
1524
- function defaultOf(type, value) {
1525
- const number = Number(value);
1526
- switch (type) {
1527
- case "string": return {
1528
- ok: true,
1529
- value
1530
- };
1531
- case "boolean": return value === "true" || value === "false" ? {
1532
- ok: true,
1533
- value: value === "true"
1534
- } : {
1535
- ok: false,
1536
- error: `${value} isn't true or false`
1537
- };
1538
- case "integer": return /^-?\d+$/.test(value) && Number.isSafeInteger(number) ? {
1539
- ok: true,
1540
- value: number
1541
- } : {
1542
- ok: false,
1543
- error: `${value} isn't an integer`
1544
- };
1545
- case "real": return /^-?\d+(\.\d+)?$/.test(value) ? {
1546
- ok: true,
1547
- value: number
1548
- } : {
1549
- ok: false,
1550
- error: `${value} isn't a number`
1551
- };
1552
- default: return {
1553
- ok: false,
1554
- error: "only string, integer, real and boolean columns can have a default here"
1555
- };
1556
- }
1786
+ function defaultOf(type, value, digits) {
1787
+ const parse = defaultParsers[type];
1788
+ return parse === void 0 ? {
1789
+ ok: false,
1790
+ error: `only ${defaultTypeList} columns can have a default here`
1791
+ } : parse(value, digits);
1792
+ }
1793
+ /** A column's `{precision,scale}`, which only a decimal takes, or why it can't have them (#398). */
1794
+ function digitsOf(type, precision, scale) {
1795
+ if (precision === void 0) return {};
1796
+ if (type !== "decimal") return "only a decimal takes a precision and scale, as decimal{10,2}";
1797
+ const digits = {
1798
+ precision: Number(precision),
1799
+ ...scale !== void 0 && { scale: Number(scale) }
1800
+ };
1801
+ const problem = digitsProblem(digits);
1802
+ return problem === void 0 ? digits : `it has ${problem}`;
1557
1803
  }
1558
1804
  /** The index `:unique` or `:index` asks for. */
1559
1805
  function indexOf(modifiers) {
@@ -1564,11 +1810,13 @@ function indexOf(modifiers) {
1564
1810
  function parseColumn(arg) {
1565
1811
  const match = syntax.exec(arg);
1566
1812
  if (match === null) return `${arg}: write a column as name:type, with ! for NOT NULL, =value for a default, and :unique or :index`;
1567
- const [, given, typeName = "string", bang, value, indexes = ""] = match;
1813
+ const [, given, typeName = "string", precision, scale, bang, value, indexes = ""] = match;
1568
1814
  const type = typeName;
1569
- if (!types$1.includes(type)) return `${arg}: ${typeName} isn't a type; use string, integer, real, boolean, datetime, json or references`;
1815
+ if (!types$1.includes(type)) return `${arg}: ${typeName} isn't a type; use ${typeList}`;
1570
1816
  const name = underscore(given);
1571
1817
  const index = indexOf(indexes);
1818
+ const digits = digitsOf(type, precision, scale);
1819
+ if (typeof digits === "string") return `${arg}: ${digits}`;
1572
1820
  if (type === "references") {
1573
1821
  const association = camelize(name);
1574
1822
  return {
@@ -1584,10 +1832,11 @@ function parseColumn(arg) {
1584
1832
  name,
1585
1833
  type,
1586
1834
  notNull: bang !== void 0,
1587
- index
1835
+ index,
1836
+ ...digits
1588
1837
  };
1589
1838
  if (value === void 0) return column;
1590
- const literal = defaultOf(type, value);
1839
+ const literal = defaultOf(type, value, digits);
1591
1840
  return literal.ok ? {
1592
1841
  ...column,
1593
1842
  default: literal.value
@@ -1605,8 +1854,7 @@ function parseColumns(args) {
1605
1854
  columns: parsed
1606
1855
  };
1607
1856
  }
1608
- //#endregion
1609
- //#region cli/generate/model-file.ts
1857
+ // cli/generate/model-file.ts
1610
1858
  const library = "@forestfuture/active-record";
1611
1859
  /** A Model's file name: its class name in kebab-case (`LineItem` → `line-item.ts`). */
1612
1860
  function modelFileName(className) {
@@ -1674,8 +1922,7 @@ function appendModel(existing, model) {
1674
1922
  source: `${(model.associations.length > 0 ? importingBelongsTo(imported.source) : imported.source).trimEnd()}\n\n${classSource(model)}`
1675
1923
  };
1676
1924
  }
1677
- //#endregion
1678
- //#region cli/generate/migration-file.ts
1925
+ // cli/generate/migration-file.ts
1679
1926
  /** `20261108090503`: the UTC second, as 14 digits. */
1680
1927
  function stamp(now) {
1681
1928
  return Number(now.toISOString().slice(0, 19).replaceAll(/\D/g, ""));
@@ -1690,8 +1937,7 @@ function migrationFileName(existing, name, now) {
1690
1937
  const version = Math.max(stamp(now), highest + 1);
1691
1938
  return `${String(version).padStart(14, "0")}_${underscore(name)}.sql`;
1692
1939
  }
1693
- //#endregion
1694
- //#region cli/generate/names.ts
1940
+ // cli/generate/names.ts
1695
1941
  /** A name the generators accept: letters, digits and `_`, starting with a letter. */
1696
1942
  const allowed$1 = /^[A-Za-z][A-Za-z0-9_]*$/;
1697
1943
  /**
@@ -1717,8 +1963,7 @@ function modelName(given) {
1717
1963
  function migrationNameError(given) {
1718
1964
  return allowed$1.test(given) ? void 0 : `${given} isn't a migration name; use letters, digits and _, like AddSkuToProducts`;
1719
1965
  }
1720
- //#endregion
1721
- //#region cli/generate/command.ts
1966
+ // cli/generate/command.ts
1722
1967
  /** A refusal: these errors, then "Wrote nothing". */
1723
1968
  function refused(...errors) {
1724
1969
  return printing([...errors, "Wrote nothing"], 1);
@@ -1746,7 +1991,7 @@ function patternRefusal({ project, db }, path) {
1746
1991
  const pattern = target.database.migrationsPattern;
1747
1992
  const relativePath = slashed(relative(target.configDir, path));
1748
1993
  if (pattern === void 0 || process.getBuiltinModule("node:path").matchesGlob(relativePath, pattern)) return;
1749
- return `${shown$1(project.cwd, path)} wouldn't match ${project.adapter.patternSetting ?? "the pattern"} (${pattern}) in ${shown$1(project.cwd, target.configFile)}, so it wouldn't be applied; write the migration with your migration tool instead`;
1994
+ return `${shown$1(project.cwd, path)} wouldn't match ${target.adapter.patternSetting ?? "the pattern"} (${pattern}) in ${shown$1(project.cwd, target.configFile)}, so it wouldn't be applied; write the migration with your migration tool instead`;
1750
1995
  }
1751
1996
  /**
1752
1997
  * Each table's key column's type, for the columns that reference it: as the adapter read it, or
@@ -1761,7 +2006,7 @@ function keyTypes(tables) {
1761
2006
  /** Where `g model` writes a Model: its own file, or the one file Models are appended to. */
1762
2007
  function modelPathOf(cwd, options, className) {
1763
2008
  const models = options.models ?? "src/models";
1764
- return resolve(cwd, models, oneModelsFile(models) ? "" : modelFileName(className));
2009
+ return resolve(cwd, models, isOneModelsFile(models) ? "" : modelFileName(className));
1765
2010
  }
1766
2011
  /** The Model `g model` writes, and where (its own file, or appended to one); or why it can't. */
1767
2012
  function modelFile(request) {
@@ -1769,7 +2014,7 @@ function modelFile(request) {
1769
2014
  const { cwd } = project;
1770
2015
  const { target } = db;
1771
2016
  const className = request.className;
1772
- const separateFiles = !oneModelsFile(options.models ?? "src/models");
2017
+ const separateFiles = !isOneModelsFile(options.models ?? "src/models");
1773
2018
  const path = modelPathOf(cwd, options, className);
1774
2019
  const model = {
1775
2020
  className,
@@ -1798,9 +2043,9 @@ function modelFile(request) {
1798
2043
  }
1799
2044
  /** The migration, checked by applying it after the others in memory; or why it was refused. */
1800
2045
  async function checkedMigration(request, existing) {
1801
- const { project, db, options, columns } = request;
1802
- const { adapter } = project;
2046
+ const { db, options, columns } = request;
1803
2047
  const { target } = db;
2048
+ const { adapter } = target;
1804
2049
  const { migrationsTable, entry } = target.database;
1805
2050
  const current = await adapter.readSchema(existing, {
1806
2051
  migrationsTable,
@@ -1926,15 +2171,11 @@ async function planGenerate(project, options) {
1926
2171
  async function runGenerate(options, print) {
1927
2172
  const cwd = resolve(options.cwd ?? process.cwd());
1928
2173
  const { config, models, out } = options;
1929
- const adapter = await loadAdapter(cwd, options.config);
1930
- if (typeof adapter === "string") {
1931
- print(adapter);
1932
- return 1;
1933
- }
1934
- for (const note of configNotes(adapter)) print(note);
2174
+ const loaded = await loadForCommand(cwd, options, print);
2175
+ if (loaded === void 0) return 1;
1935
2176
  const model = options.kind === "model" ? modelName(options.name) : void 0;
1936
2177
  const files = model?.ok === true ? [modelPathOf(cwd, options, model.className)] : [];
1937
- const read = readProject(adapter, cwd, {
2178
+ const read = readProject(loaded, cwd, {
1938
2179
  config,
1939
2180
  models,
1940
2181
  out
@@ -1945,8 +2186,7 @@ async function runGenerate(options, print) {
1945
2186
  }
1946
2187
  return apply(await planGenerate(await withModels(read, { models }), options), cwd, print);
1947
2188
  }
1948
- //#endregion
1949
- //#region cli/generate/flags.ts
2189
+ // cli/generate/flags.ts
1950
2190
  /** `active-record g model …` and `active-record g migration …`. */
1951
2191
  const generateSubcommand = defineSubcommand({
1952
2192
  options: {
@@ -1984,8 +2224,7 @@ datetime, json or references; then ! for NOT NULL, =value for a default, and :un
1984
2224
  }, print);
1985
2225
  }
1986
2226
  });
1987
- //#endregion
1988
- //#region cli/init/insert.ts
2227
+ // cli/init/insert.ts
1989
2228
  /** Just past the comment starting at `index`, or `index` when none starts there. */
1990
2229
  function pastComment(text, index) {
1991
2230
  if (text.startsWith("//", index)) {
@@ -2111,8 +2350,7 @@ function withEntries(text, entries) {
2111
2350
  const added = trailing ? lines.map((line) => `${line},`).join("") : lines.join(",");
2112
2351
  return `${text.slice(0, last.end)}${trailing ? "" : ","}${text.slice(last.end, after)}${added}${text.slice(after)}`;
2113
2352
  }
2114
- //#endregion
2115
- //#region cli/init/command.ts
2353
+ // cli/init/command.ts
2116
2354
  /** The JSON Schema the package ships for the file, which editors complete its keys from. */
2117
2355
  const schemaFile = "config-schema.json";
2118
2356
  /** The core package as the nearest `node_modules` holds it, or as the project's own will. */
@@ -2151,7 +2389,7 @@ async function foundEntries(dir) {
2151
2389
  }
2152
2390
  if (found.length === 1) return found[0];
2153
2391
  if (found.length === 0) return `Nothing here says which database the project uses; choose ${listed(adapterNames)} with --adapter`;
2154
- return `This project could use ${listed(found.map((each) => each.name))}; choose one with --adapter`;
2392
+ return `This project could use ${listed(found.map((each) => each.name))}; choose one with --adapter, then run init again with the other to add its databases too`;
2155
2393
  }
2156
2394
  /** The file's text: the schema link, then each database with its adapter first. */
2157
2395
  function source(link, { name, result }) {
@@ -2164,34 +2402,68 @@ function source(link, { name, result }) {
2164
2402
  databases
2165
2403
  }, null, 2)}\n`;
2166
2404
  }
2405
+ /** The plugins whose databases `init` adds to a file: `--adapter`'s, or each one the file names. */
2406
+ async function pluginsAdding(inFile, adapter) {
2407
+ if (adapter === void 0) return inFile;
2408
+ if (!adapterNames.includes(adapter)) return `--adapter takes ${listed(adapterNames)}, not ${adapter}`;
2409
+ const plugin = await pluginOf(adapter);
2410
+ return plugin.unsupported?.() ?? [plugin];
2411
+ }
2167
2412
  /**
2168
- * What `init` does when the file is there: add each database the adapter the file names finds and
2169
- * the file doesn't name, keeping the rest of the text as written; or say why it can't.
2413
+ * The databases `plugins` find in `dir` that the file's `databases` (`inFile`) don't name, each
2414
+ * plugin writing what it can when `--adapter` chose an adapter new to the file; or why one can't be
2415
+ * read.
2416
+ */
2417
+ function missingFrom(dir, plugins, inFile, newAdapter) {
2418
+ const added = [];
2419
+ for (const plugin of plugins) {
2420
+ const found = plugin.init(dir, newAdapter);
2421
+ if (typeof found === "string") return found;
2422
+ for (const [binding, entry] of Object.entries(found?.databases ?? {})) {
2423
+ if (Object.hasOwn(inFile, binding)) continue;
2424
+ added.push({
2425
+ binding,
2426
+ adapter: plugin.name,
2427
+ entry,
2428
+ note: found?.notes?.[binding]
2429
+ });
2430
+ }
2431
+ }
2432
+ return added;
2433
+ }
2434
+ /** The line saying what init added, with the adapter, or each one's when they differ. */
2435
+ function addedLine(name, added) {
2436
+ return `Added ${listed(added.map((each) => each.binding), "and")} to ${name} (${new Set(added.map((each) => each.adapter)).size === 1 ? `on ${added[0].adapter}` : added.map((each) => `${each.binding} on ${each.adapter}`).join(", ")})`;
2437
+ }
2438
+ /**
2439
+ * What `init` does when the file is there: add each database that the adapters the file names (or
2440
+ * the one `--adapter` names) find and the file doesn't name, keeping the rest of the text as
2441
+ * written; or say why it can't.
2170
2442
  */
2171
2443
  async function planAdding(cwd, path, options) {
2172
2444
  const name = shown$1(cwd, path);
2173
- const adapter = await loadAdapter(cwd, options.config);
2174
- if (typeof adapter === "string") return printing([adapter], 1);
2175
- if (options.adapter !== void 0 && options.adapter !== adapter.name) return printing([`${name} names ${adapter.name}; a project uses one adapter, for now, so --adapter ${options.adapter} adds nothing`], 1);
2176
- const found = adapter.init(dirname(path), false);
2177
- if (typeof found === "string") return printing([found], 1);
2445
+ const adapters = await loadAdapters(cwd, options.config);
2446
+ if (typeof adapters === "string") return printing([adapters], 1);
2447
+ const plugins = await pluginsAdding(adapters.plugins, options.adapter);
2448
+ if (typeof plugins === "string") return printing([plugins], 1);
2178
2449
  const text = readFileSync(path, "utf8");
2179
- const named = parseJsonc(text).databases;
2180
- const missing = Object.entries(found?.databases ?? {}).filter(([key]) => !Object.hasOwn(named, key));
2181
- if (missing.length === 0) return printing([`${name} names every database init finds; it wrote nothing`]);
2182
- const source = withEntries(text, missing.map(([key, entry]) => [key, {
2183
- adapter: adapter.name,
2450
+ const inFile = parseJsonc(text).databases;
2451
+ const inUse = adapters.plugins.some((each) => each.name === options.adapter);
2452
+ const newAdapter = options.adapter !== void 0 && !inUse;
2453
+ const added = missingFrom(dirname(path), plugins, inFile, newAdapter);
2454
+ if (typeof added === "string") return printing([added], 1);
2455
+ if (added.length === 0) return printing([`${name} names every database init finds; it wrote nothing`]);
2456
+ const source = withEntries(text, added.map(({ binding, adapter, entry }) => [binding, {
2457
+ adapter,
2184
2458
  ...entry
2185
2459
  }]));
2186
2460
  if (source === void 0) return printing([`${name}'s databases couldn't be found to add to`], 1);
2187
- const bindings = missing.map(([key]) => key);
2188
- const notes = bindings.flatMap((key) => found?.notes?.[key] ?? []).map((note) => printed(`Note: ${note}`));
2189
- const added = `Added ${listed(bindings, "and")} to ${name} (on ${adapter.name})`;
2461
+ const notes = added.flatMap((each) => each.note ?? []).map((note) => printed(`Note: ${note}`));
2190
2462
  return {
2191
2463
  steps: [written({
2192
2464
  path,
2193
2465
  source
2194
- }, added), ...notes],
2466
+ }, addedLine(name, added)), ...notes],
2195
2467
  code: 0
2196
2468
  };
2197
2469
  }
@@ -2224,22 +2496,21 @@ async function planInit(options) {
2224
2496
  async function runInit(options, print) {
2225
2497
  return apply(await planInit(options), resolve(options.cwd ?? process.cwd()), print);
2226
2498
  }
2227
- //#endregion
2228
- //#region cli/init/flags.ts
2499
+ // cli/init/flags.ts
2229
2500
  /** `active-record init`: writes the project's active-record.jsonc. */
2230
2501
  const initSubcommand = defineSubcommand({
2231
2502
  options: { adapter: { type: "string" } },
2232
2503
  usage: ` active-record init Write active-record.jsonc, which names your databases`,
2233
2504
  flagHelp: `Options for init:
2234
- --adapter <name> The adapter, when the project could use several, or nothing says which`,
2505
+ --adapter <name> The adapter, when the project could use several, or nothing says which;
2506
+ with the file there, adds that adapter's databases`,
2235
2507
  action({ values, positionals }, print, fail) {
2236
2508
  if (positionals.length > 0) return fail(`Unexpected ${positionals[0]}`);
2237
2509
  const { help: _, ...options } = values;
2238
2510
  return runInit(options, print);
2239
2511
  }
2240
2512
  });
2241
- //#endregion
2242
- //#region cli/migrate/command.ts
2513
+ // cli/migrate/command.ts
2243
2514
  const standardIo = () => ({
2244
2515
  input: process.stdin,
2245
2516
  output: process.stdout,
@@ -2261,17 +2532,14 @@ async function allowed(target, options, io) {
2261
2532
  /** `active-record migrate`: resolves to the exit code, the adapter's own when it ran. */
2262
2533
  async function runMigrate(options, print, io = standardIo()) {
2263
2534
  const cwd = options.cwd ?? process.cwd();
2264
- const adapter = await loadAdapter(cwd, options.config);
2265
- if (typeof adapter === "string") {
2266
- print(adapter);
2267
- return 1;
2268
- }
2269
- for (const note of configNotes(adapter)) print(note);
2270
- const chosen = chosenDatabase(adapter, cwd, options);
2271
- if (typeof chosen === "string") {
2272
- print(chosen);
2535
+ const project = await loadForCommand(cwd, options, print);
2536
+ if (project === void 0) return 1;
2537
+ const found = chosenDatabase(project, options);
2538
+ if (typeof found === "string") {
2539
+ print(found);
2273
2540
  return 1;
2274
2541
  }
2542
+ const { adapter, chosen } = found;
2275
2543
  const remote = options.remote === true;
2276
2544
  if (remote) {
2277
2545
  const target = adapter.remote(chosen, "migrate");
@@ -2283,8 +2551,7 @@ async function runMigrate(options, print, io = standardIo()) {
2283
2551
  }
2284
2552
  return adapter.migrate(cwd, chosen, { remote }, { output: (text) => io.output.write(text) });
2285
2553
  }
2286
- //#endregion
2287
- //#region cli/migrate/flags.ts
2554
+ // cli/migrate/flags.ts
2288
2555
  /** `active-record migrate`: applies the pending migrations, to the local database or the real one. */
2289
2556
  const migrateSubcommand = defineSubcommand({
2290
2557
  options: {
@@ -2304,8 +2571,7 @@ const migrateSubcommand = defineSubcommand({
2304
2571
  return runMigrate(options, print);
2305
2572
  }
2306
2573
  });
2307
- //#endregion
2308
- //#region cli/schema/command.ts
2574
+ // cli/schema/command.ts
2309
2575
  /** A schema that couldn't be generated: the errors, and that the last good file stays as it was. */
2310
2576
  function failed(errors, cwd, db) {
2311
2577
  const out = shown$1(cwd, db.target.out);
@@ -2315,19 +2581,19 @@ function failed(errors, cwd, db) {
2315
2581
  /** `--check`: whether the file on disk was generated from these tables (its fingerprint, not its format). */
2316
2582
  function checkPlan(project, db, tables) {
2317
2583
  const out = shown$1(project.cwd, db.target.out);
2318
- const schema = schemaSourceOf(project, db, tables);
2584
+ const schema = schemaSourceOf(db, tables);
2319
2585
  const current = db.schema !== void 0 && fingerprintIn(db.schema) === fingerprintOf(schema);
2320
2586
  return printing([current ? `${out} is up to date` : `${out} is out of date: run \`active-record schema\``], current ? 0 : 1);
2321
2587
  }
2322
2588
  /** One database's schema, generated (or, with `check`, checked). */
2323
2589
  async function planDatabase(project, db, check) {
2324
- const { adapter, cwd } = project;
2590
+ const { cwd } = project;
2325
2591
  if (db.migrations === void 0) return failed([`No migrations folder at ${shown$1(cwd, db.target.migrationsDir)}/`], cwd, db);
2326
2592
  const refusal = check ? void 0 : schemaRefusal(cwd, db);
2327
2593
  if (refusal !== void 0) return failed([refusal], cwd, db);
2328
2594
  if (db.modelErrors.length > 0) return failed(db.modelErrors, cwd, db);
2329
2595
  const { migrationsTable, entry } = db.target.database;
2330
- const result = await adapter.readSchema(db.migrations, {
2596
+ const result = await db.target.adapter.readSchema(db.migrations, {
2331
2597
  migrationsTable,
2332
2598
  entry
2333
2599
  });
@@ -2345,13 +2611,9 @@ async function planSchema(project, check) {
2345
2611
  */
2346
2612
  async function runSchema(options, print) {
2347
2613
  const cwd = resolve(options.cwd ?? process.cwd());
2348
- const adapter = await loadAdapter(cwd, options.config);
2349
- if (typeof adapter === "string") {
2350
- print(adapter);
2351
- return 1;
2352
- }
2353
- for (const note of configNotes(adapter)) print(note);
2354
- const read = readProject(adapter, cwd, options);
2614
+ const loaded = await loadForCommand(cwd, options, print);
2615
+ if (loaded === void 0) return 1;
2616
+ const read = readProject(loaded, cwd, options);
2355
2617
  if (typeof read === "string") {
2356
2618
  print(read);
2357
2619
  return 1;
@@ -2368,9 +2630,9 @@ async function runSchema(options, print) {
2368
2630
  * `--watch` would.
2369
2631
  */
2370
2632
  async function watchFromCommandLine(options, print) {
2371
- const adapter = await loadAdapter(resolve(options.cwd ?? process.cwd()), options.config);
2372
- if (typeof adapter === "string") {
2373
- print(adapter);
2633
+ const loaded = await loadDatabases(resolve(options.cwd ?? process.cwd()), options.config);
2634
+ if (typeof loaded === "string") {
2635
+ print(loaded);
2374
2636
  return 1;
2375
2637
  }
2376
2638
  watchSchema(options, print);
@@ -2383,9 +2645,9 @@ async function watchFromCommandLine(options, print) {
2383
2645
  async function watchSchema(options, print) {
2384
2646
  let running = runSchema(options, print);
2385
2647
  const cwd = resolve(options.cwd ?? process.cwd());
2386
- const adapter = await loadAdapter(cwd, options.config);
2387
- if (typeof adapter === "string") return () => {};
2388
- const project = readProject(adapter, cwd, options);
2648
+ const loaded = await loadDatabases(cwd, options.config);
2649
+ if (typeof loaded === "string") return () => {};
2650
+ const project = readProject(loaded, cwd, options);
2389
2651
  if (typeof project === "string") return () => {};
2390
2652
  let pending;
2391
2653
  const regenerate = () => {
@@ -2400,8 +2662,7 @@ async function watchSchema(options, print) {
2400
2662
  for (const watcher of watchers) watcher.close();
2401
2663
  };
2402
2664
  }
2403
- //#endregion
2404
- //#region cli/main.ts
2665
+ // cli/main.ts
2405
2666
  /** Each subcommand by the names it answers to. */
2406
2667
  const subcommands = {
2407
2668
  init: initSubcommand,
@@ -2463,9 +2724,7 @@ function main(argv, print = console.log) {
2463
2724
  }
2464
2725
  return subcommand.run(rest, print, (problem) => usage(print, problem));
2465
2726
  }
2466
- //#endregion
2467
- //#region cli/bin.ts
2727
+ // cli/bin.ts
2468
2728
  const code = await main(process.argv.slice(2));
2469
2729
  if (code !== "watching") process.exitCode = code;
2470
- //#endregion
2471
2730
  export {};