@forestfuture/active-record 0.6.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.
package/dist/command.mjs CHANGED
@@ -1,22 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import { J as tableize, Y as ancestors, i as isBase } from "./generated-model-CfDggoVN.mjs";
3
- import { a as underscore, i as camelize, n as pluralize, r as singularize } from "./epoch-storage-o2aoOH7H.mjs";
4
- import { a as isIdentifier, c as byName$1, d as importPath, f as shown$1, l as hasNestedMigrations, o as listed, p as slashed, r as classify, s as moduleName, t as storageOverride, u as migrationsOf } from "./storage-override-BYBYP8Mj.mjs";
5
- import { existsSync, 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";
9
- import { createJiti } from "jiti";
10
9
  import { createInterface } from "node:readline";
10
+ import { createJiti } from "jiti";
11
11
  import { Console } from "node:console";
12
12
  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
- adapter: { type: "string" },
20
19
  config: { type: "string" },
21
20
  help: {
22
21
  type: "boolean",
@@ -25,8 +24,7 @@ const sharedOptions = {
25
24
  };
26
25
  /** The help for the shared flags, after every subcommand's own. */
27
26
  const sharedFlagHelp = `Options for every command:
28
- --adapter <name> The adapter (d1), when the project has several installed
29
- --config <file> Use this Wrangler config
27
+ --config <file> Use this config file, in place of active-record.jsonc
30
28
  -h, --help Show this help`;
31
29
  /** A subcommand from its spec: its `action` gets the command line parsed, or `fail` says why it can't be. */
32
30
  function defineSubcommand(spec) {
@@ -65,207 +63,147 @@ function helpFor(subcommands) {
65
63
  sharedFlagHelp
66
64
  ].join("\n\n");
67
65
  }
68
- //#endregion
69
- //#region cli/project/targets.ts
70
- /**
71
- * A database's base class: `ApplicationRecord` when there's one database, as in Rails, and one
72
- * per binding when there are several (`LOGS` → `LogsRecord`), as Rails names them.
73
- */
74
- function baseFor(modelsDir, binding, several) {
75
- if (!several) return {
76
- path: join(modelsDir, "application-record.ts"),
77
- className: "ApplicationRecord"
78
- };
79
- const className = `${classify(binding.toLowerCase())}Record`;
80
- return {
81
- path: join(modelsDir, `${moduleName(className)}.ts`),
82
- className
83
- };
84
- }
85
- /** Where Models and their base class go without `--models`. */
86
- const defaultModels = "src/models";
87
- /** Whether `--models` names one file all Models go in (`src/models.ts`), not a folder. */
88
- function oneModelsFile(models) {
89
- return models.endsWith(".ts");
90
- }
91
- /** The folder Models and their base class live in: `--models`, or `src/models`. */
92
- function modelsDirOf(cwd, models = defaultModels) {
93
- const path = resolve(cwd, models);
94
- return oneModelsFile(models) ? dirname(path) : path;
95
- }
96
- /** The Model folder to watch, when it exists: `--models`'s, or the one holding its one file. */
97
- function modelsFolders(cwd, models = defaultModels) {
98
- const folder = modelsDirOf(cwd, models);
99
- return existsSync(folder) ? [folder] : [];
100
- }
101
- /** Bindings whose base classes would be the same (`DB` and `db` → `DbRecord`), as an error. */
102
- function sharedBase(targets) {
103
- const seen = /* @__PURE__ */ new Map();
104
- for (const { database, base } of targets) {
105
- const other = seen.get(base.className);
106
- if (other !== void 0) return `The bindings ${other} and ${database.binding} would share the base class ${base.className}; rename one`;
107
- seen.set(base.className, database.binding);
66
+ // cli/project/adapters.ts
67
+ /** Each adapter a database's `adapter` names. Its plugin ships with the command, loaded when it's used. */
68
+ const adapters = {
69
+ d1: {
70
+ entry: "@forestfuture/active-record/d1",
71
+ plugin: async () => (await import("./plugin-wOSILvSB.mjs")).cli
72
+ },
73
+ postgresql: {
74
+ entry: "@forestfuture/active-record/postgresql",
75
+ plugin: async () => (await import("./plugin-x5-d3TSN.mjs")).cli
76
+ }
77
+ };
78
+ /** The adapters' names, in the registry's order. */
79
+ const adapterNames = Object.keys(adapters);
80
+ /** The entry an adapter's factory and `connect` are imported from, as the registry names it. */
81
+ function adapterEntry(adapter) {
82
+ return adapters[adapter.name]?.entry ?? adapter.name;
83
+ }
84
+ /** What's wrong with a database's `adapter`, if anything. */
85
+ function adapterError(binding, adapter) {
86
+ if (adapter === void 0) {
87
+ const quoted = adapterNames.map((name) => JSON.stringify(name));
88
+ return `databases.${binding} has no adapter (add "adapter": ${listed(quoted)})`;
89
+ }
90
+ if (typeof adapter === "string" && Object.hasOwn(adapters, adapter)) return void 0;
91
+ return `databases.${binding} has the adapter ${JSON.stringify(adapter)}, which isn't ${listed(adapterNames)}`;
92
+ }
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) {
95
+ const file = basename(project.file);
96
+ const names = [];
97
+ for (const [binding, entry] of Object.entries(project.databases)) {
98
+ const error = adapterError(binding, entry.adapter);
99
+ if (error !== void 0) return `${file}: ${error}`;
100
+ if (!names.includes(entry.adapter)) names.push(entry.adapter);
108
101
  }
102
+ return names;
109
103
  }
110
- /** The databases to generate, from the adapter's config and the options; or why there are none. */
111
- function targetsOf(adapter, cwd, options) {
112
- const config = adapter.databases(cwd, options.config);
113
- if (!config.ok) return config.error;
114
- const { databases, dir } = config;
115
- if (options.migrations !== void 0 && databases.length > 1) return `--migrations needs a single database; this config has ${databases.length}`;
116
- const targets = databases.map((database) => {
117
- const migrationsDir = resolve(cwd, options.migrations ?? join(dir, database.migrationsDir));
118
- const out = databases.length === 1 ? resolve(cwd, options.out ?? "src/db/schema.ts") : resolve(cwd, options.out ?? "src/db", `${database.binding}.ts`);
119
- const base = baseFor(modelsDirOf(cwd, options.models), database.binding, databases.length > 1);
120
- return {
121
- database,
122
- configDir: dir,
123
- migrationsDir,
124
- out,
125
- base
126
- };
127
- });
128
- return sharedBase(targets) ?? targets;
104
+ /** The plugin of the adapter `name`. */
105
+ function pluginOf(name) {
106
+ return adapters[name].plugin();
129
107
  }
130
- //#endregion
131
- //#region cli/project/load.ts
132
108
  /**
133
- * A jiti based in the project: it reads TypeScript, extensionless imports and `tsconfig.json`
134
- * paths, and resolves the library (`@forestfuture/active-record` and `@forestfuture/d1-record`)
135
- * from the project's `node_modules`, so the Models and the command share a single copy of it.
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.
136
111
  */
137
- function projectJiti(cwd) {
138
- return createJiti(`${cwd}/`, {
139
- tsconfigPaths: true,
140
- fsCache: false,
141
- moduleCache: true
142
- });
112
+ async function loadAdapters(cwd, configPath) {
113
+ const project = projectDatabases(cwd, configPath);
114
+ if (typeof project === "string") return 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
+ };
143
122
  }
144
- /** The Model files: the folder's `.ts` files, or the one file `--models` names. */
145
- function modelFiles(cwd, models) {
146
- const path = resolve(cwd, models);
147
- if (!existsSync(path)) return `No Models at ${shown$1(cwd, path)} (run active-record g model, or pass --models)`;
148
- if (oneModelsFile(models) || statSync(path).isFile()) return [path];
149
- return readdirSync(path).filter((name) => name.endsWith(".ts") && !name.endsWith(".d.ts")).sort().map((name) => join(path, name));
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
+ };
150
131
  }
151
- /** The core, which every command loads from the project, beside the adapter some need. */
152
- const corePackage = "@forestfuture/active-record";
153
- /** Whether `error` is the loader failing to find `name` itself, not something it imports. */
154
- function isMissing(error, name) {
155
- const { code, message } = error;
156
- return (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") && String(message).startsWith(`Cannot find module '${name}'`);
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);
157
135
  }
158
- /**
159
- * The project's own copies of `packages` (the core, and the adapter when a command needs it), as
160
- * one module, or why one can't be loaded, naming it. Each is imported from a file in the project,
161
- * as its Models import it, because only imports made inside a file follow a `tsconfig.json` path
162
- * (a workspace link), and so the Models and the command get one copy.
163
- */
164
- async function loadLibrary(cwd, jiti, { command, packages }) {
165
- const filename = join(cwd, `active-record-${command}.ts`);
166
- let library = {};
167
- for (const name of packages) try {
168
- const source = `export * from "${name}";`;
169
- const loaded = await jiti.evalModule(source, {
170
- filename,
171
- async: true
172
- });
173
- library = {
174
- ...library,
175
- ...loaded
176
- };
177
- } catch (error) {
178
- if (isMissing(error, name)) return `${name} isn't installed here (install it, then run active-record ${command} again)`;
179
- return `Couldn't load ${name}: ${error.message}`;
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: []
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 ?? []);
180
156
  }
181
- return library;
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;
182
165
  }
183
166
  /**
184
- * Forgets the project's own modules, so they are read again. Its dependencies stay as they are,
185
- * and so do `keep` (the library's files, which may sit under the project's folder).
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.
186
169
  */
187
- function forgetProjectFiles(cwd, jiti, keep) {
188
- const folder = `${slashed(resolve(cwd))}/`;
189
- for (const file of Object.keys(jiti.cache)) {
190
- const name = slashed(file);
191
- if (name.startsWith(folder) && !name.includes("/node_modules/") && !keep.has(file)) delete jiti.cache[file];
192
- }
193
- }
194
- //#endregion
195
- //#region cli/project/adapters.ts
196
- /** Each adapter `--adapter` names, and its package. */
197
- const adapters = {
198
- d1: "@forestfuture/d1-record",
199
- pg: "@forestfuture/pg-record"
200
- };
201
- /** The packages a `package.json` depends on; none when it isn't there, or isn't JSON. */
202
- function dependenciesIn(file) {
203
- if (!existsSync(file)) return [];
204
- try {
205
- const manifest = JSON.parse(readFileSync(file, "utf8"));
206
- return ["dependencies", "devDependencies"].flatMap((field) => Object.keys(manifest[field] ?? {}));
207
- } catch {
208
- return [];
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);
209
176
  }
210
177
  }
211
- /** The package an adapter's plugin came from: `@forestfuture/d1-record` for `d1`. */
212
- function adapterPackage(adapter) {
213
- return adapters[adapter.name] ?? adapter.name;
214
- }
215
- /** The adapters the nearest `package.json` that lists any depends on, from `cwd` up. */
216
- function listedIn(cwd) {
217
- for (let dir = resolve(cwd);; dir = dirname(dir)) {
218
- const names = dependenciesIn(join(dir, "package.json"));
219
- const found = Object.keys(adapters).filter((name) => names.includes(adapters[name]));
220
- if (found.length > 0) return found;
221
- if (dirname(dir) === dir) return [];
222
- }
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`;
223
183
  }
224
184
  /**
225
- * The adapter's plugin, from the project's copy of its `/cli`, found as the project finds it (its
226
- * `node_modules`, or a `tsconfig.json` path); undefined when it isn't installed.
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.
227
187
  */
228
- async function pluginOf(cwd, name) {
229
- const entry = `${adapters[name]}/cli`;
230
- try {
231
- const source = `export { cli } from "${entry}";`;
232
- const filename = join(cwd, "active-record-adapter.ts");
233
- return (await projectJiti(cwd).evalModule(source, {
234
- filename,
235
- async: true
236
- })).cli;
237
- } catch (error) {
238
- if (isMissing(error, entry) || isMissing(error, adapters[name])) return void 0;
239
- return `Couldn't load ${entry}: ${error.message}`;
240
- }
241
- }
242
- /** The plugins of the adapters `named`, or the project lists, or else any installed. */
243
- async function installed(cwd, named) {
244
- const listedHere = named === void 0 ? listedIn(cwd) : [named];
245
- const found = [];
246
- for (const name of listedHere.length > 0 ? listedHere : Object.keys(adapters)) {
247
- const plugin = await pluginOf(cwd, name);
248
- if (typeof plugin === "string") return plugin;
249
- if (plugin !== void 0) found.push(plugin);
250
- }
251
- return found;
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;
252
193
  }
253
194
  /**
254
- * The project's adapter plugin: the one `named` (`--adapter`), or the one its `package.json` lists,
255
- * or, when none lists one (a workspace whose root holds them), the one installed. Several, or
256
- * none, is a message saying what to do.
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.
257
197
  */
258
- async function loadAdapter(cwd, named) {
259
- if (named !== void 0 && !Object.hasOwn(adapters, named)) return `--adapter takes ${listed(Object.keys(adapters))}, not ${named}`;
260
- const found = await installed(cwd, named);
261
- if (typeof found === "string") return found;
262
- if (found.length === 1) return found[0];
263
- if (found.length > 1) return `Several adapters are installed here (${listed(found.map((plugin) => plugin.name))}); choose one with --adapter`;
264
- if (named !== void 0) return `${adapters[named]} isn't installed here (install it, then try again)`;
265
- return `No adapter is installed here: install one, such as ${adapters["d1"]}, then try again`;
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;
266
206
  }
267
- //#endregion
268
- //#region cli/project/databases.ts
269
207
  /**
270
208
  * The database a command works on: the only one, or the one `--database` names; or, as a message
271
209
  * to print, why there isn't one (several and none named, or a name no binding has).
@@ -278,24 +216,41 @@ function chooseDatabase(databases, named) {
278
216
  }
279
217
  return databases.find((database) => database.binding === named) ?? `No database is bound as ${named}; this config has ${bindings}`;
280
218
  }
281
- /** The database for `--database` (and `--config`), with its config file, or why there isn't one. */
282
- function chosenDatabase(adapter, cwd, options) {
283
- const config = adapter.databases(cwd, options.config);
284
- if (!config.ok) return config.error;
285
- const chosen = chooseDatabase(config.databases, options.database);
286
- if (typeof chosen === "string") return chosen;
287
- const found = {
288
- binding: chosen.binding,
289
- entry: chosen.entry,
290
- configFile: config.file
291
- };
292
- return config.accountId === void 0 ? found : {
293
- ...found,
294
- accountId: config.accountId
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);
228
+ return {
229
+ adapter,
230
+ chosen: {
231
+ binding: database.binding,
232
+ entry: database.entry,
233
+ configFile,
234
+ migrationsDir
235
+ }
295
236
  };
296
237
  }
297
- //#endregion
298
- //#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
+ }
299
254
  /**
300
255
  * One line for a statement, as `onQuery` saw it (filtered values are already `[FILTERED]`):
301
256
  * ` User 1.2ms SELECT … WHERE "id" = ? [ 1 ]`, or `failed` and the reason in place of the time
@@ -303,7 +258,7 @@ function chosenDatabase(adapter, cwd, options) {
303
258
  */
304
259
  function statementLine(event, dim) {
305
260
  const { model, params, durationMs, error } = event;
306
- const sql = event.sql.replace(/\s*\n\s*/g, " ");
261
+ const sql = oneLine(event.sql);
307
262
  let line = ` ${model} `;
308
263
  if (error !== void 0) line += `failed ${sql} ${error instanceof Error ? error.message : inspect(error)}`;
309
264
  else {
@@ -312,8 +267,7 @@ function statementLine(event, dim) {
312
267
  }
313
268
  return dim ? `\u001b[2m${line}\u001b[22m` : line;
314
269
  }
315
- //#endregion
316
- //#region cli/console/commands.ts
270
+ // cli/console/commands.ts
317
271
  /**
318
272
  * The commands, and the `onQuery` the console's database is connected with. They share one
319
273
  * switch: `.verbose` flips what the listener does.
@@ -350,8 +304,7 @@ function consoleCommands(project, { verbose, write, dim }) {
350
304
  }
351
305
  };
352
306
  }
353
- //#endregion
354
- //#region cli/console/confirm.ts
307
+ // cli/console/confirm.ts
355
308
  /** How long input must stay quiet, once released, for what was already on its way to have arrived. */
356
309
  const QUIET_MS = 50;
357
310
  /** Reads and drops everything on `input` until the returned function is called and it is quiet. */
@@ -388,8 +341,135 @@ async function confirmRemote({ input, output, target, consequence = "What you ch
388
341
  release
389
342
  };
390
343
  }
391
- //#endregion
392
- //#region cli/console/project.ts
344
+ // cli/project/targets.ts
345
+ /**
346
+ * A database's base class: `ApplicationRecord` when there's one database, as in Rails, and one
347
+ * per binding when there are several (`LOGS` → `LogsRecord`), as Rails names them.
348
+ */
349
+ function baseFor(modelsDir, binding, several) {
350
+ if (!several) return {
351
+ path: join(modelsDir, "application-record.ts"),
352
+ className: "ApplicationRecord"
353
+ };
354
+ const className = `${classify(binding.toLowerCase())}Record`;
355
+ return {
356
+ path: join(modelsDir, `${moduleName(className)}.ts`),
357
+ className
358
+ };
359
+ }
360
+ /** Where Models and their base class go without `--models`. */
361
+ const defaultModels = "src/models";
362
+ /** Whether `--models` names one file all Models go in (`src/models.ts`), not a folder. */
363
+ function isOneModelsFile(models) {
364
+ return models.endsWith(".ts");
365
+ }
366
+ /** The folder Models and their base class live in: `--models`, or `src/models`. */
367
+ function modelsDirOf(cwd, models = defaultModels) {
368
+ const path = resolve(cwd, models);
369
+ return isOneModelsFile(models) ? dirname(path) : path;
370
+ }
371
+ /** The Model folder to watch, when it exists: `--models`'s, or the one holding its one file. */
372
+ function modelsFolders(cwd, models = defaultModels) {
373
+ const folder = modelsDirOf(cwd, models);
374
+ return existsSync(folder) ? [folder] : [];
375
+ }
376
+ /** Bindings whose base classes would be the same (`DB` and `db` → `DbRecord`), as an error. */
377
+ function sharedBase(targets) {
378
+ const seen = /* @__PURE__ */ new Map();
379
+ for (const { database, base } of targets) {
380
+ const other = seen.get(base.className);
381
+ if (other !== void 0) return `The bindings ${other} and ${database.binding} would share the base class ${base.className}; rename one`;
382
+ seen.set(base.className, database.binding);
383
+ }
384
+ }
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;
388
+ if (options.migrations !== void 0 && databases.length > 1) return `--migrations needs a single database; this config has ${databases.length}`;
389
+ const targets = databases.map((each) => {
390
+ const { database, configDir } = each;
391
+ const migrationsDir = resolve(cwd, options.migrations ?? join(configDir, database.migrationsDir));
392
+ const out = databases.length === 1 ? resolve(cwd, options.out ?? "src/db/schema.ts") : resolve(cwd, options.out ?? "src/db", `${database.binding}.ts`);
393
+ const base = baseFor(modelsDirOf(cwd, options.models), database.binding, databases.length > 1);
394
+ return {
395
+ ...each,
396
+ migrationsDir,
397
+ out,
398
+ base
399
+ };
400
+ });
401
+ return sharedBase(targets) ?? targets;
402
+ }
403
+ // cli/project/load.ts
404
+ /**
405
+ * A jiti based in the project: it reads TypeScript, extensionless imports and `tsconfig.json`
406
+ * paths, and resolves the library (`@forestfuture/active-record` and its adapter's package)
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.
412
+ */
413
+ function projectJiti(cwd) {
414
+ const modules = join(cwd, "node_modules");
415
+ const fsCache = existsSync(modules) ? join(modules, ".cache/jiti") : false;
416
+ return createJiti(`${cwd}/`, {
417
+ tsconfigPaths: true,
418
+ fsCache,
419
+ moduleCache: true
420
+ });
421
+ }
422
+ /** The Model files: the folder's `.ts` files, or the one file `--models` names. */
423
+ function modelFiles(cwd, models) {
424
+ const path = resolve(cwd, models);
425
+ if (!existsSync(path)) return `No Models at ${shown$1(cwd, path)} (run active-record g model, or pass --models)`;
426
+ if (isOneModelsFile(models) || statSync(path).isFile()) return [path];
427
+ return readdirSync(path).filter((name) => name.endsWith(".ts") && !name.endsWith(".d.ts")).sort().map((name) => join(path, name));
428
+ }
429
+ /** The core, which every command loads from the project, beside the adapter some need. */
430
+ const corePackage = "@forestfuture/active-record";
431
+ /** Whether `error` is the loader failing to find `name` itself, not something it imports. */
432
+ function isMissing(error, name) {
433
+ const { code, message } = error;
434
+ return (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") && String(message).startsWith(`Cannot find module '${name}'`);
435
+ }
436
+ /**
437
+ * The project's own copies of `packages` (the core, and the adapter when a command needs it), as
438
+ * one module, or why one can't be loaded, naming it. Each is imported from a file in the project,
439
+ * as its Models import it, because only imports made inside a file follow a `tsconfig.json` path
440
+ * (a workspace link), and so the Models and the command get one copy.
441
+ */
442
+ async function loadLibrary(cwd, jiti, { command, packages }) {
443
+ const filename = join(cwd, `active-record-${command}.ts`);
444
+ let library = {};
445
+ for (const name of packages) try {
446
+ const source = `export * from "${name}";`;
447
+ const loaded = await jiti.evalModule(source, {
448
+ filename,
449
+ async: true
450
+ });
451
+ library = {
452
+ ...library,
453
+ ...loaded
454
+ };
455
+ } catch (error) {
456
+ if (isMissing(error, name)) return `${name} isn't installed here (install it, then run active-record ${command} again)`;
457
+ return `Couldn't load ${name}: ${error.message}`;
458
+ }
459
+ return library;
460
+ }
461
+ /**
462
+ * Forgets the project's own modules, so they are read again. Its dependencies stay as they are,
463
+ * and so do `keep` (the library's files, which may sit under the project's folder).
464
+ */
465
+ function forgetProjectFiles(cwd, jiti, keep) {
466
+ const folder = `${slashed(resolve(cwd))}/`;
467
+ for (const file of Object.keys(jiti.cache)) {
468
+ const name = slashed(file);
469
+ if (name.startsWith(folder) && !name.includes("/node_modules/") && !keep.has(file)) delete jiti.cache[file];
470
+ }
471
+ }
472
+ // cli/console/project.ts
393
473
  /** The Model classes the files export, by name; or the file that couldn't be loaded. */
394
474
  async function loadModels(cwd, jiti, files, library) {
395
475
  const found = {};
@@ -445,12 +525,14 @@ async function loadProject(adapterPackage, cwd, models = defaultModels) {
445
525
  };
446
526
  return project;
447
527
  }
448
- //#endregion
449
- //#region cli/console/session.ts
450
- /** A line that is just `quit` or `exit`: leaves the console, as `.exit` does. */
451
- const leaving = /^\s*(?:quit|exit)\s*;?\s*$/;
452
- /** A line that is just `name!`: one of the console's commands, as a bare word. */
453
- 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*;)?$/;
454
536
  /**
455
537
  * Runs a task inside the project's database. While a line awaits, the REPL holds the next one back
456
538
  * and then runs it from inside that line's async context, where the database is already
@@ -560,7 +642,7 @@ function lineQueue() {
560
642
  ran.then(done);
561
643
  return;
562
644
  }
563
- if (leaving.test(code)) {
645
+ if (leaving.test(code.trim())) {
564
646
  stopped = true;
565
647
  server.close();
566
648
  return done();
@@ -615,7 +697,7 @@ function defineCommands(server, commands, lines, output) {
615
697
  }
616
698
  });
617
699
  return (line) => {
618
- const name = bangLine.exec(line)?.[1];
700
+ const name = bangLine.exec(line.trim())?.[1];
619
701
  return name !== void 0 && commands[name]?.bang ? runCommand(name, "") : void 0;
620
702
  };
621
703
  }
@@ -653,8 +735,7 @@ function startSession({ input, output, terminal = false, historyFile, prompt = "
653
735
  lines.attach(server, withDatabase, bang, script);
654
736
  return { closed: new Promise((resolve) => server.on("exit", () => void lines.pending().then(resolve))) };
655
737
  }
656
- //#endregion
657
- //#region cli/console/script.ts
738
+ // cli/console/script.ts
658
739
  /** A stream that collects what is written to it, as text. */
659
740
  function collecting(into) {
660
741
  return new Writable({ write(chunk, _encoding, done) {
@@ -710,8 +791,7 @@ async function runScript({ code, scope, commands, withDatabase, colors = {
710
791
  stderr
711
792
  };
712
793
  }
713
- //#endregion
714
- //#region cli/console/command.ts
794
+ // cli/console/command.ts
715
795
  /** Where the console reads and writes: the person's terminal. */
716
796
  function standardIo$1() {
717
797
  const terminal = process.stdin.isTTY === true && process.stdout.isTTY === true;
@@ -723,12 +803,12 @@ function standardIo$1() {
723
803
  };
724
804
  }
725
805
  /**
726
- * Where the history is kept: beside the project's local state, which Wrangler projects ignore. A
727
- * remote session has a file of its own, so a line typed against the real database is never
728
- * offered, with the up arrow, to a local session (or the other way round).
806
+ * Where the history is kept: in the adapter's folder for local files, which the project already
807
+ * ignores. A remote session has a file of its own, so a line typed against the real database is
808
+ * never offered, with the up arrow, to a local session (or the other way round).
729
809
  */
730
- function historyFileFor(configFile, remote) {
731
- return join(dirname(configFile), `.wrangler/d1-record-history${remote ? "-remote" : ""}`);
810
+ function historyFileFor(stateFolder, remote) {
811
+ return join(stateFolder, `active-record-history${remote ? "-remote" : ""}`);
732
812
  }
733
813
  /** Says why the console can't open; 1. */
734
814
  function refused$1(print, problem) {
@@ -780,27 +860,26 @@ function runOnce(code, opened, io, errors) {
780
860
  }
781
861
  });
782
862
  }
783
- /** Everything that has to be true before a session starts, or why it isn't. */
784
- async function prepare(options, io) {
785
- const cwd = options.cwd ?? process.cwd();
786
- const adapter = await loadAdapter(cwd, options.adapter);
787
- if (typeof adapter === "string") return adapter;
788
- const chosen = chosenDatabase(adapter, cwd, options);
789
- if (typeof chosen === "string") return chosen;
790
- const project = await loadProject(adapterPackage(adapter), cwd, options.models);
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;
868
+ const project = await loadProject(adapterEntry(adapter), cwd, options.models);
791
869
  if (typeof project === "string") return project;
792
870
  const opened = await (options.remote === true ? openRemote(adapter, {
793
871
  cwd,
794
872
  chosen
795
873
  }, options, io) : adapter.open(cwd, chosen, { remote: false }));
796
- return typeof opened === "string" ? opened : {
797
- chosen,
874
+ if (typeof opened === "string") return opened;
875
+ return {
876
+ stateFolder: adapter.stateFolder(chosen),
798
877
  project,
799
878
  opened
800
879
  };
801
880
  }
802
881
  /** The session, or the one piece of code, on the open database; the exit code. */
803
- async function converse(options, { chosen, project, opened }, { io, say, errors }) {
882
+ async function converse(options, { stateFolder, project, opened }, { io, say, errors }) {
804
883
  const scripted = options.eval !== void 0;
805
884
  const remote = options.remote === true;
806
885
  const { library, models } = project;
@@ -825,7 +904,7 @@ async function converse(options, { chosen, project, opened }, { io, say, errors
825
904
  ...io,
826
905
  ...inside,
827
906
  prompt: promptFor(remote, io.terminal === true),
828
- historyFile: options.history ?? !remote ? historyFileFor(chosen.configFile, remote) : void 0
907
+ historyFile: options.history ?? !remote ? historyFileFor(stateFolder, remote) : void 0
829
908
  }).closed;
830
909
  return {
831
910
  exitCode: 0,
@@ -837,7 +916,10 @@ async function converse(options, { chosen, project, opened }, { io, say, errors
837
916
  async function runConsole(options, print, io = standardIo$1()) {
838
917
  const errors = io.error ?? process.stderr;
839
918
  const say = options.eval === void 0 ? print : (line) => void errors.write(`${line}\n`);
840
- 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);
841
923
  if (typeof prepared === "string") return refused$1(say, prepared);
842
924
  let finished;
843
925
  let closing;
@@ -858,8 +940,7 @@ async function runConsole(options, print, io = standardIo$1()) {
858
940
  errors.write(finished.stderr);
859
941
  return finished.exitCode;
860
942
  }
861
- //#endregion
862
- //#region cli/console/flags.ts
943
+ // cli/console/flags.ts
863
944
  const options = {
864
945
  database: { type: "string" },
865
946
  models: { type: "string" },
@@ -894,14 +975,14 @@ function consoleChoices(values) {
894
975
  /** `active-record console`: opens the project's database (local, or remote) and its Models in a REPL. */
895
976
  const consoleSubcommand = defineSubcommand({
896
977
  options,
897
- usage: ` active-record console (or c) Open a console on your D1 database, with your Models`,
978
+ usage: ` active-record console (or c) Open a console on your database, with your Models`,
898
979
  flagHelp: `Options for console:
899
- --database <name> The D1 binding to open, when the config has several
980
+ --database <name> The database to open, when the config has several
900
981
  --models <path> Where the Models are: a folder (src/models) or one file (src/models.ts)
901
982
  --remote Open your remote database instead, after asking you to type its name
902
983
  --yes Don't ask first (with --remote); also how to open it without a terminal
903
984
  --history Keep what you type, which a remote session doesn't unless asked
904
- --no-history Don't keep what you type in .wrangler/d1-record-history
985
+ --no-history Don't keep what you type
905
986
  --verbose Print each statement a line runs (.verbose toggles it while it runs)
906
987
  -e, --eval <code> Run this code, print its result, and exit (only the result goes to stdout)`,
907
988
  action({ values, positionals }, print, fail) {
@@ -911,8 +992,7 @@ const consoleSubcommand = defineSubcommand({
911
992
  return runConsole(consoleChoices(values), print);
912
993
  }
913
994
  });
914
- //#endregion
915
- //#region cli/plan.ts
995
+ // cli/plan.ts
916
996
  /** A line printed with no file. */
917
997
  function printed(line) {
918
998
  return { line };
@@ -968,8 +1048,7 @@ function apply(plan, cwd, print) {
968
1048
  }
969
1049
  return plan.code;
970
1050
  }
971
- //#endregion
972
- //#region cli/project/tools.ts
1051
+ // cli/project/tools.ts
973
1052
  const tools = ["Drizzle", "Prisma"];
974
1053
  /** Each tool's files in a project, and the marker it writes into its SQL. */
975
1054
  const signs = {
@@ -1018,8 +1097,7 @@ function toolsWithFiles(projectDir) {
1018
1097
  function migrationTool(toolsFound, migrations) {
1019
1098
  return tools.find((tool) => toolsFound.includes(tool) || migrations.some((migration) => signs[tool].marker.test(migration.sql)));
1020
1099
  }
1021
- //#endregion
1022
- //#region cli/project/snapshot.ts
1100
+ // cli/project/snapshot.ts
1023
1101
  /** A file's contents, or undefined when there's no such file. */
1024
1102
  function contents(path) {
1025
1103
  return existsSync(path) ? readFileSync(path, "utf8") : void 0;
@@ -1040,26 +1118,31 @@ function databaseSnapshot(target, toolsFound) {
1040
1118
  };
1041
1119
  }
1042
1120
  /**
1043
- * Reads a project's databases from its Wrangler config, and the other `files` a command needs
1121
+ * Reads a project's databases from its config, and the other `files` a command needs
1044
1122
  * (a Model file, for `g model`); or why it can't, such as a missing config.
1045
1123
  */
1046
- function readProject(adapter, cwd, options, files = []) {
1047
- const targets = targetsOf(adapter, cwd, options);
1124
+ function readProject(project, cwd, options, files = []) {
1125
+ const targets = targetsOf(project, cwd, options);
1048
1126
  if (typeof targets === "string") return targets;
1049
- 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
+ };
1050
1135
  const read = files.flatMap((path) => {
1051
1136
  const text = contents(path);
1052
1137
  return text === void 0 ? [] : [[path, text]];
1053
1138
  });
1054
1139
  return {
1055
- adapter,
1056
1140
  cwd,
1057
- databases: targets.map((target) => databaseSnapshot(target, toolsFound)),
1141
+ databases: targets.map((target) => databaseSnapshot(target, toolsFor(target))),
1058
1142
  files: new Map(read)
1059
1143
  };
1060
1144
  }
1061
- //#endregion
1062
- //#region cli/source.ts
1145
+ // cli/source.ts
1063
1146
  /**
1064
1147
  * Text as a string literal in generated TypeScript, quotes and backslashes escaped: for values
1065
1148
  * that come from a project's config or paths (#85).
@@ -1069,13 +1152,12 @@ function stringLiteral(text) {
1069
1152
  }
1070
1153
  /** A double-quoted string literal in generated source, read back: `stringLiteral`'s pattern. */
1071
1154
  const stringLiteralPattern = String.raw`"(?:[^"\\]|\\.)*"`;
1072
- //#endregion
1073
- //#region cli/schema/render.ts
1155
+ // cli/schema/render.ts
1074
1156
  /**
1075
1157
  * The generated file's format. Bump it when the output changes, so `--check` reports files an
1076
- * older d1-record wrote (its fingerprint covers the format as well as the schema).
1158
+ * older version of the command wrote (its fingerprint covers the format as well as the schema).
1077
1159
  */
1078
- const format = 5;
1160
+ const format = 7;
1079
1161
  /**
1080
1162
  * An object key: bare when it's an identifier, quoted otherwise (`"first name"`). `__proto__` is
1081
1163
  * computed, since in an object literal a bare or quoted one sets the prototype and the key is
@@ -1099,6 +1181,20 @@ function defaultSource(value) {
1099
1181
  const source = valueSource(value.literal);
1100
1182
  return `() => ${source.startsWith("{") ? `(${source})` : source}`;
1101
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
+ }
1102
1198
  /** An attribute's spec: just its type when that's all it has, as Models are written by hand. */
1103
1199
  function specSource(spec) {
1104
1200
  const parts = [`type: ${JSON.stringify(spec.type)}`];
@@ -1106,6 +1202,8 @@ function specSource(spec) {
1106
1202
  if (spec.column !== void 0) parts.push(`column: ${JSON.stringify(spec.column)}`);
1107
1203
  if (spec.default !== void 0) parts.push(`default: ${defaultSource(spec.default)}`);
1108
1204
  if (spec.generateId) parts.push("generateId: true");
1205
+ parts.push(...digitsSource(spec));
1206
+ if (spec.enum !== void 0) parts.push(...generatedEnumSource(spec));
1109
1207
  return parts.length === 1 ? JSON.stringify(spec.type) : `{ ${parts.join(", ")} }`;
1110
1208
  }
1111
1209
  /** Text safe inside a `/** … *\/` comment. */
@@ -1120,40 +1218,69 @@ ${attributes}
1120
1218
  } as const;`;
1121
1219
  }
1122
1220
  /** A short hash of the schema itself, so `--check` ignores how the file is formatted. */
1123
- function fingerprintOf({ tables, binding, models }) {
1124
- const listed = byName(models, (model) => model.className);
1221
+ function fingerprintOf({ adapter, tables, binding, models }) {
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
+ });
1125
1239
  return createHash("sha256").update(JSON.stringify({
1126
1240
  format,
1241
+ adapter,
1127
1242
  tables,
1128
1243
  binding,
1129
1244
  models: listed
1130
1245
  })).digest("hex").slice(0, 12);
1131
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
+ }
1132
1251
  /** Items sorted by a name, as `localeCompare` doesn't: the same on every machine. */
1133
1252
  function byName(items, name) {
1134
1253
  return [...items].sort((a, b) => name(a) < name(b) ? -1 : name(a) > name(b) ? 1 : 0);
1135
1254
  }
1136
- /** The Models' entries as an object: on one line, or one a line when that would be too long. */
1137
- 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) {
1138
1257
  const line = entries.length === 0 ? "{}" : `{ ${entries.join(", ")} }`;
1139
- if (` models: ${line},`.length <= 100) return line;
1258
+ if (` ${key}: ${line},`.length <= 100) return line;
1140
1259
  return `{\n${entries.map((entry) => ` ${entry},`).join("\n")}\n }`;
1141
1260
  }
1142
- /** The `schema` value: its adapter and binding, every table by name, and every Model's table by class. */
1143
- function schemaValueSource({ tables, binding, models }) {
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
+ */
1270
+ function schemaValueSource({ adapter, tables, binding, models }) {
1144
1271
  const entries = tables.map((table) => {
1145
1272
  const primaryKey = JSON.stringify(table.primaryKey);
1146
1273
  return ` ${keySource(table.name)}: { attributes: ${table.exportName}, primaryKey: ${primaryKey} },`;
1147
1274
  }).join("\n");
1148
- 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)}`);
1149
1276
  return `/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
1150
- export const schema = {
1151
- adapter: d1({ binding: ${stringLiteral(binding)} }),
1277
+ export const schema = defineSchema({
1278
+ adapter: ${adapter.factory}({ binding: ${stringLiteral(binding)} }),
1152
1279
  tables: {
1153
1280
  ${entries}
1154
1281
  },
1155
- models: ${modelsSource(listed)},
1156
- } as const;`;
1282
+ models: ${objectSource(listed, "models")},${enumScopesSource(models)}
1283
+ });`;
1157
1284
  }
1158
1285
  /** A Model's declaration: its class, with its table's attributes after its own overrides. */
1159
1286
  function interfaceSource(model, exportName) {
@@ -1162,13 +1289,24 @@ function interfaceSource(model, exportName) {
1162
1289
  const line = ` interface ${name} ${heritage}`;
1163
1290
  return line.length <= 100 ? line : ` interface ${name}\n ${heritage}`;
1164
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
+ }
1165
1303
  /** One `declare module` block per Model file, adding each class's attributes to it. */
1166
1304
  function declarationsSource({ tables, models }) {
1167
1305
  const exportNames = new Map(tables.map((table) => [table.name, table.exportName]));
1168
1306
  const modules = /* @__PURE__ */ new Map();
1169
1307
  for (const model of byName(models, (each) => each.className)) modules.set(model.module, [...modules.get(model.module) ?? [], model]);
1170
1308
  return byName([...modules], ([module]) => module).map(([module, inModule]) => {
1171
- 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)]);
1172
1310
  return `declare module ${stringLiteral(module)} {\n${lines.join("\n")}\n}`;
1173
1311
  }).join("\n\n");
1174
1312
  }
@@ -1179,7 +1317,11 @@ function declarationsSource({ tables, models }) {
1179
1317
  */
1180
1318
  function renderSchema(schema, source) {
1181
1319
  const hasModels = schema.models.length > 0;
1182
- const imports = (hasModels ? "import type { TableAttributes } from \"@forestfuture/active-record\";\n" : "") + "import { d1 } from \"@forestfuture/d1-record\";\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`;
1183
1325
  const declarations = hasModels ? `\n\n${declarationsSource(schema)}` : "";
1184
1326
  return `// Generated by \`active-record schema\` from ${source} — don't edit.
1185
1327
  // schema: ${fingerprintOf(schema)}
@@ -1203,8 +1345,8 @@ import { schema } from ${stringLiteral(schemaImport)};
1203
1345
  * It's abstract: it has no table of its own.
1204
1346
  */
1205
1347
  export abstract class ${className} extends Model {
1206
- // The generated schema: each Model's attributes, from its table, and the D1 binding Models
1207
- // query (Product.find(id)), from your Wrangler config's d1_databases.
1348
+ // The generated schema: each Model's attributes, from its table, and the binding Models
1349
+ // query (Product.find(id)), from your project's config.
1208
1350
  static override schema = schema;
1209
1351
 
1210
1352
  // A method every record has:
@@ -1248,8 +1390,125 @@ export abstract class ${className} extends Model {
1248
1390
  function fingerprintIn(source) {
1249
1391
  return /^\/\/ schema: ([0-9a-f]{12})$/m.exec(source)?.[1];
1250
1392
  }
1251
- //#endregion
1252
- //#region cli/schema/models.ts
1393
+ // cli/schema/origin.ts
1394
+ const issue = "https://github.com/forestfuture/active-record/issues/73";
1395
+ /** Column names (as snake_case words) that suggest a `TEXT` column holds JSON. */
1396
+ const jsonish = /(^|_)(json|metadata|settings|payload|properties)$/;
1397
+ /**
1398
+ * The hint for migrations in folders, when `hasNestedMigrations` found them: the pattern to set,
1399
+ * when the adapter reads one (`setting`), or that they aren't read.
1400
+ */
1401
+ function layoutNote(cwd, target, setting) {
1402
+ const dir = target.migrationsDir;
1403
+ const found = `${shown$1(cwd, dir)}/ has its migrations in folders, as Drizzle writes them`;
1404
+ if (setting === void 0) return `${found}, which aren't read`;
1405
+ return `${found}; set ${setting} to "${`${shown$1(target.configDir, dir)}/*/migration.sql`}" in ${shown$1(cwd, target.configFile)}, so they're read`;
1406
+ }
1407
+ /** The columns worth checking, in a schema from `tool`'s migrations. */
1408
+ function columnNotes(tool, tables) {
1409
+ const notes = [];
1410
+ for (const table of tables) for (const [attribute, spec] of Object.entries(table.attributes)) {
1411
+ const column = spec.column ?? underscore(attribute);
1412
+ const words = underscore(column);
1413
+ const where = `${table.name}.${column}`;
1414
+ if (spec.type === "integer" && words.endsWith("_at")) notes.push(`${where}: read as an integer; if it holds a Unix timestamp, override it in its Model as ` + storageOverride(tool === "Drizzle"));
1415
+ else if (spec.type === "string" && jsonish.test(words)) notes.push(`${where}: read as a string; if it holds JSON, override it as "json" in its Model`);
1416
+ }
1417
+ return notes;
1418
+ }
1419
+ /** A note for a datetime whose default writes the database's own date text, which sorts apart from ISO (#143). */
1420
+ function textDateNote(where) {
1421
+ return `${where}: its default writes the database's own date text (2026-10-12 06:38:30), where active-record writes ISO text (2026-10-12T06:38:30.000Z), and the two sort apart as text, so range conditions can misplace values within a day (see Existing databases in the guide)`;
1422
+ }
1423
+ /**
1424
+ * Notes for a schema generated from another tool's migrations: the tool, then the columns to
1425
+ * check, and `textDates`, the datetime columns whose default is the database's own date text.
1426
+ */
1427
+ function originNotes(tool, tables, textDates) {
1428
+ if (tool === void 0) return [];
1429
+ return [
1430
+ `these migrations look like ${tool}'s. Some columns may convert to the wrong type and fail when read, especially numeric timestamps: check the generated types (${issue})`,
1431
+ ...columnNotes(tool, tables),
1432
+ ...textDates.map(textDateNote)
1433
+ ];
1434
+ }
1435
+ // cli/schema/writes.ts
1436
+ /** The app's base class for the database (`ApplicationRecord`), when it's missing; never over it. */
1437
+ function baseWrites(cwd, db) {
1438
+ const { target } = db;
1439
+ if (db.hasBase) return [];
1440
+ const { path, className } = target.base;
1441
+ return [written({
1442
+ path,
1443
+ source: renderBase(className, importPath(dirname(path), target.out))
1444
+ }, `Wrote ${shown$1(cwd, path)}`)];
1445
+ }
1446
+ /**
1447
+ * Why the schema can't be written where it's going, if it can't: a file the command didn't write
1448
+ * (a Drizzle schema, say) is never replaced, and a file next to a folder of the same name would
1449
+ * take over that folder's imports (`@/db/schema` finds `schema.ts` before `schema/index.ts`).
1450
+ */
1451
+ function schemaRefusal(cwd, db) {
1452
+ const out = shown$1(cwd, db.target.out);
1453
+ const folder = db.target.out.replace(/\.ts$/, "");
1454
+ const suggestion = "choose another file with --out, such as --out src/db/active-record.ts";
1455
+ if (db.schemaFolder) return `${out} would take over imports of the folder ${shown$1(cwd, folder)}/ (an import of ${basename(folder)} finds the file first), so it isn't written; ${suggestion}`;
1456
+ if (db.schema !== void 0 && fingerprintIn(db.schema) === void 0) return `${out} wasn't written by active-record schema (it has no "Generated by" header), so it's left as it is; ${suggestion}`;
1457
+ }
1458
+ /** The adapter a schema imports: the plugin's name is its factory's, from the adapter's package. */
1459
+ function schemaAdapterOf(adapter) {
1460
+ return {
1461
+ factory: adapter.name,
1462
+ from: adapterEntry(adapter)
1463
+ };
1464
+ }
1465
+ /** What a database's schema is rendered from: its adapter, tables and binding, and the Models found. */
1466
+ function schemaSourceOf(db, tables) {
1467
+ const { target } = db;
1468
+ const models = db.models.map(({ className, modelName, table, file, enumScopes }) => ({
1469
+ className,
1470
+ modelName,
1471
+ table,
1472
+ module: importPath(dirname(target.out), file),
1473
+ enumScopes
1474
+ }));
1475
+ return {
1476
+ adapter: schemaAdapterOf(target.adapter),
1477
+ tables,
1478
+ binding: target.database.binding,
1479
+ models
1480
+ };
1481
+ }
1482
+ /**
1483
+ * What writing a database's schema takes, once its tables are known: the schema file (unless
1484
+ * it's unchanged), the base class when it's missing, and the notes.
1485
+ */
1486
+ function schemaWrites(project, db, result) {
1487
+ const { cwd } = project;
1488
+ const { target } = db;
1489
+ const out = shown$1(cwd, target.out);
1490
+ const source = `${shown$1(cwd, target.migrationsDir)}/`;
1491
+ const rendered = renderSchema(schemaSourceOf(db, result.tables), source);
1492
+ const count = `${result.tables.length} table${result.tables.length === 1 ? "" : "s"}`;
1493
+ const setting = target.adapter.patternSetting;
1494
+ const notes = db.nestedMigrations ? [layoutNote(cwd, target, setting)] : [];
1495
+ const steps = [];
1496
+ if (rendered === db.schema) steps.push({ line: `${out} is up to date (${count})` });
1497
+ else {
1498
+ steps.push(written({
1499
+ path: target.out,
1500
+ source: rendered
1501
+ }, `Wrote ${out} (${count}) from ${source}`));
1502
+ const tool = migrationTool(db.toolsFound, db.migrations ?? []);
1503
+ notes.unshift(...result.notes, ...originNotes(tool, result.tables, result.textDates));
1504
+ }
1505
+ steps.push(...baseWrites(cwd, db), ...notes.map((note) => ({ line: `Note: ${note}` })));
1506
+ return {
1507
+ steps,
1508
+ code: 0
1509
+ };
1510
+ }
1511
+ // cli/schema/models.ts
1253
1512
  /**
1254
1513
  * Writes a schema file that's missing, for while the Models load: an import finds a module only
1255
1514
  * when its file exists. The plan writes the real one. Returns its path, to remove afterwards.
@@ -1268,10 +1527,14 @@ async function freshSchemas(jiti, project, placeholders) {
1268
1527
  const schemas = /* @__PURE__ */ new Map();
1269
1528
  for (const db of project.databases) {
1270
1529
  const { database, out } = db.target;
1271
- const migrationsTable = database.migrationsTable;
1272
- const result = project.adapter.readSchema(db.migrations ?? [], { migrationsTable });
1530
+ const { migrationsTable, entry } = database;
1531
+ const result = await db.target.adapter.readSchema(db.migrations ?? [], {
1532
+ migrationsTable,
1533
+ entry
1534
+ });
1273
1535
  if (db.migrations === void 0 || !result.ok) continue;
1274
1536
  const source = renderSchema({
1537
+ adapter: schemaAdapterOf(db.target.adapter),
1275
1538
  tables: result.tables,
1276
1539
  binding: database.binding,
1277
1540
  models: []
@@ -1292,11 +1555,48 @@ function databaseOf(value, schemas) {
1292
1555
  return holder === void 0 ? void 0 : schemas.get(holder.schema);
1293
1556
  }
1294
1557
  /** Whether `file` declares the class itself, rather than exporting it from another file. */
1295
- function declares(file, name) {
1558
+ function isDeclaredIn(file, name) {
1296
1559
  return new RegExp(`\\bclass\\s+${name}\\b`).test(readFileSync(file, "utf8"));
1297
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
+ }
1298
1597
  /** Adds a class from `file` if it's a Model directly below a base: one whose table it is. */
1299
- function addModel(cwd, file, { name, model }, found) {
1598
+ function addModel(cwd, file, exported, found) {
1599
+ const { name, model } = exported;
1300
1600
  if (isBase(model) || !isBase(Object.getPrototypeOf(model))) return;
1301
1601
  if (name === "default") {
1302
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`);
@@ -1306,18 +1606,25 @@ function addModel(cwd, file, { name, model }, found) {
1306
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 \$`);
1307
1607
  return;
1308
1608
  }
1309
- if (found.models.get(model) !== void 0 && !declares(file, model.name)) return;
1310
- try {
1311
- model.attributeDefinitions;
1312
- } catch (error) {
1313
- 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}`);
1314
1618
  return;
1315
1619
  }
1316
1620
  found.models.set(model, {
1317
1621
  className: model.name,
1622
+ modelName: model.modelName,
1318
1623
  table: model.table,
1319
- file
1624
+ file,
1625
+ ...enumScopes.length === 0 ? {} : { enumScopes }
1320
1626
  });
1627
+ found.databases.set(model, exported.database);
1321
1628
  }
1322
1629
  /** Imports a Model file, or says why it couldn't be loaded. */
1323
1630
  async function importFile(cwd, jiti, file) {
@@ -1330,15 +1637,21 @@ async function importFile(cwd, jiti, file) {
1330
1637
  }
1331
1638
  /** Adds the Models a file exports that are built on a schema being generated. */
1332
1639
  function addExported(cwd, file, exported, context) {
1333
- 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, {
1334
- name,
1335
- model: value
1336
- }, 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
+ }
1337
1649
  }
1338
1650
  /** Loads the Model files, finding the Models built on the schemas being generated. */
1339
1651
  async function modelsIn(cwd, jiti, files, schemas) {
1340
1652
  const found = {
1341
1653
  models: /* @__PURE__ */ new Map(),
1654
+ databases: /* @__PURE__ */ new Map(),
1342
1655
  errors: []
1343
1656
  };
1344
1657
  const library = await loadLibrary(cwd, jiti, {
@@ -1393,156 +1706,100 @@ async function withModels(project, { models = defaultModels, check = false } = {
1393
1706
  forgetProjectFiles(cwd, jiti, loadedBefore);
1394
1707
  }
1395
1708
  }
1396
- //#endregion
1397
- //#region cli/schema/origin.ts
1398
- const issue = "https://github.com/forestfuture/active-record/issues/73";
1399
- /** Column names (as snake_case words) that suggest a `TEXT` column holds JSON. */
1400
- const jsonish = /(^|_)(json|metadata|settings|payload|properties)$/;
1401
- /** Wrangler's hint for migrations in folders, when `hasNestedMigrations` found them. */
1402
- function layoutNote(cwd, target) {
1403
- const dir = target.migrationsDir;
1404
- const pattern = `${shown$1(target.configDir, dir)}/*/migration.sql`;
1405
- return `${shown$1(cwd, dir)}/ has its migrations in folders, as Drizzle writes them; set migrations_pattern to "${pattern}" in your Wrangler config, so Wrangler and d1-record read them`;
1406
- }
1407
- /** The columns worth checking, in a schema from `tool`'s migrations. */
1408
- function columnNotes(tool, tables) {
1409
- const notes = [];
1410
- for (const table of tables) for (const [attribute, spec] of Object.entries(table.attributes)) {
1411
- const column = spec.column ?? underscore(attribute);
1412
- const words = underscore(column);
1413
- const where = `${table.name}.${column}`;
1414
- if (spec.type === "integer" && words.endsWith("_at")) notes.push(`${where}: read as an integer; if it holds a Unix timestamp, override it in its Model as ` + storageOverride(tool === "Drizzle"));
1415
- else if (spec.type === "string" && jsonish.test(words)) notes.push(`${where}: read as a string; if it holds JSON, override it as "json" in its Model`);
1416
- }
1417
- return notes;
1418
- }
1419
- /** A note for a datetime whose default writes SQLite's date text, which sorts apart from ISO (#143). */
1420
- function textDateNote(where) {
1421
- return `${where}: its default writes SQLite's date text (2026-10-12 06:38:30), where d1-record writes ISO text (2026-10-12T06:38:30.000Z), and the two sort apart as text, so range conditions can misplace values within a day (see Existing databases in the guide)`;
1422
- }
1423
- /**
1424
- * Notes for a schema generated from another tool's migrations: the tool, then the columns to
1425
- * check, and `textDates`, the datetime columns whose default is SQLite's own date text.
1426
- */
1427
- function originNotes(tool, tables, textDates) {
1428
- if (tool === void 0) return [];
1429
- return [
1430
- `these migrations look like ${tool}'s. Some columns may convert to the wrong type and fail when read, especially numeric timestamps: check the generated types (${issue})`,
1431
- ...columnNotes(tool, tables),
1432
- ...textDates.map(textDateNote)
1433
- ];
1434
- }
1435
- //#endregion
1436
- //#region cli/schema/writes.ts
1437
- /** The app's base class for the database (`ApplicationRecord`), when it's missing; never over it. */
1438
- function baseWrites(cwd, db) {
1439
- const { target } = db;
1440
- if (db.hasBase) return [];
1441
- const { path, className } = target.base;
1442
- return [written({
1443
- path,
1444
- source: renderBase(className, importPath(dirname(path), target.out))
1445
- }, `Wrote ${shown$1(cwd, path)}`)];
1446
- }
1447
- /**
1448
- * Why the schema can't be written where it's going, if it can't: a file d1-record didn't write
1449
- * (a Drizzle schema, say) is never replaced, and a file next to a folder of the same name would
1450
- * take over that folder's imports (`@/db/schema` finds `schema.ts` before `schema/index.ts`).
1451
- */
1452
- function schemaRefusal(cwd, db) {
1453
- const out = shown$1(cwd, db.target.out);
1454
- const folder = db.target.out.replace(/\.ts$/, "");
1455
- const suggestion = "choose another file with --out, such as --out src/db/d1-record.ts";
1456
- if (db.schemaFolder) return `${out} would take over imports of the folder ${shown$1(cwd, folder)}/ (an import of ${basename(folder)} finds the file first), so it isn't written; ${suggestion}`;
1457
- if (db.schema !== void 0 && fingerprintIn(db.schema) === void 0) return `${out} wasn't written by active-record schema (it has no "Generated by" header), so it's left as it is; ${suggestion}`;
1458
- }
1459
- /** What a database's schema is rendered from: its tables, its binding, and the Models found. */
1460
- function schemaSourceOf(db, tables) {
1461
- const { target } = db;
1462
- const models = db.models.map(({ className, table, file }) => ({
1463
- className,
1464
- table,
1465
- module: importPath(dirname(target.out), file)
1466
- }));
1467
- return {
1468
- tables,
1469
- binding: target.database.binding,
1470
- models
1471
- };
1472
- }
1473
- /**
1474
- * What writing a database's schema takes, once its tables are known: the schema file (unless
1475
- * it's unchanged), the base class when it's missing, and the notes.
1476
- */
1477
- function schemaWrites(cwd, db, result) {
1478
- const { target } = db;
1479
- const out = shown$1(cwd, target.out);
1480
- const source = `${shown$1(cwd, target.migrationsDir)}/`;
1481
- const rendered = renderSchema(schemaSourceOf(db, result.tables), source);
1482
- const count = `${result.tables.length} table${result.tables.length === 1 ? "" : "s"}`;
1483
- const notes = db.nestedMigrations ? [layoutNote(cwd, target)] : [];
1484
- const steps = [];
1485
- if (rendered === db.schema) steps.push({ line: `${out} is up to date (${count})` });
1486
- else {
1487
- steps.push(written({
1488
- path: target.out,
1489
- source: rendered
1490
- }, `Wrote ${out} (${count}) from ${source}`));
1491
- const tool = migrationTool(db.toolsFound, db.migrations ?? []);
1492
- notes.unshift(...result.notes, ...originNotes(tool, result.tables, result.textDates));
1493
- }
1494
- steps.push(...baseWrites(cwd, db), ...notes.map((note) => ({ line: `Note: ${note}` })));
1495
- return {
1496
- steps,
1497
- code: 0
1498
- };
1499
- }
1500
- //#endregion
1501
- //#region cli/generate/columns.ts
1709
+ // cli/generate/columns.ts
1502
1710
  const types$1 = [
1503
1711
  "string",
1504
1712
  "integer",
1505
1713
  "real",
1714
+ "decimal",
1506
1715
  "boolean",
1507
1716
  "datetime",
1717
+ "date",
1718
+ "time",
1508
1719
  "json",
1720
+ "binary",
1509
1721
  "references"
1510
1722
  ];
1511
- 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)}`;
1512
1785
  /** A `=value` default as its type's literal, or why it can't be one. */
1513
- function defaultOf(type, value) {
1514
- const number = Number(value);
1515
- switch (type) {
1516
- case "string": return {
1517
- ok: true,
1518
- value
1519
- };
1520
- case "boolean": return value === "true" || value === "false" ? {
1521
- ok: true,
1522
- value: value === "true"
1523
- } : {
1524
- ok: false,
1525
- error: `${value} isn't true or false`
1526
- };
1527
- case "integer": return /^-?\d+$/.test(value) && Number.isSafeInteger(number) ? {
1528
- ok: true,
1529
- value: number
1530
- } : {
1531
- ok: false,
1532
- error: `${value} isn't an integer`
1533
- };
1534
- case "real": return /^-?\d+(\.\d+)?$/.test(value) ? {
1535
- ok: true,
1536
- value: number
1537
- } : {
1538
- ok: false,
1539
- error: `${value} isn't a number`
1540
- };
1541
- default: return {
1542
- ok: false,
1543
- error: "only string, integer, real and boolean columns can have a default here"
1544
- };
1545
- }
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}`;
1546
1803
  }
1547
1804
  /** The index `:unique` or `:index` asks for. */
1548
1805
  function indexOf(modifiers) {
@@ -1553,11 +1810,13 @@ function indexOf(modifiers) {
1553
1810
  function parseColumn(arg) {
1554
1811
  const match = syntax.exec(arg);
1555
1812
  if (match === null) return `${arg}: write a column as name:type, with ! for NOT NULL, =value for a default, and :unique or :index`;
1556
- const [, given, typeName = "string", bang, value, indexes = ""] = match;
1813
+ const [, given, typeName = "string", precision, scale, bang, value, indexes = ""] = match;
1557
1814
  const type = typeName;
1558
- 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}`;
1559
1816
  const name = underscore(given);
1560
1817
  const index = indexOf(indexes);
1818
+ const digits = digitsOf(type, precision, scale);
1819
+ if (typeof digits === "string") return `${arg}: ${digits}`;
1561
1820
  if (type === "references") {
1562
1821
  const association = camelize(name);
1563
1822
  return {
@@ -1573,10 +1832,11 @@ function parseColumn(arg) {
1573
1832
  name,
1574
1833
  type,
1575
1834
  notNull: bang !== void 0,
1576
- index
1835
+ index,
1836
+ ...digits
1577
1837
  };
1578
1838
  if (value === void 0) return column;
1579
- const literal = defaultOf(type, value);
1839
+ const literal = defaultOf(type, value, digits);
1580
1840
  return literal.ok ? {
1581
1841
  ...column,
1582
1842
  default: literal.value
@@ -1594,8 +1854,7 @@ function parseColumns(args) {
1594
1854
  columns: parsed
1595
1855
  };
1596
1856
  }
1597
- //#endregion
1598
- //#region cli/generate/model-file.ts
1857
+ // cli/generate/model-file.ts
1599
1858
  const library = "@forestfuture/active-record";
1600
1859
  /** A Model's file name: its class name in kebab-case (`LineItem` → `line-item.ts`). */
1601
1860
  function modelFileName(className) {
@@ -1663,8 +1922,22 @@ function appendModel(existing, model) {
1663
1922
  source: `${(model.associations.length > 0 ? importingBelongsTo(imported.source) : imported.source).trimEnd()}\n\n${classSource(model)}`
1664
1923
  };
1665
1924
  }
1666
- //#endregion
1667
- //#region cli/generate/names.ts
1925
+ // cli/generate/migration-file.ts
1926
+ /** `20261108090503`: the UTC second, as 14 digits. */
1927
+ function stamp(now) {
1928
+ return Number(now.toISOString().slice(0, 19).replaceAll(/\D/g, ""));
1929
+ }
1930
+ /**
1931
+ * The next migration's file name: the current UTC second as its version, or one past the highest
1932
+ * version there when that's later, as Rails numbers them, so two written in one second stay in
1933
+ * order. Files numbered `0001_…` sort before it, on every adapter.
1934
+ */
1935
+ function migrationFileName(existing, name, now) {
1936
+ const highest = Math.max(0, ...existing.map(leadingNumber).filter(Number.isFinite));
1937
+ const version = Math.max(stamp(now), highest + 1);
1938
+ return `${String(version).padStart(14, "0")}_${underscore(name)}.sql`;
1939
+ }
1940
+ // cli/generate/names.ts
1668
1941
  /** A name the generators accept: letters, digits and `_`, starting with a letter. */
1669
1942
  const allowed$1 = /^[A-Za-z][A-Za-z0-9_]*$/;
1670
1943
  /**
@@ -1690,8 +1963,7 @@ function modelName(given) {
1690
1963
  function migrationNameError(given) {
1691
1964
  return allowed$1.test(given) ? void 0 : `${given} isn't a migration name; use letters, digits and _, like AddSkuToProducts`;
1692
1965
  }
1693
- //#endregion
1694
- //#region cli/generate/command.ts
1966
+ // cli/generate/command.ts
1695
1967
  /** A refusal: these errors, then "Wrote nothing". */
1696
1968
  function refused(...errors) {
1697
1969
  return printing([...errors, "Wrote nothing"], 1);
@@ -1713,25 +1985,28 @@ function databaseFor(project, options) {
1713
1985
  if (typeof chosen === "string") return chosen;
1714
1986
  return project.databases.find((db) => db.target.database === chosen);
1715
1987
  }
1716
- /** Wrangler only applies migrations its `migrations_pattern` matches, so refuse any other file. */
1988
+ /** Only migrations a database's pattern matches are applied, so refuse any other file. */
1717
1989
  function patternRefusal({ project, db }, path) {
1718
1990
  const { target } = db;
1719
1991
  const pattern = target.database.migrationsPattern;
1720
1992
  const relativePath = slashed(relative(target.configDir, path));
1721
1993
  if (pattern === void 0 || process.getBuiltinModule("node:path").matchesGlob(relativePath, pattern)) return;
1722
- return `${shown$1(project.cwd, path)} wouldn't match migrations_pattern (${pattern}), so Wrangler wouldn't apply it; 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`;
1723
1995
  }
1724
- /** Each table's key type, for the columns that reference it. */
1996
+ /**
1997
+ * Each table's key column's type, for the columns that reference it: as the adapter read it, or
1998
+ * else by its attribute's type.
1999
+ */
1725
2000
  function keyTypes(tables) {
1726
2001
  return new Map(tables.map((table) => {
1727
2002
  const spec = table.attributes[table.primaryKey];
1728
- return [table.name, spec.type === "integer" ? "INTEGER" : "TEXT"];
2003
+ return [table.name, table.keyType ?? (spec.type === "integer" ? "INTEGER" : "TEXT")];
1729
2004
  }));
1730
2005
  }
1731
2006
  /** Where `g model` writes a Model: its own file, or the one file Models are appended to. */
1732
2007
  function modelPathOf(cwd, options, className) {
1733
2008
  const models = options.models ?? "src/models";
1734
- return resolve(cwd, models, oneModelsFile(models) ? "" : modelFileName(className));
2009
+ return resolve(cwd, models, isOneModelsFile(models) ? "" : modelFileName(className));
1735
2010
  }
1736
2011
  /** The Model `g model` writes, and where (its own file, or appended to one); or why it can't. */
1737
2012
  function modelFile(request) {
@@ -1739,7 +2014,7 @@ function modelFile(request) {
1739
2014
  const { cwd } = project;
1740
2015
  const { target } = db;
1741
2016
  const className = request.className;
1742
- const separateFiles = !oneModelsFile(options.models ?? "src/models");
2017
+ const separateFiles = !isOneModelsFile(options.models ?? "src/models");
1743
2018
  const path = modelPathOf(cwd, options, className);
1744
2019
  const model = {
1745
2020
  className,
@@ -1766,17 +2041,16 @@ function modelFile(request) {
1766
2041
  source: appended.source
1767
2042
  } : refused(`${shown$1(cwd, path)}: ${appended.error}`);
1768
2043
  }
1769
- /** Notes for references to tables the migrations don't make yet: their key type is a guess. */
1770
- function referenceNotes(columns, keys) {
1771
- return columns.filter((column) => column.type === "references" && !keys.has(column.references)).map((column) => `${column.references} isn't in the migrations yet, so ${column.name} is TEXT`);
1772
- }
1773
2044
  /** The migration, checked by applying it after the others in memory; or why it was refused. */
1774
- function checkedMigration(request, existing) {
1775
- const { project, db, options, columns } = request;
1776
- const { adapter } = project;
2045
+ async function checkedMigration(request, existing) {
2046
+ const { db, options, columns } = request;
1777
2047
  const { target } = db;
1778
- const migrationsTable = target.database.migrationsTable;
1779
- const current = adapter.readSchema(existing, { migrationsTable });
2048
+ const { adapter } = target;
2049
+ const { migrationsTable, entry } = target.database;
2050
+ const current = await adapter.readSchema(existing, {
2051
+ migrationsTable,
2052
+ entry
2053
+ });
1780
2054
  if (!current.ok) return refused(...current.errors);
1781
2055
  const keys = keyTypes(current.tables);
1782
2056
  const stem = request.className === void 0 ? options.name : `create_${tableize(request.className)}`;
@@ -1784,16 +2058,18 @@ function checkedMigration(request, existing) {
1784
2058
  name: stem,
1785
2059
  columns,
1786
2060
  keys,
1787
- existing: existing.map((each) => each.name),
1788
2061
  options
1789
2062
  });
1790
2063
  if (!result.ok) return refused(result.error);
1791
- const name = result.file;
2064
+ const name = migrationFileName(existing.map((each) => each.name), stem, /* @__PURE__ */ new Date());
1792
2065
  const after = [...existing, {
1793
2066
  name,
1794
2067
  sql: result.sql
1795
- }].sort((a, b) => byName$1(a.name, b.name));
1796
- const checked = adapter.readSchema(after, { migrationsTable });
2068
+ }].sort((a, b) => byVersion(a.name, b.name));
2069
+ const checked = await adapter.readSchema(after, {
2070
+ migrationsTable,
2071
+ entry
2072
+ });
1797
2073
  if (!checked.ok) return refused(...checked.errors);
1798
2074
  return {
1799
2075
  migration: {
@@ -1802,7 +2078,7 @@ function checkedMigration(request, existing) {
1802
2078
  },
1803
2079
  after,
1804
2080
  schema: checked,
1805
- notes: referenceNotes(columns, keys)
2081
+ notes: result.notes ?? []
1806
2082
  };
1807
2083
  }
1808
2084
  /** The request: the database, the columns and the names, each checked. */
@@ -1838,12 +2114,12 @@ function withModel(models, added) {
1838
2114
  return [...models.filter((each) => each.className !== added.className), added];
1839
2115
  }
1840
2116
  /** Checks everything a generator would write, before anything is written. */
1841
- function checkedFor(project, options) {
2117
+ async function checkedFor(project, options) {
1842
2118
  const request = requestFor(project, options);
1843
2119
  if (isPlan(request)) return request;
1844
2120
  const model = request.className === void 0 ? void 0 : modelFile(request);
1845
2121
  if (model !== void 0 && isPlan(model)) return model;
1846
- const checked = checkedMigration(request, request.db.migrations ?? []);
2122
+ const checked = await checkedMigration(request, request.db.migrations ?? []);
1847
2123
  if (isPlan(checked)) return checked;
1848
2124
  const refusal = patternRefusal(request, checked.migration.path);
1849
2125
  if (refusal !== void 0) return unusable(refusal);
@@ -1869,13 +2145,13 @@ function checkedFor(project, options) {
1869
2145
  * What `g model` or `g migration` writes and prints for a project: a migration (and a Model),
1870
2146
  * checked against the existing migrations, then the schema regenerated with it.
1871
2147
  */
1872
- function planGenerate(project, options) {
1873
- const checked = checkedFor(project, options);
2148
+ async function planGenerate(project, options) {
2149
+ const checked = await checkedFor(project, options);
1874
2150
  if (isPlan(checked)) return checked;
1875
2151
  const { db, migration, model, notes } = checked;
1876
2152
  const { cwd } = project;
1877
2153
  const own = model === void 0 ? [migration] : [migration, model];
1878
- const schema = schemaWrites(cwd, db, checked.schema);
2154
+ const schema = schemaWrites(project, db, checked.schema);
1879
2155
  const named = project.databases.length > 1 ? ` --database ${db.target.database.binding}` : "";
1880
2156
  return {
1881
2157
  steps: [
@@ -1895,14 +2171,11 @@ function planGenerate(project, options) {
1895
2171
  async function runGenerate(options, print) {
1896
2172
  const cwd = resolve(options.cwd ?? process.cwd());
1897
2173
  const { config, models, out } = options;
1898
- const adapter = await loadAdapter(cwd, options.adapter);
1899
- if (typeof adapter === "string") {
1900
- print(adapter);
1901
- return 1;
1902
- }
2174
+ const loaded = await loadForCommand(cwd, options, print);
2175
+ if (loaded === void 0) return 1;
1903
2176
  const model = options.kind === "model" ? modelName(options.name) : void 0;
1904
2177
  const files = model?.ok === true ? [modelPathOf(cwd, options, model.className)] : [];
1905
- const read = readProject(adapter, cwd, {
2178
+ const read = readProject(loaded, cwd, {
1906
2179
  config,
1907
2180
  models,
1908
2181
  out
@@ -1911,10 +2184,9 @@ async function runGenerate(options, print) {
1911
2184
  print(read);
1912
2185
  return 1;
1913
2186
  }
1914
- return apply(planGenerate(await withModels(read, { models }), options), cwd, print);
2187
+ return apply(await planGenerate(await withModels(read, { models }), options), cwd, print);
1915
2188
  }
1916
- //#endregion
1917
- //#region cli/generate/flags.ts
2189
+ // cli/generate/flags.ts
1918
2190
  /** `active-record g model …` and `active-record g migration …`. */
1919
2191
  const generateSubcommand = defineSubcommand({
1920
2192
  options: {
@@ -1930,11 +2202,11 @@ const generateSubcommand = defineSubcommand({
1930
2202
  datetime, json or references; then ! for NOT NULL, =value for a default, and :unique or
1931
2203
  :index for an index. For example: email:string!:unique active:boolean!=false user:references`,
1932
2204
  flagHelp: `Options for g:
1933
- --id integer Give the table an INTEGER key D1 generates (a TEXT key made in code by default)
2205
+ --id integer Give the table an integer key the database generates (a key made in code by default)
1934
2206
  --no-timestamps Leave out created_at and updated_at
1935
2207
  --models <path> Write Models here (src/models), or append them to one file (src/models.ts);
1936
2208
  ApplicationRecord is imported from the same folder
1937
- --database <name> The D1 binding to use, when the config has several
2209
+ --database <name> The database to use, when the config has several
1938
2210
  --out <file> The schema file to regenerate, when it isn't src/db/schema.ts`,
1939
2211
  action({ values, positionals }, print, fail) {
1940
2212
  const [kind, name, ...columns] = positionals;
@@ -1952,8 +2224,293 @@ datetime, json or references; then ! for NOT NULL, =value for a default, and :un
1952
2224
  }, print);
1953
2225
  }
1954
2226
  });
1955
- //#endregion
1956
- //#region cli/migrate/command.ts
2227
+ // cli/init/insert.ts
2228
+ /** Just past the comment starting at `index`, or `index` when none starts there. */
2229
+ function pastComment(text, index) {
2230
+ if (text.startsWith("//", index)) {
2231
+ const end = text.indexOf("\n", index);
2232
+ return end < 0 ? text.length : end;
2233
+ }
2234
+ if (text.startsWith("/*", index)) {
2235
+ const end = text.indexOf("*/", index + 2);
2236
+ return end < 0 ? text.length : end + 2;
2237
+ }
2238
+ return index;
2239
+ }
2240
+ /** Just past the string starting at `start`. */
2241
+ function pastString(text, start) {
2242
+ let index = start + 1;
2243
+ while (index < text.length && text[index] !== "\"") index += text[index] === "\\" ? 2 : 1;
2244
+ return index + 1;
2245
+ }
2246
+ /** The text's tokens, in order: strings, and each other character that isn't space or a comment. */
2247
+ function tokensOf(text) {
2248
+ const tokens = [];
2249
+ let index = 0;
2250
+ while (index < text.length) {
2251
+ const comment = pastComment(text, index);
2252
+ if (comment > index) index = comment;
2253
+ else if (/\s/.test(text[index])) index += 1;
2254
+ else if (text[index] === "\"") {
2255
+ const end = pastString(text, index);
2256
+ tokens.push({
2257
+ start: index,
2258
+ end,
2259
+ value: JSON.parse(text.slice(index, end)),
2260
+ string: true
2261
+ });
2262
+ index = end;
2263
+ } else {
2264
+ tokens.push({
2265
+ start: index,
2266
+ end: index + 1,
2267
+ value: text[index],
2268
+ string: false
2269
+ });
2270
+ index += 1;
2271
+ }
2272
+ }
2273
+ return tokens;
2274
+ }
2275
+ /** How a token changes the depth of nesting: an opening bracket 1, a closing one -1. */
2276
+ function depthChange({ value, string }) {
2277
+ if (string) return 0;
2278
+ if (value === "{" || value === "[") return 1;
2279
+ return value === "}" || value === "]" ? -1 : 0;
2280
+ }
2281
+ /** The index of the token that closes the object or array opened at `open`. */
2282
+ function closing(tokens, open) {
2283
+ let depth = 0;
2284
+ for (let index = open; index < tokens.length; index++) {
2285
+ depth += depthChange(tokens[index]);
2286
+ if (depth === 0) return index;
2287
+ }
2288
+ return tokens.length - 1;
2289
+ }
2290
+ /** Whether the tokens at `index` are the key `databases`, then `:` and an object's `{`. */
2291
+ function isDatabasesKey(tokens, index) {
2292
+ const key = tokens[index];
2293
+ return key.string && key.value === "databases" && tokens[index + 1]?.value === ":" && tokens[index + 2]?.value === "{";
2294
+ }
2295
+ /**
2296
+ * The indexes of the top-level `databases` object's `{` and `}`, if the text has one: the last,
2297
+ * when it has two, as JSON.parse (and so the command) reads it.
2298
+ */
2299
+ function databasesObject(tokens) {
2300
+ let depth = 0;
2301
+ let found;
2302
+ for (let index = 0; index < tokens.length; index++) {
2303
+ depth += depthChange(tokens[index]);
2304
+ if (depth === 1 && isDatabasesKey(tokens, index)) found = {
2305
+ open: index + 2,
2306
+ close: closing(tokens, index + 2)
2307
+ };
2308
+ }
2309
+ return found;
2310
+ }
2311
+ /** The whitespace a line starts with, for the line holding `at`. */
2312
+ function indentAt(text, at) {
2313
+ const lineStart = text.lastIndexOf("\n", at - 1) + 1;
2314
+ return /^[ \t]*/.exec(text.slice(lineStart))[0];
2315
+ }
2316
+ /** The end of `at`'s line, before any `\r`, when only space and comments follow it there, or `at`. */
2317
+ function endOfLine(text, at) {
2318
+ const found = text.indexOf("\n", at);
2319
+ const end = found < 0 ? text.length : found;
2320
+ const lineEnd = text[end - 1] === "\r" ? end - 1 : end;
2321
+ for (let index = at; index < lineEnd;) {
2322
+ if (text.startsWith("//", index)) return lineEnd;
2323
+ const past = pastComment(text, index);
2324
+ if (past > lineEnd) return at;
2325
+ if (past > index) index = past;
2326
+ else if (text[index] === " " || text[index] === " ") index += 1;
2327
+ else return at;
2328
+ }
2329
+ return lineEnd;
2330
+ }
2331
+ /**
2332
+ * The text with `entries` added at the end of its top-level `databases` object, each on a line of
2333
+ * its own (with the file's line endings), as the entries before it are indented, with a trailing
2334
+ * comma if the last one had one;
2335
+ * undefined when the text has no such object with an entry in it.
2336
+ */
2337
+ function withEntries(text, entries) {
2338
+ const tokens = tokensOf(text);
2339
+ const object = databasesObject(tokens);
2340
+ if (object === void 0 || object.close - object.open < 2) return void 0;
2341
+ const last = tokens[object.close - 1];
2342
+ const trailing = last.value === "," && !last.string;
2343
+ const indent = indentAt(text, tokens[object.open + 1].start);
2344
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
2345
+ const lines = entries.map(([key, value]) => {
2346
+ const fields = Object.entries(value).map(([name, field]) => `${JSON.stringify(name)}: ${JSON.stringify(field)}`);
2347
+ return `${eol}${indent}${JSON.stringify(key)}: { ${fields.join(", ")} }`;
2348
+ });
2349
+ const after = endOfLine(text, last.end);
2350
+ const added = trailing ? lines.map((line) => `${line},`).join("") : lines.join(",");
2351
+ return `${text.slice(0, last.end)}${trailing ? "" : ","}${text.slice(last.end, after)}${added}${text.slice(after)}`;
2352
+ }
2353
+ // cli/init/command.ts
2354
+ /** The JSON Schema the package ships for the file, which editors complete its keys from. */
2355
+ const schemaFile = "config-schema.json";
2356
+ /** The core package as the nearest `node_modules` holds it, or as the project's own will. */
2357
+ function installedCore(cwd, dir) {
2358
+ for (let at = dir;; at = dirname(at)) {
2359
+ const here = join(at, "node_modules", corePackage);
2360
+ if (existsSync(here)) return here;
2361
+ if (dirname(at) === at) return join(cwd, "node_modules", corePackage);
2362
+ }
2363
+ }
2364
+ /** The `$schema` link, from the file's folder to the schema in the installed package. */
2365
+ function schemaLink(cwd, dir) {
2366
+ const link = slashed(relative(dir, join(installedCore(cwd, dir), schemaFile)));
2367
+ return link.startsWith("../") ? link : `./${link}`;
2368
+ }
2369
+ /** The plugin `name`'s entries, chosen with `--adapter`, or why there are none. */
2370
+ async function chosenEntries(dir, name) {
2371
+ if (!adapterNames.includes(name)) return `--adapter takes ${listed(adapterNames)}, not ${name}`;
2372
+ const result = (await pluginOf(name)).init(dir, true);
2373
+ if (result === void 0) return `Nothing here declares a database for ${name}`;
2374
+ return typeof result === "string" ? result : {
2375
+ name,
2376
+ result
2377
+ };
2378
+ }
2379
+ /** The entries of the one adapter something in the project points to, or why there isn't one. */
2380
+ async function foundEntries(dir) {
2381
+ const found = [];
2382
+ for (const name of adapterNames) {
2383
+ const result = (await pluginOf(name)).init(dir, false);
2384
+ if (typeof result === "string") return result;
2385
+ if (result !== void 0) found.push({
2386
+ name,
2387
+ result
2388
+ });
2389
+ }
2390
+ if (found.length === 1) return found[0];
2391
+ if (found.length === 0) return `Nothing here says which database the project uses; choose ${listed(adapterNames)} 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`;
2393
+ }
2394
+ /** The file's text: the schema link, then each database with its adapter first. */
2395
+ function source(link, { name, result }) {
2396
+ const databases = Object.fromEntries(Object.entries(result.databases).map(([binding, entry]) => [binding, {
2397
+ adapter: name,
2398
+ ...entry
2399
+ }]));
2400
+ return `${JSON.stringify({
2401
+ $schema: link,
2402
+ databases
2403
+ }, null, 2)}\n`;
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
+ }
2412
+ /**
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.
2442
+ */
2443
+ async function planAdding(cwd, path, options) {
2444
+ const name = shown$1(cwd, path);
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);
2449
+ const text = readFileSync(path, "utf8");
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,
2458
+ ...entry
2459
+ }]));
2460
+ if (source === void 0) return printing([`${name}'s databases couldn't be found to add to`], 1);
2461
+ const notes = added.flatMap((each) => each.note ?? []).map((note) => printed(`Note: ${note}`));
2462
+ return {
2463
+ steps: [written({
2464
+ path,
2465
+ source
2466
+ }, addedLine(name, added)), ...notes],
2467
+ code: 0
2468
+ };
2469
+ }
2470
+ /** What `init` does: write the file, and say what's next; or say why it can't. */
2471
+ async function planInit(options) {
2472
+ const cwd = resolve(options.cwd ?? process.cwd());
2473
+ const path = resolve(cwd, options.config ?? "active-record.jsonc");
2474
+ const name = shown$1(cwd, path);
2475
+ const there = lstatSync(path, { throwIfNoEntry: false });
2476
+ if (there?.isSymbolicLink() === true) return printing([`${name} is a link; init writes nothing through it`], 1);
2477
+ if (there !== void 0) return planAdding(cwd, path, options);
2478
+ const dir = dirname(path);
2479
+ const found = options.adapter === void 0 ? await foundEntries(dir) : await chosenEntries(dir, options.adapter);
2480
+ if (typeof found === "string") return printing([found], 1);
2481
+ const bindings = listed(Object.keys(found.result.databases), "and");
2482
+ const notes = Object.values(found.result.notes ?? {}).map((note) => printed(`Note: ${note}`));
2483
+ return {
2484
+ steps: [
2485
+ written({
2486
+ path,
2487
+ source: source(schemaLink(cwd, dir), found)
2488
+ }, `Wrote ${name} (${bindings}, on ${found.name})`),
2489
+ ...notes,
2490
+ printed("Next: npx active-record schema")
2491
+ ],
2492
+ code: 0
2493
+ };
2494
+ }
2495
+ /** `active-record init`: resolves to the exit code. */
2496
+ async function runInit(options, print) {
2497
+ return apply(await planInit(options), resolve(options.cwd ?? process.cwd()), print);
2498
+ }
2499
+ // cli/init/flags.ts
2500
+ /** `active-record init`: writes the project's active-record.jsonc. */
2501
+ const initSubcommand = defineSubcommand({
2502
+ options: { adapter: { type: "string" } },
2503
+ usage: ` active-record init Write active-record.jsonc, which names your databases`,
2504
+ flagHelp: `Options for init:
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`,
2507
+ action({ values, positionals }, print, fail) {
2508
+ if (positionals.length > 0) return fail(`Unexpected ${positionals[0]}`);
2509
+ const { help: _, ...options } = values;
2510
+ return runInit(options, print);
2511
+ }
2512
+ });
2513
+ // cli/migrate/command.ts
1957
2514
  const standardIo = () => ({
1958
2515
  input: process.stdin,
1959
2516
  output: process.stdout,
@@ -1975,16 +2532,14 @@ async function allowed(target, options, io) {
1975
2532
  /** `active-record migrate`: resolves to the exit code, the adapter's own when it ran. */
1976
2533
  async function runMigrate(options, print, io = standardIo()) {
1977
2534
  const cwd = options.cwd ?? process.cwd();
1978
- const adapter = await loadAdapter(cwd, options.adapter);
1979
- if (typeof adapter === "string") {
1980
- print(adapter);
1981
- return 1;
1982
- }
1983
- const chosen = chosenDatabase(adapter, cwd, options);
1984
- if (typeof chosen === "string") {
1985
- 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);
1986
2540
  return 1;
1987
2541
  }
2542
+ const { adapter, chosen } = found;
1988
2543
  const remote = options.remote === true;
1989
2544
  if (remote) {
1990
2545
  const target = adapter.remote(chosen, "migrate");
@@ -1996,8 +2551,7 @@ async function runMigrate(options, print, io = standardIo()) {
1996
2551
  }
1997
2552
  return adapter.migrate(cwd, chosen, { remote }, { output: (text) => io.output.write(text) });
1998
2553
  }
1999
- //#endregion
2000
- //#region cli/migrate/flags.ts
2554
+ // cli/migrate/flags.ts
2001
2555
  /** `active-record migrate`: applies the pending migrations, to the local database or the real one. */
2002
2556
  const migrateSubcommand = defineSubcommand({
2003
2557
  options: {
@@ -2017,8 +2571,7 @@ const migrateSubcommand = defineSubcommand({
2017
2571
  return runMigrate(options, print);
2018
2572
  }
2019
2573
  });
2020
- //#endregion
2021
- //#region cli/schema/command.ts
2574
+ // cli/schema/command.ts
2022
2575
  /** A schema that couldn't be generated: the errors, and that the last good file stays as it was. */
2023
2576
  function failed(errors, cwd, db) {
2024
2577
  const out = shown$1(cwd, db.target.out);
@@ -2026,41 +2579,41 @@ function failed(errors, cwd, db) {
2026
2579
  return printing([...errors, kept], 1);
2027
2580
  }
2028
2581
  /** `--check`: whether the file on disk was generated from these tables (its fingerprint, not its format). */
2029
- function checkPlan(cwd, db, tables) {
2030
- const out = shown$1(cwd, db.target.out);
2582
+ function checkPlan(project, db, tables) {
2583
+ const out = shown$1(project.cwd, db.target.out);
2031
2584
  const schema = schemaSourceOf(db, tables);
2032
2585
  const current = db.schema !== void 0 && fingerprintIn(db.schema) === fingerprintOf(schema);
2033
2586
  return printing([current ? `${out} is up to date` : `${out} is out of date: run \`active-record schema\``], current ? 0 : 1);
2034
2587
  }
2035
2588
  /** One database's schema, generated (or, with `check`, checked). */
2036
- function planDatabase(project, db, check) {
2037
- const { adapter, cwd } = project;
2589
+ async function planDatabase(project, db, check) {
2590
+ const { cwd } = project;
2038
2591
  if (db.migrations === void 0) return failed([`No migrations folder at ${shown$1(cwd, db.target.migrationsDir)}/`], cwd, db);
2039
2592
  const refusal = check ? void 0 : schemaRefusal(cwd, db);
2040
2593
  if (refusal !== void 0) return failed([refusal], cwd, db);
2041
2594
  if (db.modelErrors.length > 0) return failed(db.modelErrors, cwd, db);
2042
- const migrationsTable = db.target.database.migrationsTable;
2043
- const result = adapter.readSchema(db.migrations, { migrationsTable });
2595
+ const { migrationsTable, entry } = db.target.database;
2596
+ const result = await db.target.adapter.readSchema(db.migrations, {
2597
+ migrationsTable,
2598
+ entry
2599
+ });
2044
2600
  if (!result.ok) return failed(result.errors, cwd, db);
2045
- return check ? checkPlan(cwd, db, result.tables) : schemaWrites(cwd, db, result);
2601
+ return check ? checkPlan(project, db, result.tables) : schemaWrites(project, db, result);
2046
2602
  }
2047
2603
  /** What `active-record schema` writes and prints for a project (or, with `check`, only prints). */
2048
- function planSchema(project, check) {
2049
- return combined(project.databases.map((db) => planDatabase(project, db, check)));
2604
+ async function planSchema(project, check) {
2605
+ return combined(await Promise.all(project.databases.map((db) => planDatabase(project, db, check))));
2050
2606
  }
2051
2607
  /**
2052
- * `active-record schema`: generates each D1 database's `schema.ts` from its migrations and the Models
2608
+ * `active-record schema`: generates each database's `schema.ts` from its migrations and the Models
2053
2609
  * built on it (#66, #68, #232). Resolves to the exit code: 0, or 1 when anything failed or, with
2054
2610
  * `check`, is out of date.
2055
2611
  */
2056
2612
  async function runSchema(options, print) {
2057
2613
  const cwd = resolve(options.cwd ?? process.cwd());
2058
- const adapter = await loadAdapter(cwd, options.adapter);
2059
- if (typeof adapter === "string") {
2060
- print(adapter);
2061
- return 1;
2062
- }
2063
- 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);
2064
2617
  if (typeof read === "string") {
2065
2618
  print(read);
2066
2619
  return 1;
@@ -2069,7 +2622,21 @@ async function runSchema(options, print) {
2069
2622
  models: options.models,
2070
2623
  check: options.check
2071
2624
  });
2072
- return apply(planSchema(project, options.check === true), project.cwd, print);
2625
+ return apply(await planSchema(project, options.check === true), project.cwd, print);
2626
+ }
2627
+ /**
2628
+ * `active-record schema --watch` from the command line: watching, once its adapter loads; or, when
2629
+ * it can't (none installed, or a Node it can't run on), 1, having said why, as a run without
2630
+ * `--watch` would.
2631
+ */
2632
+ async function watchFromCommandLine(options, print) {
2633
+ const loaded = await loadDatabases(resolve(options.cwd ?? process.cwd()), options.config);
2634
+ if (typeof loaded === "string") {
2635
+ print(loaded);
2636
+ return 1;
2637
+ }
2638
+ watchSchema(options, print);
2639
+ return "watching";
2073
2640
  }
2074
2641
  /**
2075
2642
  * `active-record schema --watch`: generates, then again whenever a migration or a Model file changes,
@@ -2078,9 +2645,9 @@ async function runSchema(options, print) {
2078
2645
  async function watchSchema(options, print) {
2079
2646
  let running = runSchema(options, print);
2080
2647
  const cwd = resolve(options.cwd ?? process.cwd());
2081
- const adapter = await loadAdapter(cwd, options.adapter);
2082
- if (typeof adapter === "string") return () => {};
2083
- 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);
2084
2651
  if (typeof project === "string") return () => {};
2085
2652
  let pending;
2086
2653
  const regenerate = () => {
@@ -2095,10 +2662,10 @@ async function watchSchema(options, print) {
2095
2662
  for (const watcher of watchers) watcher.close();
2096
2663
  };
2097
2664
  }
2098
- //#endregion
2099
- //#region cli/main.ts
2665
+ // cli/main.ts
2100
2666
  /** Each subcommand by the names it answers to. */
2101
2667
  const subcommands = {
2668
+ init: initSubcommand,
2102
2669
  schema: defineSubcommand({
2103
2670
  options: {
2104
2671
  check: { type: "boolean" },
@@ -2107,7 +2674,7 @@ const subcommands = {
2107
2674
  migrations: { type: "string" },
2108
2675
  models: { type: "string" }
2109
2676
  },
2110
- usage: ` active-record schema [options] Generate src/db/schema.ts from your D1 migrations`,
2677
+ usage: ` active-record schema [options] Generate src/db/schema.ts from your migrations`,
2111
2678
  flagHelp: `Options for schema:
2112
2679
  --check Fail if the generated schema is out of date (for CI)
2113
2680
  --watch Regenerate whenever a migration changes
@@ -2117,9 +2684,7 @@ const subcommands = {
2117
2684
  action({ values, positionals }, print, fail) {
2118
2685
  const { watch, help: _, ...options } = values;
2119
2686
  if (positionals.length > 0) return fail(`Unexpected ${positionals[0]}`);
2120
- if (!watch) return runSchema(options, print);
2121
- watchSchema(options, print);
2122
- return "watching";
2687
+ return watch ? watchFromCommandLine(options, print) : runSchema(options, print);
2123
2688
  }
2124
2689
  }),
2125
2690
  g: generateSubcommand,
@@ -2134,7 +2699,17 @@ function usage(print, problem) {
2134
2699
  print(`${problem}\n\n${help}`);
2135
2700
  return 1;
2136
2701
  }
2137
- /** Runs the command line; resolves to the exit code (or never, while watching). */
2702
+ /**
2703
+ * Whether this Node has what the command itself uses: `process.getBuiltinModule`, `fs.globSync`
2704
+ * and `path.matchesGlob` (Node 22.5; Node 20 has only the first and last). A plugin says what
2705
+ * it needs itself, with `unsupported`.
2706
+ */
2707
+ function isSupportedNode() {
2708
+ if (typeof process.getBuiltinModule !== "function") return false;
2709
+ const { globSync } = process.getBuiltinModule("node:fs");
2710
+ return globSync !== void 0 && process.getBuiltinModule("node:path").matchesGlob !== void 0;
2711
+ }
2712
+ /** Runs the command line: the exit code, or "watching" while `schema --watch` runs on. */
2138
2713
  function main(argv, print = console.log) {
2139
2714
  const [command = "", ...rest] = argv;
2140
2715
  const subcommand = Object.hasOwn(subcommands, command) ? subcommands[command] : void 0;
@@ -2143,15 +2718,13 @@ function main(argv, print = console.log) {
2143
2718
  print(help);
2144
2719
  return asked ? 0 : 1;
2145
2720
  }
2146
- if (process.getBuiltinModule?.("node:sqlite") === void 0) {
2147
- print(`active-record ${command} needs Node 22.13 or later, for node:sqlite (this is Node ${process.versions.node})`);
2721
+ if (!isSupportedNode()) {
2722
+ print(`active-record ${command} needs Node 22.5 or later (this is Node ${process.versions.node})`);
2148
2723
  return 1;
2149
2724
  }
2150
2725
  return subcommand.run(rest, print, (problem) => usage(print, problem));
2151
2726
  }
2152
- //#endregion
2153
- //#region cli/bin.ts
2727
+ // cli/bin.ts
2154
2728
  const code = await main(process.argv.slice(2));
2155
2729
  if (code !== "watching") process.exitCode = code;
2156
- //#endregion
2157
2730
  export {};