@forestfuture/active-record 0.0.0 → 0.7.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.
@@ -0,0 +1,2471 @@
1
+ #!/usr/bin/env node
2
+ import { J as tableize, Y as ancestors, i as isBase } from "./generated-model-Cnt0Ot9q.mjs";
3
+ import { a as underscore, i as camelize, n as pluralize, r as singularize } from "./epoch-storage-o2aoOH7H.mjs";
4
+ import { _ as shown$1, a as isIdentifier, f as byVersion, g as importPath, h as migrationsOf, l as parseJsonc, m as leadingNumber, o as listed, p as hasNestedMigrations, r as classify, s as moduleName, t as storageOverride, u as projectDatabases, v as slashed } from "./storage-override-CpbkdIqE.mjs";
5
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
6
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
7
+ import { inspect, parseArgs, types } from "node:util";
8
+ import { WriteStream } from "node:tty";
9
+ import { createInterface } from "node:readline";
10
+ import { createJiti } from "jiti";
11
+ import { Console } from "node:console";
12
+ import { PassThrough, Readable, Writable } from "node:stream";
13
+ import { AsyncLocalStorage } from "node:async_hooks";
14
+ import repl from "node:repl";
15
+ import { createHash } from "node:crypto";
16
+ //#region cli/subcommand.ts
17
+ /** The flags every subcommand takes. */
18
+ const sharedOptions = {
19
+ config: { type: "string" },
20
+ help: {
21
+ type: "boolean",
22
+ short: "h"
23
+ }
24
+ };
25
+ /** The help for the shared flags, after every subcommand's own. */
26
+ const sharedFlagHelp = `Options for every command:
27
+ --config <file> Use this config file, in place of active-record.jsonc
28
+ -h, --help Show this help`;
29
+ /** A subcommand from its spec: its `action` gets the command line parsed, or `fail` says why it can't be. */
30
+ function defineSubcommand(spec) {
31
+ const { options: own, action, ...help } = spec;
32
+ const options = {
33
+ ...sharedOptions,
34
+ ...own
35
+ };
36
+ return {
37
+ ...help,
38
+ options,
39
+ run(argv, print, fail) {
40
+ let parsed;
41
+ try {
42
+ parsed = parseArgs({
43
+ args: [...argv],
44
+ allowPositionals: true,
45
+ options
46
+ });
47
+ } catch (error) {
48
+ return fail(error.message);
49
+ }
50
+ return action(parsed, print, fail);
51
+ }
52
+ };
53
+ }
54
+ /** The usage: every subcommand's Usage lines, its notes, its flags, then the shared flags. */
55
+ function helpFor(subcommands) {
56
+ const usage = `Usage:\n${subcommands.map((subcommand) => subcommand.usage).join("\n")}`;
57
+ const notes = subcommands.flatMap((subcommand) => subcommand.notes ?? []);
58
+ const flags = subcommands.map((subcommand) => subcommand.flagHelp);
59
+ return [
60
+ usage,
61
+ ...notes,
62
+ ...flags,
63
+ sharedFlagHelp
64
+ ].join("\n\n");
65
+ }
66
+ //#endregion
67
+ //#region cli/project/adapters.ts
68
+ /** Each adapter a database's `adapter` names. Its plugin ships with the command, loaded when it's used. */
69
+ const adapters = {
70
+ d1: {
71
+ entry: "@forestfuture/active-record/d1",
72
+ plugin: async () => (await import("./plugin-Cyoej7qV.mjs")).cli
73
+ },
74
+ postgresql: {
75
+ entry: "@forestfuture/active-record/postgresql",
76
+ plugin: async () => (await import("./plugin-XOHYndhP.mjs")).cli
77
+ }
78
+ };
79
+ /** The adapters' names, in the registry's order. */
80
+ const adapterNames = Object.keys(adapters);
81
+ /** The entry an adapter's factory and `connect` are imported from, as the registry names it. */
82
+ function adapterEntry(adapter) {
83
+ return adapters[adapter.name]?.entry ?? adapter.name;
84
+ }
85
+ /** What's wrong with a database's `adapter`, if anything. */
86
+ function adapterError(binding, adapter) {
87
+ if (adapter === void 0) {
88
+ const quoted = adapterNames.map((name) => JSON.stringify(name));
89
+ return `databases.${binding} has no adapter (add "adapter": ${listed(quoted)})`;
90
+ }
91
+ if (typeof adapter === "string" && Object.hasOwn(adapters, adapter)) return void 0;
92
+ return `databases.${binding} has the adapter ${JSON.stringify(adapter)}, which isn't ${listed(adapterNames)}`;
93
+ }
94
+ /** The one adapter the project's databases name, or why there isn't one (#305). */
95
+ function adapterNamed(project) {
96
+ const file = basename(project.file);
97
+ const entries = Object.entries(project.databases);
98
+ for (const [binding, entry] of entries) {
99
+ const error = adapterError(binding, entry.adapter);
100
+ if (error !== void 0) return `${file}: ${error}`;
101
+ }
102
+ const named = new Set(entries.map(([, entry]) => entry.adapter));
103
+ if (named.size === 1) return { name: [...named][0] };
104
+ return `${file} names more than one adapter (${entries.map(([binding, entry]) => `${String(entry.adapter)} for ${binding}`).join(", ")}); a project uses one, for now`;
105
+ }
106
+ /** The notes the project's adapter has about its databases, as the command prints them. */
107
+ function configNotes(adapter) {
108
+ const config = adapter.databases();
109
+ return config.ok ? (config.notes ?? []).map((note) => `Note: ${note}`) : [];
110
+ }
111
+ /** The plugin of the adapter `name`. */
112
+ function pluginOf(name) {
113
+ return adapters[name].plugin();
114
+ }
115
+ /**
116
+ * The project's adapter, as its `active-record.jsonc` (or the file `configPath` names) names it, with
117
+ * its plugin reading the databases there; or a message saying what to do.
118
+ */
119
+ async function loadAdapter(cwd, configPath) {
120
+ const project = projectDatabases(cwd, configPath);
121
+ if (typeof project === "string") return project;
122
+ const named = adapterNamed(project);
123
+ if (typeof named === "string") return named;
124
+ const plugin = await pluginOf(named.name);
125
+ return plugin.unsupported?.() ?? {
126
+ ...plugin,
127
+ databases: () => plugin.databases(project)
128
+ };
129
+ }
130
+ //#endregion
131
+ //#region cli/project/databases.ts
132
+ /**
133
+ * The database a command works on: the only one, or the one `--database` names; or, as a message
134
+ * to print, why there isn't one (several and none named, or a name no binding has).
135
+ */
136
+ function chooseDatabase(databases, named) {
137
+ const bindings = listed(databases.map((database) => database.binding));
138
+ if (named === void 0) {
139
+ if (databases.length === 1) return databases[0];
140
+ return `This config has several databases; choose one with --database (${bindings})`;
141
+ }
142
+ return databases.find((database) => database.binding === named) ?? `No database is bound as ${named}; this config has ${bindings}`;
143
+ }
144
+ /** The database for `--database` (and `--config`), with its config file, or why there isn't one. */
145
+ function chosenDatabase(adapter, cwd, options) {
146
+ const config = adapter.databases();
147
+ if (!config.ok) return config.error;
148
+ const chosen = chooseDatabase(config.databases, options.database);
149
+ if (typeof chosen === "string") return chosen;
150
+ const { binding, entry } = chosen;
151
+ const migrationsDir = resolve(config.dir, chosen.migrationsDir);
152
+ return {
153
+ binding,
154
+ entry,
155
+ configFile: config.file,
156
+ migrationsDir
157
+ };
158
+ }
159
+ //#endregion
160
+ //#region cli/console/verbose.ts
161
+ /**
162
+ * One line for a statement, as `onQuery` saw it (filtered values are already `[FILTERED]`):
163
+ * ` User 1.2ms SELECT … WHERE "id" = ? [ 1 ]`, or `failed` and the reason in place of the time
164
+ * and values. Dim on a terminal, so it reads as background to the results.
165
+ */
166
+ function statementLine(event, dim) {
167
+ const { model, params, durationMs, error } = event;
168
+ const sql = event.sql.replace(/\s*\n\s*/g, " ");
169
+ let line = ` ${model} `;
170
+ if (error !== void 0) line += `failed ${sql} ${error instanceof Error ? error.message : inspect(error)}`;
171
+ else {
172
+ line += `${durationMs.toFixed(1)}ms ${sql}`;
173
+ if (params.length > 0) line += ` ${inspect(params, { breakLength: Number.POSITIVE_INFINITY })}`;
174
+ }
175
+ return dim ? `\u001b[2m${line}\u001b[22m` : line;
176
+ }
177
+ //#endregion
178
+ //#region cli/console/commands.ts
179
+ /**
180
+ * The commands, and the `onQuery` the console's database is connected with. They share one
181
+ * switch: `.verbose` flips what the listener does.
182
+ */
183
+ function consoleCommands(project, { verbose, write, dim }) {
184
+ let showing = verbose;
185
+ return {
186
+ onQuery: (event) => {
187
+ if (showing) write(statementLine(event, dim));
188
+ },
189
+ commands: {
190
+ verbose: {
191
+ help: "Show the SQL each line runs: .verbose, .verbose on, or .verbose off (also: verbose!)",
192
+ bang: true,
193
+ run: (argument) => {
194
+ const word = argument.trim().toLowerCase();
195
+ if (word !== "" && word !== "on" && word !== "off") return "Use .verbose, .verbose on, or .verbose off";
196
+ showing = word === "" ? !showing : word === "on";
197
+ return `SQL logging ${showing ? "on" : "off"}`;
198
+ }
199
+ },
200
+ reload: {
201
+ help: "Read your Models again, after editing them (also: reload!)",
202
+ bang: true,
203
+ run: async (_argument, scope) => {
204
+ const before = Object.keys(project.models);
205
+ const again = await project.reload();
206
+ if (typeof again === "string") return again;
207
+ for (const name of before) delete scope[name];
208
+ Object.assign(scope, again);
209
+ return `Reloaded: ${Object.keys(again).join(", ")}`;
210
+ }
211
+ }
212
+ }
213
+ };
214
+ }
215
+ //#endregion
216
+ //#region cli/console/confirm.ts
217
+ /** How long input must stay quiet, once released, for what was already on its way to have arrived. */
218
+ const QUIET_MS = 50;
219
+ /** Reads and drops everything on `input` until the returned function is called and it is quiet. */
220
+ function discarding(input) {
221
+ const drop = () => {};
222
+ input.on("data", drop);
223
+ input.resume();
224
+ return async () => {
225
+ await new Promise((resolve) => setTimeout(resolve, QUIET_MS));
226
+ input.off("data", drop);
227
+ input.pause();
228
+ };
229
+ }
230
+ /**
231
+ * Names the remote database and asks for its name; confirmed only when that is what is typed.
232
+ * Anything else, a blank line, or the end of the input cancels. It reads one line, and then
233
+ * drops what follows (see `Confirmation.release`).
234
+ */
235
+ async function confirmRemote({ input, output, target, consequence = "What you change in the console is changed in this database, not a copy." }) {
236
+ const note = target.note === void 0 ? "" : `${target.note}\n`;
237
+ output.write(`${target.description}\n${note}${consequence}\nType its name to continue, anything else cancels: `);
238
+ const reader = createInterface({
239
+ input,
240
+ terminal: false
241
+ });
242
+ const typed = await new Promise((resolve) => {
243
+ reader.once("line", resolve);
244
+ reader.once("close", () => resolve(void 0));
245
+ });
246
+ reader.close();
247
+ const release = discarding(input);
248
+ return {
249
+ confirmed: typed !== void 0 && target.name !== "" && typed.trim() === target.name,
250
+ release
251
+ };
252
+ }
253
+ //#endregion
254
+ //#region cli/project/targets.ts
255
+ /**
256
+ * A database's base class: `ApplicationRecord` when there's one database, as in Rails, and one
257
+ * per binding when there are several (`LOGS` → `LogsRecord`), as Rails names them.
258
+ */
259
+ function baseFor(modelsDir, binding, several) {
260
+ if (!several) return {
261
+ path: join(modelsDir, "application-record.ts"),
262
+ className: "ApplicationRecord"
263
+ };
264
+ const className = `${classify(binding.toLowerCase())}Record`;
265
+ return {
266
+ path: join(modelsDir, `${moduleName(className)}.ts`),
267
+ className
268
+ };
269
+ }
270
+ /** Where Models and their base class go without `--models`. */
271
+ const defaultModels = "src/models";
272
+ /** Whether `--models` names one file all Models go in (`src/models.ts`), not a folder. */
273
+ function oneModelsFile(models) {
274
+ return models.endsWith(".ts");
275
+ }
276
+ /** The folder Models and their base class live in: `--models`, or `src/models`. */
277
+ function modelsDirOf(cwd, models = defaultModels) {
278
+ const path = resolve(cwd, models);
279
+ return oneModelsFile(models) ? dirname(path) : path;
280
+ }
281
+ /** The Model folder to watch, when it exists: `--models`'s, or the one holding its one file. */
282
+ function modelsFolders(cwd, models = defaultModels) {
283
+ const folder = modelsDirOf(cwd, models);
284
+ return existsSync(folder) ? [folder] : [];
285
+ }
286
+ /** Bindings whose base classes would be the same (`DB` and `db` → `DbRecord`), as an error. */
287
+ function sharedBase(targets) {
288
+ const seen = /* @__PURE__ */ new Map();
289
+ for (const { database, base } of targets) {
290
+ const other = seen.get(base.className);
291
+ if (other !== void 0) return `The bindings ${other} and ${database.binding} would share the base class ${base.className}; rename one`;
292
+ seen.set(base.className, database.binding);
293
+ }
294
+ }
295
+ /** The databases to generate, from the adapter's config and the options; or why there are none. */
296
+ function targetsOf(adapter, cwd, options) {
297
+ const config = adapter.databases();
298
+ if (!config.ok) return config.error;
299
+ const { databases, dir, file } = config;
300
+ if (options.migrations !== void 0 && databases.length > 1) return `--migrations needs a single database; this config has ${databases.length}`;
301
+ const targets = databases.map((database) => {
302
+ const migrationsDir = resolve(cwd, options.migrations ?? join(dir, database.migrationsDir));
303
+ const out = databases.length === 1 ? resolve(cwd, options.out ?? "src/db/schema.ts") : resolve(cwd, options.out ?? "src/db", `${database.binding}.ts`);
304
+ const base = baseFor(modelsDirOf(cwd, options.models), database.binding, databases.length > 1);
305
+ return {
306
+ database,
307
+ configFile: file,
308
+ configDir: dir,
309
+ migrationsDir,
310
+ out,
311
+ base
312
+ };
313
+ });
314
+ return sharedBase(targets) ?? targets;
315
+ }
316
+ //#endregion
317
+ //#region cli/project/load.ts
318
+ /**
319
+ * A jiti based in the project: it reads TypeScript, extensionless imports and `tsconfig.json`
320
+ * paths, and resolves the library (`@forestfuture/active-record` and its adapter's package)
321
+ * from the project's `node_modules`, so the Models and the command share a single copy of it.
322
+ */
323
+ function projectJiti(cwd) {
324
+ return createJiti(`${cwd}/`, {
325
+ tsconfigPaths: true,
326
+ fsCache: false,
327
+ moduleCache: true
328
+ });
329
+ }
330
+ /** The Model files: the folder's `.ts` files, or the one file `--models` names. */
331
+ function modelFiles(cwd, models) {
332
+ const path = resolve(cwd, models);
333
+ if (!existsSync(path)) return `No Models at ${shown$1(cwd, path)} (run active-record g model, or pass --models)`;
334
+ if (oneModelsFile(models) || statSync(path).isFile()) return [path];
335
+ return readdirSync(path).filter((name) => name.endsWith(".ts") && !name.endsWith(".d.ts")).sort().map((name) => join(path, name));
336
+ }
337
+ /** The core, which every command loads from the project, beside the adapter some need. */
338
+ const corePackage = "@forestfuture/active-record";
339
+ /** Whether `error` is the loader failing to find `name` itself, not something it imports. */
340
+ function isMissing(error, name) {
341
+ const { code, message } = error;
342
+ return (code === "MODULE_NOT_FOUND" || code === "ERR_MODULE_NOT_FOUND") && String(message).startsWith(`Cannot find module '${name}'`);
343
+ }
344
+ /**
345
+ * The project's own copies of `packages` (the core, and the adapter when a command needs it), as
346
+ * one module, or why one can't be loaded, naming it. Each is imported from a file in the project,
347
+ * as its Models import it, because only imports made inside a file follow a `tsconfig.json` path
348
+ * (a workspace link), and so the Models and the command get one copy.
349
+ */
350
+ async function loadLibrary(cwd, jiti, { command, packages }) {
351
+ const filename = join(cwd, `active-record-${command}.ts`);
352
+ let library = {};
353
+ for (const name of packages) try {
354
+ const source = `export * from "${name}";`;
355
+ const loaded = await jiti.evalModule(source, {
356
+ filename,
357
+ async: true
358
+ });
359
+ library = {
360
+ ...library,
361
+ ...loaded
362
+ };
363
+ } catch (error) {
364
+ if (isMissing(error, name)) return `${name} isn't installed here (install it, then run active-record ${command} again)`;
365
+ return `Couldn't load ${name}: ${error.message}`;
366
+ }
367
+ return library;
368
+ }
369
+ /**
370
+ * Forgets the project's own modules, so they are read again. Its dependencies stay as they are,
371
+ * and so do `keep` (the library's files, which may sit under the project's folder).
372
+ */
373
+ function forgetProjectFiles(cwd, jiti, keep) {
374
+ const folder = `${slashed(resolve(cwd))}/`;
375
+ for (const file of Object.keys(jiti.cache)) {
376
+ const name = slashed(file);
377
+ if (name.startsWith(folder) && !name.includes("/node_modules/") && !keep.has(file)) delete jiti.cache[file];
378
+ }
379
+ }
380
+ //#endregion
381
+ //#region cli/console/project.ts
382
+ /** The Model classes the files export, by name; or the file that couldn't be loaded. */
383
+ async function loadModels(cwd, jiti, files, library) {
384
+ const found = {};
385
+ for (const file of files) {
386
+ let exported;
387
+ try {
388
+ exported = await jiti.import(file);
389
+ } catch (error) {
390
+ const message = error.message.replaceAll(`${resolve(cwd)}${sep}`, "");
391
+ return `Couldn't load ${shown$1(cwd, file)}: ${message}`;
392
+ }
393
+ for (const [name, value] of Object.entries(exported)) if (typeof value === "function" && value.prototype instanceof library.Model && !isBase(value)) found[name] = value;
394
+ }
395
+ return found;
396
+ }
397
+ /** The Models found in the files now, or why there are none to use. */
398
+ async function modelsIn$1(cwd, models, jiti, library) {
399
+ const files = modelFiles(cwd, models);
400
+ if (typeof files === "string") return files;
401
+ const found = await loadModels(cwd, jiti, files, library);
402
+ if (typeof found === "string") return found;
403
+ if (Object.keys(found).length === 0) return `No Models in ${shown$1(cwd, resolve(cwd, models))} (run active-record g model, or pass --models)`;
404
+ return found;
405
+ }
406
+ /**
407
+ * The project's Models and library, loaded as its own code would load them: one `jiti` based in
408
+ * the project reads TypeScript, extensionless imports and `tsconfig.json` paths, and resolves
409
+ * the library from the project's `node_modules`, so the Models and the console
410
+ * share a single copy of the library. Or why they can't be loaded.
411
+ */
412
+ async function loadProject(adapterPackage, cwd, models = defaultModels) {
413
+ const files = modelFiles(cwd, models);
414
+ if (typeof files === "string") return files;
415
+ const jiti = projectJiti(cwd);
416
+ const loadedBefore = new Set(Object.keys(jiti.cache));
417
+ const library = await loadLibrary(cwd, jiti, {
418
+ command: "console",
419
+ packages: [corePackage, adapterPackage]
420
+ });
421
+ if (typeof library === "string") return library;
422
+ const libraryFiles = new Set(Object.keys(jiti.cache).filter((file) => !loadedBefore.has(file)));
423
+ const found = await modelsIn$1(cwd, models, jiti, library);
424
+ if (typeof found === "string") return found;
425
+ const project = {
426
+ library,
427
+ models: found,
428
+ reload: async () => {
429
+ forgetProjectFiles(cwd, jiti, libraryFiles);
430
+ const again = await modelsIn$1(cwd, models, jiti, library);
431
+ if (typeof again !== "string") project.models = again;
432
+ return again;
433
+ }
434
+ };
435
+ return project;
436
+ }
437
+ //#endregion
438
+ //#region cli/console/session.ts
439
+ /** A line that is just `quit` or `exit`: leaves the console, as `.exit` does. */
440
+ const leaving = /^\s*(?:quit|exit)\s*;?\s*$/;
441
+ /** A line that is just `name!`: one of the console's commands, as a bare word. */
442
+ const bangLine = /^\s*([A-Za-z_]\w*)!\s*;?\s*$/;
443
+ /**
444
+ * Runs a task inside the project's database. While a line awaits, the REPL holds the next one back
445
+ * and then runs it from inside that line's async context, where the database is already
446
+ * registered. Wrapping it again would register it twice, which reads as "several databases": so a
447
+ * task already inside one isn't wrapped.
448
+ */
449
+ function databaseRunner(withDatabase) {
450
+ const wrapped = new AsyncLocalStorage();
451
+ return (task) => {
452
+ if (wrapped.getStore() === true) task();
453
+ else withDatabase(() => wrapped.run(true, task));
454
+ };
455
+ }
456
+ /**
457
+ * What each line of a script came to. A line's callback has its value or what it threw; a rejected
458
+ * `await` never calls back, so then it is what the REPL wrote. Half a statement (a `Recoverable`)
459
+ * is not an outcome: the REPL waits for the rest of it. The first failure closes the session.
460
+ */
461
+ function scripted(script, close) {
462
+ let outcome;
463
+ let unfinished = false;
464
+ return {
465
+ /** The callback to evaluate the next line with. */
466
+ start(callback) {
467
+ outcome = void 0;
468
+ unfinished = false;
469
+ script?.reset();
470
+ if (script === void 0) return callback;
471
+ return (error, result) => {
472
+ if (error instanceof repl.Recoverable) unfinished = true;
473
+ else outcome = error === null ? {
474
+ ok: true,
475
+ value: result
476
+ } : {
477
+ ok: false,
478
+ error
479
+ };
480
+ callback(error, result);
481
+ };
482
+ },
483
+ /** The input ended: a statement left unfinished is a failure, as the REPL would drop it. */
484
+ ended() {
485
+ if (script !== void 0 && unfinished) script.report({
486
+ ok: false,
487
+ error: /* @__PURE__ */ new SyntaxError("Unexpected end of input")
488
+ });
489
+ },
490
+ /** The REPL asked for the next line: the one in flight is over. */
491
+ finish() {
492
+ if (script === void 0 || unfinished) return;
493
+ const wrote = script.written();
494
+ const reported = outcome ?? (wrote === void 0 ? {
495
+ ok: true,
496
+ value: void 0
497
+ } : {
498
+ ok: false,
499
+ error: wrote.value
500
+ });
501
+ script.report(reported);
502
+ if (!reported.ok) close();
503
+ }
504
+ };
505
+ }
506
+ /**
507
+ * The REPL's lines, run one at a time inside the project's `withDatabase`. The REPL's input events
508
+ * don't inherit an async context, so each line gets its own: the Models' statics find the
509
+ * session's database, and so do the records they load. Lines pasted or piped arrive together, but
510
+ * each waits for the one before it (an `await` in the first may be what the second uses).
511
+ */
512
+ function lineQueue() {
513
+ let tail = Promise.resolve();
514
+ let lineDone;
515
+ let stopped = false;
516
+ return {
517
+ /** Settles when every line so far has finished; a later line makes the next one. */
518
+ pending: () => tail,
519
+ /** Runs `task` after the lines before it, and before the ones after. It must not throw. */
520
+ enqueue(task) {
521
+ tail = tail.then(() => stopped ? void 0 : task());
522
+ },
523
+ attach(server, withDatabase, command, script) {
524
+ const evaluate = server.eval;
525
+ const inTheDatabase = databaseRunner(withDatabase);
526
+ const displayPrompt = server.displayPrompt.bind(server);
527
+ const tracker = scripted(script, () => {
528
+ stopped = true;
529
+ server.close();
530
+ });
531
+ server.once("exit", () => tracker.ended());
532
+ server.displayPrompt = (preserveCursor) => {
533
+ try {
534
+ displayPrompt(preserveCursor);
535
+ } finally {
536
+ tracker.finish();
537
+ lineDone?.();
538
+ }
539
+ };
540
+ const inDatabase = (code, context, file, callback) => {
541
+ if (!code.endsWith("\n")) {
542
+ inTheDatabase(() => evaluate.call(server, code, context, file, callback));
543
+ return;
544
+ }
545
+ tail = tail.then(() => new Promise((done) => {
546
+ if (stopped) return done();
547
+ const ran = command(code);
548
+ if (ran !== void 0) {
549
+ ran.then(done);
550
+ return;
551
+ }
552
+ if (leaving.test(code)) {
553
+ stopped = true;
554
+ server.close();
555
+ return done();
556
+ }
557
+ lineDone = done;
558
+ const settled = tracker.start(callback);
559
+ inTheDatabase(() => evaluate.call(server, code, context, file, settled));
560
+ }));
561
+ };
562
+ server.eval = inDatabase;
563
+ }
564
+ };
565
+ }
566
+ /**
567
+ * Piped input as the REPL sees it: its end waits until every line has finished. The REPL closes at
568
+ * once when its input ends, even with an `await` still running, and then shows no more prompts.
569
+ */
570
+ function untilDrained(input, pending) {
571
+ const gated = new PassThrough();
572
+ input.pipe(gated, { end: false });
573
+ input.once("end", () => {
574
+ setImmediate(async () => {
575
+ let last;
576
+ do {
577
+ last = pending();
578
+ await last;
579
+ } while (last !== pending());
580
+ gated.end();
581
+ });
582
+ });
583
+ return gated;
584
+ }
585
+ /**
586
+ * The console's own commands, which run in line order, print what they say and ask for the next
587
+ * line. Returns the function that runs a line typed as `name!`, or undefined when it isn't one.
588
+ */
589
+ function defineCommands(server, commands, lines, output) {
590
+ const runCommand = async (name, argument) => {
591
+ let message;
592
+ try {
593
+ message = await commands[name].run(argument, server.context);
594
+ } catch (error) {
595
+ message = `${name} failed: ${error.message}`;
596
+ }
597
+ output.write(`${message}\n`);
598
+ server.displayPrompt();
599
+ };
600
+ for (const [name, command] of Object.entries(commands)) server.defineCommand(name, {
601
+ help: command.help,
602
+ action(argument) {
603
+ lines.enqueue(() => runCommand(name, argument));
604
+ }
605
+ });
606
+ return (line) => {
607
+ const name = bangLine.exec(line)?.[1];
608
+ return name !== void 0 && commands[name]?.bang ? runCommand(name, "") : void 0;
609
+ };
610
+ }
611
+ /** Starts the session; `closed` resolves when it ends (end of input, or `.exit`). */
612
+ function startSession({ input, output, terminal = false, historyFile, prompt = "> ", scope, commands = {}, withDatabase, onLine }) {
613
+ const lines = lineQueue();
614
+ let written;
615
+ const server = repl.start({
616
+ prompt,
617
+ input: terminal ? input : untilDrained(input, lines.pending),
618
+ output,
619
+ terminal,
620
+ useColors: terminal,
621
+ breakEvalOnSigint: terminal,
622
+ useGlobal: false,
623
+ writer(value) {
624
+ if (onLine !== void 0) {
625
+ written = { value };
626
+ return "";
627
+ }
628
+ const shown = inspect(value, { colors: this.useColors });
629
+ return types.isNativeError(value) ? shown : `#=> ${shown}`;
630
+ }
631
+ });
632
+ if (terminal && historyFile !== void 0) server.setupHistory(historyFile, () => {});
633
+ Object.assign(server.context, scope);
634
+ const bang = defineCommands(server, commands, lines, output);
635
+ const script = onLine && {
636
+ report: onLine,
637
+ written: () => written,
638
+ reset: () => {
639
+ written = void 0;
640
+ }
641
+ };
642
+ lines.attach(server, withDatabase, bang, script);
643
+ return { closed: new Promise((resolve) => server.on("exit", () => void lines.pending().then(resolve))) };
644
+ }
645
+ //#endregion
646
+ //#region cli/console/script.ts
647
+ /** A stream that collects what is written to it, as text. */
648
+ function collecting(into) {
649
+ return new Writable({ write(chunk, _encoding, done) {
650
+ into.push(String(chunk));
651
+ done();
652
+ } });
653
+ }
654
+ /** The result as `node -p` prints it: a string as it is, anything else as inspect shows it. */
655
+ function shown(value, colors) {
656
+ return typeof value === "string" ? value : inspect(value, { colors });
657
+ }
658
+ /**
659
+ * Runs `code` as the console would run a line (top-level `await`, the Models and `db` in scope,
660
+ * each statement inside the project's `withDatabase`). The code's own `console.log` goes to
661
+ * stdout and `console.error` to stderr, as in `node -e`. The last result is printed after them
662
+ * unless it is undefined; a failure prints no result, and its stack on stderr, and no later line
663
+ * runs.
664
+ */
665
+ async function runScript({ code, scope, commands, withDatabase, colors = {
666
+ result: false,
667
+ error: false
668
+ } }) {
669
+ let last;
670
+ const logged = [];
671
+ const complained = [];
672
+ await startSession({
673
+ input: Readable.from([`${code}\n`]),
674
+ output: new Writable({ write: (_chunk, _encoding, done) => done() }),
675
+ scope: {
676
+ ...scope,
677
+ console: new Console({
678
+ stdout: collecting(logged),
679
+ stderr: collecting(complained)
680
+ })
681
+ },
682
+ commands,
683
+ withDatabase,
684
+ onLine: (outcome) => {
685
+ if (last?.ok !== false) last = outcome;
686
+ }
687
+ }).closed;
688
+ const stdout = logged.join("");
689
+ const stderr = complained.join("");
690
+ if (last?.ok === false) return {
691
+ exitCode: 1,
692
+ stdout,
693
+ stderr: `${stderr}${inspect(last.error, { colors: colors.error })}\n`
694
+ };
695
+ const value = last?.value;
696
+ return {
697
+ exitCode: 0,
698
+ stdout: `${stdout}${value === void 0 ? "" : `${shown(value, colors.result)}\n`}`,
699
+ stderr
700
+ };
701
+ }
702
+ //#endregion
703
+ //#region cli/console/command.ts
704
+ /** Where the console reads and writes: the person's terminal. */
705
+ function standardIo$1() {
706
+ const terminal = process.stdin.isTTY === true && process.stdout.isTTY === true;
707
+ return {
708
+ input: process.stdin,
709
+ output: process.stdout,
710
+ error: process.stderr,
711
+ terminal
712
+ };
713
+ }
714
+ /**
715
+ * Where the history is kept: in the adapter's folder for local files, which the project already
716
+ * ignores. A remote session has a file of its own, so a line typed against the real database is
717
+ * never offered, with the up arrow, to a local session (or the other way round).
718
+ */
719
+ function historyFileFor(stateFolder, remote) {
720
+ return join(stateFolder, `active-record-history${remote ? "-remote" : ""}`);
721
+ }
722
+ /** Says why the console can't open; 1. */
723
+ function refused$1(print, problem) {
724
+ print(problem);
725
+ return 1;
726
+ }
727
+ /** Red on a terminal, so a session on the real database can't be taken for a local one. */
728
+ function promptFor(remote, terminal) {
729
+ const prompt = remote ? "remote> " : "local> ";
730
+ return remote && terminal ? `\u001b[31m${prompt}\u001b[39m` : prompt;
731
+ }
732
+ /**
733
+ * The real database, once it is allowed: it has an id, and the person confirmed it (on a terminal)
734
+ * or said `--yes`. Input typed behind the confirmation is dropped until the database is open.
735
+ */
736
+ async function openRemote(adapter, { cwd, chosen }, options, io) {
737
+ const target = adapter.remote(chosen, "open");
738
+ if (typeof target === "string") return target;
739
+ let release = async () => {};
740
+ if (options.yes !== true) {
741
+ if (io.terminal !== true) return "Opening a remote database asks you to confirm it: run this on a terminal, or add --yes";
742
+ const confirmation = await confirmRemote({
743
+ input: io.input,
744
+ output: io.output,
745
+ target
746
+ });
747
+ ({release} = confirmation);
748
+ if (!confirmation.confirmed) {
749
+ await release();
750
+ return "Not opened.";
751
+ }
752
+ }
753
+ const opened = await adapter.open(cwd, chosen, { remote: true });
754
+ await release();
755
+ return opened;
756
+ }
757
+ /** Whether a stream is a terminal, which colors what is written to it. */
758
+ function isTerminal(stream) {
759
+ return stream instanceof WriteStream;
760
+ }
761
+ /** Runs `code` once, and returns its output rather than writing it: that waits until it is closed. */
762
+ function runOnce(code, opened, io, errors) {
763
+ return runScript({
764
+ code,
765
+ ...opened,
766
+ colors: {
767
+ result: isTerminal(io.output),
768
+ error: isTerminal(errors)
769
+ }
770
+ });
771
+ }
772
+ /** Everything that has to be true before a session starts, or why it isn't. */
773
+ async function prepare(options, io) {
774
+ const cwd = options.cwd ?? process.cwd();
775
+ const adapter = await loadAdapter(cwd, options.config);
776
+ if (typeof adapter === "string") return adapter;
777
+ const chosen = chosenDatabase(adapter, cwd, options);
778
+ if (typeof chosen === "string") return chosen;
779
+ const project = await loadProject(adapterEntry(adapter), cwd, options.models);
780
+ if (typeof project === "string") return project;
781
+ const opened = await (options.remote === true ? openRemote(adapter, {
782
+ cwd,
783
+ chosen
784
+ }, options, io) : adapter.open(cwd, chosen, { remote: false }));
785
+ if (typeof opened === "string") return opened;
786
+ return {
787
+ stateFolder: adapter.stateFolder(chosen),
788
+ notes: configNotes(adapter),
789
+ project,
790
+ opened
791
+ };
792
+ }
793
+ /** The session, or the one piece of code, on the open database; the exit code. */
794
+ async function converse(options, { stateFolder, notes, project, opened }, { io, say, errors }) {
795
+ const scripted = options.eval !== void 0;
796
+ const remote = options.remote === true;
797
+ const { library, models } = project;
798
+ const { commands, onQuery } = consoleCommands(project, {
799
+ verbose: options.verbose === true,
800
+ write: scripted ? say : (line) => io.output.write(`${line}\n`),
801
+ dim: scripted ? isTerminal(errors) : io.terminal === true
802
+ });
803
+ const database = library.connect(opened.binding, { onQuery });
804
+ say(opened.description);
805
+ say(`Models: ${Object.keys(models).join(", ")}`);
806
+ for (const note of notes) say(note);
807
+ const inside = {
808
+ scope: {
809
+ ...models,
810
+ db: database
811
+ },
812
+ commands,
813
+ withDatabase: async (run) => void await library.withDatabase(database, run)
814
+ };
815
+ if (options.eval !== void 0) return runOnce(options.eval, inside, io, errors);
816
+ await startSession({
817
+ ...io,
818
+ ...inside,
819
+ prompt: promptFor(remote, io.terminal === true),
820
+ historyFile: options.history ?? !remote ? historyFileFor(stateFolder, remote) : void 0
821
+ }).closed;
822
+ return {
823
+ exitCode: 0,
824
+ stdout: "",
825
+ stderr: ""
826
+ };
827
+ }
828
+ /** Runs the console until its input ends; the exit code. */
829
+ async function runConsole(options, print, io = standardIo$1()) {
830
+ const errors = io.error ?? process.stderr;
831
+ const say = options.eval === void 0 ? print : (line) => void errors.write(`${line}\n`);
832
+ const prepared = await prepare(options, io);
833
+ if (typeof prepared === "string") return refused$1(say, prepared);
834
+ let finished;
835
+ let closing;
836
+ try {
837
+ finished = await converse(options, prepared, {
838
+ io,
839
+ say,
840
+ errors
841
+ });
842
+ } finally {
843
+ closing = await prepared.opened.dispose().then(() => void 0, (error) => error);
844
+ }
845
+ if (closing !== void 0) {
846
+ say(`Couldn't close the database: ${closing.message}`);
847
+ return 1;
848
+ }
849
+ io.output.write(finished.stdout);
850
+ errors.write(finished.stderr);
851
+ return finished.exitCode;
852
+ }
853
+ //#endregion
854
+ //#region cli/console/flags.ts
855
+ const options = {
856
+ database: { type: "string" },
857
+ models: { type: "string" },
858
+ history: { type: "boolean" },
859
+ "no-history": { type: "boolean" },
860
+ verbose: { type: "boolean" },
861
+ remote: { type: "boolean" },
862
+ yes: { type: "boolean" },
863
+ eval: {
864
+ type: "string",
865
+ short: "e",
866
+ multiple: true
867
+ }
868
+ };
869
+ /** What is wrong with the flags together, if anything. */
870
+ function flagProblem(values) {
871
+ if (values.history && values["no-history"]) return "Use --history or --no-history, not both";
872
+ if (values.yes && !values.remote) return "--yes only goes with --remote";
873
+ const code = values.eval ?? [];
874
+ if (code.length > 1) return "Use -e once; join statements with ;";
875
+ if (code[0]?.trim() === "") return "-e needs some code to run";
876
+ }
877
+ /** The console's options from its parsed flags. */
878
+ function consoleChoices(values) {
879
+ const { history, "no-history": noHistory, eval: code, help: _, ...flags } = values;
880
+ return {
881
+ ...flags,
882
+ history: noHistory ? false : history || void 0,
883
+ eval: code?.[0]
884
+ };
885
+ }
886
+ /** `active-record console`: opens the project's database (local, or remote) and its Models in a REPL. */
887
+ const consoleSubcommand = defineSubcommand({
888
+ options,
889
+ usage: ` active-record console (or c) Open a console on your database, with your Models`,
890
+ flagHelp: `Options for console:
891
+ --database <name> The database to open, when the config has several
892
+ --models <path> Where the Models are: a folder (src/models) or one file (src/models.ts)
893
+ --remote Open your remote database instead, after asking you to type its name
894
+ --yes Don't ask first (with --remote); also how to open it without a terminal
895
+ --history Keep what you type, which a remote session doesn't unless asked
896
+ --no-history Don't keep what you type
897
+ --verbose Print each statement a line runs (.verbose toggles it while it runs)
898
+ -e, --eval <code> Run this code, print its result, and exit (only the result goes to stdout)`,
899
+ action({ values, positionals }, print, fail) {
900
+ if (positionals.length > 0) return fail(`Unexpected ${positionals[0]}`);
901
+ const problem = flagProblem(values);
902
+ if (problem !== void 0) return fail(problem);
903
+ return runConsole(consoleChoices(values), print);
904
+ }
905
+ });
906
+ //#endregion
907
+ //#region cli/plan.ts
908
+ /** A line printed with no file. */
909
+ function printed(line) {
910
+ return { line };
911
+ }
912
+ /** A file written, then its line printed. */
913
+ function written(file, line) {
914
+ return {
915
+ file,
916
+ line
917
+ };
918
+ }
919
+ /** A plan that only prints these lines, with this exit code. */
920
+ function printing(lines, code = 0) {
921
+ return {
922
+ steps: lines.map(printed),
923
+ code
924
+ };
925
+ }
926
+ /** The files a plan writes, in order. */
927
+ function filesOf(plan) {
928
+ return plan.steps.flatMap((step) => step.file === void 0 ? [] : [step.file]);
929
+ }
930
+ /** Several plans as one: every step, in order, and the worst exit code. */
931
+ function combined(plans) {
932
+ return {
933
+ steps: plans.flatMap((plan) => plan.steps),
934
+ code: Math.max(0, ...plans.map((plan) => plan.code))
935
+ };
936
+ }
937
+ /** A file the plan writes more than once, where a later write would replace an earlier one. */
938
+ function repeated(plan) {
939
+ const paths = filesOf(plan).map((file) => file.path);
940
+ return paths.find((path, index) => paths.indexOf(path) !== index);
941
+ }
942
+ /**
943
+ * Carries out a plan: each step writes its file (making its folder), then prints its line, so
944
+ * a write that fails leaves the files already written said. A plan that would write one file
945
+ * twice writes nothing. Returns the exit code.
946
+ */
947
+ function apply(plan, cwd, print) {
948
+ const twice = repeated(plan);
949
+ if (twice !== void 0) {
950
+ print(`${shown$1(cwd, twice)} would be written twice; choose another --out or name`);
951
+ print("Wrote nothing");
952
+ return 1;
953
+ }
954
+ for (const { file, line } of plan.steps) {
955
+ if (file !== void 0) {
956
+ mkdirSync(dirname(file.path), { recursive: true });
957
+ writeFileSync(file.path, file.source);
958
+ }
959
+ print(line);
960
+ }
961
+ return plan.code;
962
+ }
963
+ //#endregion
964
+ //#region cli/project/tools.ts
965
+ const tools = ["Drizzle", "Prisma"];
966
+ /** Each tool's files in a project, and the marker it writes into its SQL. */
967
+ const signs = {
968
+ Drizzle: {
969
+ files: [
970
+ "ts",
971
+ "mts",
972
+ "cts",
973
+ "js",
974
+ "mjs",
975
+ "cjs",
976
+ "json"
977
+ ].map((ext) => `drizzle.config.${ext}`),
978
+ marker: /^--> statement-breakpoint/m
979
+ },
980
+ Prisma: {
981
+ files: [
982
+ "prisma/schema.prisma",
983
+ "schema.prisma",
984
+ "prisma.config.ts"
985
+ ],
986
+ marker: /^-- CreateTable$/m
987
+ }
988
+ };
989
+ /**
990
+ * The folders a tool's config may be in: the project's, and each above it up to the repository's
991
+ * root (a monorepo keeps it there), or just the project's outside a repository.
992
+ */
993
+ function searchedFolders(projectDir) {
994
+ const folders = [projectDir];
995
+ for (let dir = projectDir; !existsSync(join(dir, ".git")); dir = dirname(dir)) {
996
+ if (dirname(dir) === dir) return [projectDir];
997
+ folders.push(dirname(dir));
998
+ }
999
+ return folders;
1000
+ }
1001
+ /** The tools whose files are in the project or above it (`drizzle.config.ts`, `prisma/schema.prisma`). */
1002
+ function toolsWithFiles(projectDir) {
1003
+ const folders = searchedFolders(projectDir);
1004
+ return tools.filter((tool) => folders.some((folder) => signs[tool].files.some((file) => existsSync(join(folder, file)))));
1005
+ }
1006
+ /**
1007
+ * The tool that wrote a project's migrations, if one is recognised: by its files (`toolsFound`,
1008
+ * from `toolsWithFiles`), or its marker in a migration.
1009
+ */
1010
+ function migrationTool(toolsFound, migrations) {
1011
+ return tools.find((tool) => toolsFound.includes(tool) || migrations.some((migration) => signs[tool].marker.test(migration.sql)));
1012
+ }
1013
+ //#endregion
1014
+ //#region cli/project/snapshot.ts
1015
+ /** A file's contents, or undefined when there's no such file. */
1016
+ function contents(path) {
1017
+ return existsSync(path) ? readFileSync(path, "utf8") : void 0;
1018
+ }
1019
+ /** What's on disk for one database. */
1020
+ function databaseSnapshot(target, toolsFound) {
1021
+ const folder = target.out.replace(/\.ts$/, "");
1022
+ return {
1023
+ target,
1024
+ migrations: existsSync(target.migrationsDir) ? migrationsOf(target) : void 0,
1025
+ schema: contents(target.out),
1026
+ schemaFolder: existsSync(folder) && statSync(folder).isDirectory(),
1027
+ hasBase: existsSync(target.base.path),
1028
+ nestedMigrations: hasNestedMigrations(target),
1029
+ toolsFound,
1030
+ models: [],
1031
+ modelErrors: []
1032
+ };
1033
+ }
1034
+ /**
1035
+ * Reads a project's databases from its config, and the other `files` a command needs
1036
+ * (a Model file, for `g model`); or why it can't, such as a missing config.
1037
+ */
1038
+ function readProject(adapter, cwd, options, files = []) {
1039
+ const targets = targetsOf(adapter, cwd, options);
1040
+ if (typeof targets === "string") return targets;
1041
+ const toolsFound = targets.length === 0 ? [] : toolsWithFiles(targets[0].configDir);
1042
+ const read = files.flatMap((path) => {
1043
+ const text = contents(path);
1044
+ return text === void 0 ? [] : [[path, text]];
1045
+ });
1046
+ return {
1047
+ adapter,
1048
+ cwd,
1049
+ databases: targets.map((target) => databaseSnapshot(target, toolsFound)),
1050
+ files: new Map(read)
1051
+ };
1052
+ }
1053
+ //#endregion
1054
+ //#region cli/source.ts
1055
+ /**
1056
+ * Text as a string literal in generated TypeScript, quotes and backslashes escaped: for values
1057
+ * that come from a project's config or paths (#85).
1058
+ */
1059
+ function stringLiteral(text) {
1060
+ return JSON.stringify(text);
1061
+ }
1062
+ /** A double-quoted string literal in generated source, read back: `stringLiteral`'s pattern. */
1063
+ const stringLiteralPattern = String.raw`"(?:[^"\\]|\\.)*"`;
1064
+ //#endregion
1065
+ //#region cli/schema/render.ts
1066
+ /**
1067
+ * The generated file's format. Bump it when the output changes, so `--check` reports files an
1068
+ * older version of the command wrote (its fingerprint covers the format as well as the schema).
1069
+ */
1070
+ const format = 6;
1071
+ /**
1072
+ * An object key: bare when it's an identifier, quoted otherwise (`"first name"`). `__proto__` is
1073
+ * computed, since in an object literal a bare or quoted one sets the prototype and the key is
1074
+ * lost (#119).
1075
+ */
1076
+ function keySource(name) {
1077
+ if (name === "__proto__") return "[\"__proto__\"]";
1078
+ return isIdentifier(name) ? name : JSON.stringify(name);
1079
+ }
1080
+ /** A JSON value as TypeScript source: `{ a: 1, tags: ["x"] }`. */
1081
+ function valueSource(value) {
1082
+ if (Array.isArray(value)) return `[${value.map(valueSource).join(", ")}]`;
1083
+ if (value !== null && typeof value === "object") {
1084
+ const entries = Object.entries(value).map(([key, each]) => `${keySource(key)}: ${valueSource(each)}`);
1085
+ return entries.length === 0 ? "{}" : `{ ${entries.join(", ")} }`;
1086
+ }
1087
+ return JSON.stringify(value);
1088
+ }
1089
+ function defaultSource(value) {
1090
+ if ("date" in value) return `() => new Date(${JSON.stringify(value.date)})`;
1091
+ const source = valueSource(value.literal);
1092
+ return `() => ${source.startsWith("{") ? `(${source})` : source}`;
1093
+ }
1094
+ /** An attribute's spec: just its type when that's all it has, as Models are written by hand. */
1095
+ function specSource(spec) {
1096
+ const parts = [`type: ${JSON.stringify(spec.type)}`];
1097
+ if (spec.null === false) parts.push("null: false");
1098
+ if (spec.column !== void 0) parts.push(`column: ${JSON.stringify(spec.column)}`);
1099
+ if (spec.default !== void 0) parts.push(`default: ${defaultSource(spec.default)}`);
1100
+ if (spec.generateId) parts.push("generateId: true");
1101
+ return parts.length === 1 ? JSON.stringify(spec.type) : `{ ${parts.join(", ")} }`;
1102
+ }
1103
+ /** Text safe inside a `/** … *\/` comment. */
1104
+ function commentText(text) {
1105
+ return text.replaceAll("*/", "*\\/");
1106
+ }
1107
+ function tableSource(table) {
1108
+ const attributes = Object.entries(table.attributes).map(([name, spec]) => ` ${keySource(name)}: ${specSource(spec)},`).join("\n");
1109
+ return `/** ${commentText(table.name)} — last changed by ${commentText(table.lastChangedBy)} */
1110
+ export const ${table.exportName} = {
1111
+ ${attributes}
1112
+ } as const;`;
1113
+ }
1114
+ /** A short hash of the schema itself, so `--check` ignores how the file is formatted. */
1115
+ function fingerprintOf({ adapter, tables, binding, models }) {
1116
+ const listed = byName(models, (model) => model.className);
1117
+ return createHash("sha256").update(JSON.stringify({
1118
+ format,
1119
+ adapter,
1120
+ tables,
1121
+ binding,
1122
+ models: listed
1123
+ })).digest("hex").slice(0, 12);
1124
+ }
1125
+ /** Items sorted by a name, as `localeCompare` doesn't: the same on every machine. */
1126
+ function byName(items, name) {
1127
+ return [...items].sort((a, b) => name(a) < name(b) ? -1 : name(a) > name(b) ? 1 : 0);
1128
+ }
1129
+ /** The Models' entries as an object: on one line, or one a line when that would be too long. */
1130
+ function modelsSource(entries) {
1131
+ const line = entries.length === 0 ? "{}" : `{ ${entries.join(", ")} }`;
1132
+ if (` models: ${line},`.length <= 100) return line;
1133
+ return `{\n${entries.map((entry) => ` ${entry},`).join("\n")}\n }`;
1134
+ }
1135
+ /** The `schema` value: its adapter and binding, every table by name, and every Model's table by class. */
1136
+ function schemaValueSource({ adapter, tables, binding, models }) {
1137
+ const entries = tables.map((table) => {
1138
+ const primaryKey = JSON.stringify(table.primaryKey);
1139
+ return ` ${keySource(table.name)}: { attributes: ${table.exportName}, primaryKey: ${primaryKey} },`;
1140
+ }).join("\n");
1141
+ const listed = byName(models, (model) => model.className).map((model) => `${keySource(model.className)}: ${JSON.stringify(model.table)}`);
1142
+ return `/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
1143
+ export const schema = {
1144
+ adapter: ${adapter.factory}({ binding: ${stringLiteral(binding)} }),
1145
+ tables: {
1146
+ ${entries}
1147
+ },
1148
+ models: ${modelsSource(listed)},
1149
+ } as const;`;
1150
+ }
1151
+ /** A Model's declaration: its class, with its table's attributes after its own overrides. */
1152
+ function interfaceSource(model, exportName) {
1153
+ const name = model.className;
1154
+ const heritage = `extends TableAttributes<typeof ${exportName}, (typeof ${name})["attributes"]> {}`;
1155
+ const line = ` interface ${name} ${heritage}`;
1156
+ return line.length <= 100 ? line : ` interface ${name}\n ${heritage}`;
1157
+ }
1158
+ /** One `declare module` block per Model file, adding each class's attributes to it. */
1159
+ function declarationsSource({ tables, models }) {
1160
+ const exportNames = new Map(tables.map((table) => [table.name, table.exportName]));
1161
+ const modules = /* @__PURE__ */ new Map();
1162
+ for (const model of byName(models, (each) => each.className)) modules.set(model.module, [...modules.get(model.module) ?? [], model]);
1163
+ return byName([...modules], ([module]) => module).map(([module, inModule]) => {
1164
+ const lines = inModule.map((model) => interfaceSource(model, exportNames.get(model.table)));
1165
+ return `declare module ${stringLiteral(module)} {\n${lines.join("\n")}\n}`;
1166
+ }).join("\n\n");
1167
+ }
1168
+ /**
1169
+ * The generated `schema.ts`: each table's attributes, the binding with every table and Model,
1170
+ * and each Model's attributes added to its class. It's the schema as a document, like Rails'
1171
+ * `schema.rb`; the app's base class (`renderBase`) holds it.
1172
+ */
1173
+ function renderSchema(schema, source) {
1174
+ const hasModels = schema.models.length > 0;
1175
+ const imports = (hasModels ? "import type { TableAttributes } from \"@forestfuture/active-record\";\n" : "") + `import { ${schema.adapter.factory} } from ${stringLiteral(schema.adapter.from)};\n\n`;
1176
+ const declarations = hasModels ? `\n\n${declarationsSource(schema)}` : "";
1177
+ return `// Generated by \`active-record schema\` from ${source} — don't edit.
1178
+ // schema: ${fingerprintOf(schema)}
1179
+
1180
+ ${imports}${schema.tables.map(tableSource).join("\n\n")}
1181
+
1182
+ ${schemaValueSource(schema)}${declarations}
1183
+ `;
1184
+ }
1185
+ /**
1186
+ * The app's base class for a database's Models, written once and then the app's own, as Rails'
1187
+ * `ApplicationRecord` is: `class Product extends ApplicationRecord {}`.
1188
+ */
1189
+ function renderBase(className, schemaImport) {
1190
+ return `import { Model } from "@forestfuture/active-record";
1191
+ import { schema } from ${stringLiteral(schemaImport)};
1192
+
1193
+ /**
1194
+ * The base class for this app's Models: \`class Product extends ${className} {}\`. Methods,
1195
+ * callbacks and scopes written here are shared by every Model, as in Rails' ApplicationRecord.
1196
+ * It's abstract: it has no table of its own.
1197
+ */
1198
+ export abstract class ${className} extends Model {
1199
+ // The generated schema: each Model's attributes, from its table, and the binding Models
1200
+ // query (Product.find(id)), from your project's config.
1201
+ static override schema = schema;
1202
+
1203
+ // A method every record has:
1204
+ // label() {
1205
+ // return \`\${this.constructor.name} \${JSON.stringify(this.attributes())}\`;
1206
+ // }
1207
+
1208
+ // A scope every Model has, in SQL since it runs on each Model's own table (import sql too):
1209
+ // static newest = this.scope((q) => q.order(sql\`created_at DESC\`));
1210
+
1211
+ // Log every query, from every Model, in production too (import type QueryListener too; the
1212
+ // guide's Connecting page shows development-only logging, and one request's queries):
1213
+ // static override onQuery: QueryListener = ({ model, sql, durationMs }) =>
1214
+ // console.log(\`\${model} \${durationMs.toFixed(1)}ms \${sql}\`);
1215
+
1216
+ // Values of attributes named like these show as "[FILTERED]" to onQuery and in errors. These
1217
+ // are Rails' defaults (passwords, tokens, keys, emails…); add yours, or leave one out:
1218
+ // static override filterAttributes = [...Model.filterAttributes, "iban"];
1219
+
1220
+ // Attributes toJSON() leaves out, so Response.json(record) never sends them (exact names;
1221
+ // attributes() still has them):
1222
+ // static override hiddenAttributes = ["passwordDigest"];
1223
+
1224
+ // How new TEXT keys are made (a UUID by default), e.g. time-ordered ones from a
1225
+ // library you choose:
1226
+ // static override generateId = () => uuidv7();
1227
+
1228
+ static {
1229
+ // A callback that runs for every Model, before each Model's own:
1230
+ // this.beforeSave((record) => {
1231
+ // console.log(\`Saving \${record.constructor.name}\`);
1232
+ // });
1233
+ // Error messages in place of the built-in English, for every Model (a Model can declare
1234
+ // its own, and attributes: { email: { … } } is for one attribute):
1235
+ // this.errorMessages({ blank: "is required" });
1236
+ }
1237
+ }
1238
+ `;
1239
+ }
1240
+ /** The fingerprint a generated file was made from, read from its header. */
1241
+ function fingerprintIn(source) {
1242
+ return /^\/\/ schema: ([0-9a-f]{12})$/m.exec(source)?.[1];
1243
+ }
1244
+ //#endregion
1245
+ //#region cli/schema/origin.ts
1246
+ const issue = "https://github.com/forestfuture/active-record/issues/73";
1247
+ /** Column names (as snake_case words) that suggest a `TEXT` column holds JSON. */
1248
+ const jsonish = /(^|_)(json|metadata|settings|payload|properties)$/;
1249
+ /**
1250
+ * The hint for migrations in folders, when `hasNestedMigrations` found them: the pattern to set,
1251
+ * when the adapter reads one (`setting`), or that they aren't read.
1252
+ */
1253
+ function layoutNote(cwd, target, setting) {
1254
+ const dir = target.migrationsDir;
1255
+ const found = `${shown$1(cwd, dir)}/ has its migrations in folders, as Drizzle writes them`;
1256
+ if (setting === void 0) return `${found}, which aren't read`;
1257
+ return `${found}; set ${setting} to "${`${shown$1(target.configDir, dir)}/*/migration.sql`}" in ${shown$1(cwd, target.configFile)}, so they're read`;
1258
+ }
1259
+ /** The columns worth checking, in a schema from `tool`'s migrations. */
1260
+ function columnNotes(tool, tables) {
1261
+ const notes = [];
1262
+ for (const table of tables) for (const [attribute, spec] of Object.entries(table.attributes)) {
1263
+ const column = spec.column ?? underscore(attribute);
1264
+ const words = underscore(column);
1265
+ const where = `${table.name}.${column}`;
1266
+ 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"));
1267
+ 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`);
1268
+ }
1269
+ return notes;
1270
+ }
1271
+ /** A note for a datetime whose default writes the database's own date text, which sorts apart from ISO (#143). */
1272
+ function textDateNote(where) {
1273
+ 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)`;
1274
+ }
1275
+ /**
1276
+ * Notes for a schema generated from another tool's migrations: the tool, then the columns to
1277
+ * check, and `textDates`, the datetime columns whose default is the database's own date text.
1278
+ */
1279
+ function originNotes(tool, tables, textDates) {
1280
+ if (tool === void 0) return [];
1281
+ return [
1282
+ `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})`,
1283
+ ...columnNotes(tool, tables),
1284
+ ...textDates.map(textDateNote)
1285
+ ];
1286
+ }
1287
+ //#endregion
1288
+ //#region cli/schema/writes.ts
1289
+ /** The app's base class for the database (`ApplicationRecord`), when it's missing; never over it. */
1290
+ function baseWrites(cwd, db) {
1291
+ const { target } = db;
1292
+ if (db.hasBase) return [];
1293
+ const { path, className } = target.base;
1294
+ return [written({
1295
+ path,
1296
+ source: renderBase(className, importPath(dirname(path), target.out))
1297
+ }, `Wrote ${shown$1(cwd, path)}`)];
1298
+ }
1299
+ /**
1300
+ * Why the schema can't be written where it's going, if it can't: a file the command didn't write
1301
+ * (a Drizzle schema, say) is never replaced, and a file next to a folder of the same name would
1302
+ * take over that folder's imports (`@/db/schema` finds `schema.ts` before `schema/index.ts`).
1303
+ */
1304
+ function schemaRefusal(cwd, db) {
1305
+ const out = shown$1(cwd, db.target.out);
1306
+ const folder = db.target.out.replace(/\.ts$/, "");
1307
+ const suggestion = "choose another file with --out, such as --out src/db/active-record.ts";
1308
+ 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}`;
1309
+ 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}`;
1310
+ }
1311
+ /** The adapter a schema imports: the plugin's name is its factory's, from the adapter's package. */
1312
+ function schemaAdapterOf(adapter) {
1313
+ return {
1314
+ factory: adapter.name,
1315
+ from: adapterEntry(adapter)
1316
+ };
1317
+ }
1318
+ /** What a database's schema is rendered from: its adapter, tables and binding, and the Models found. */
1319
+ function schemaSourceOf(project, db, tables) {
1320
+ const { target } = db;
1321
+ const models = db.models.map(({ className, table, file }) => ({
1322
+ className,
1323
+ table,
1324
+ module: importPath(dirname(target.out), file)
1325
+ }));
1326
+ return {
1327
+ adapter: schemaAdapterOf(project.adapter),
1328
+ tables,
1329
+ binding: target.database.binding,
1330
+ models
1331
+ };
1332
+ }
1333
+ /**
1334
+ * What writing a database's schema takes, once its tables are known: the schema file (unless
1335
+ * it's unchanged), the base class when it's missing, and the notes.
1336
+ */
1337
+ function schemaWrites(project, db, result) {
1338
+ const { cwd } = project;
1339
+ const { target } = db;
1340
+ const out = shown$1(cwd, target.out);
1341
+ const source = `${shown$1(cwd, target.migrationsDir)}/`;
1342
+ const rendered = renderSchema(schemaSourceOf(project, db, result.tables), source);
1343
+ const count = `${result.tables.length} table${result.tables.length === 1 ? "" : "s"}`;
1344
+ const setting = project.adapter.patternSetting;
1345
+ const notes = db.nestedMigrations ? [layoutNote(cwd, target, setting)] : [];
1346
+ const steps = [];
1347
+ if (rendered === db.schema) steps.push({ line: `${out} is up to date (${count})` });
1348
+ else {
1349
+ steps.push(written({
1350
+ path: target.out,
1351
+ source: rendered
1352
+ }, `Wrote ${out} (${count}) from ${source}`));
1353
+ const tool = migrationTool(db.toolsFound, db.migrations ?? []);
1354
+ notes.unshift(...result.notes, ...originNotes(tool, result.tables, result.textDates));
1355
+ }
1356
+ steps.push(...baseWrites(cwd, db), ...notes.map((note) => ({ line: `Note: ${note}` })));
1357
+ return {
1358
+ steps,
1359
+ code: 0
1360
+ };
1361
+ }
1362
+ //#endregion
1363
+ //#region cli/schema/models.ts
1364
+ /**
1365
+ * Writes a schema file that's missing, for while the Models load: an import finds a module only
1366
+ * when its file exists. The plan writes the real one. Returns its path, to remove afterwards.
1367
+ */
1368
+ function placeholder(out, source) {
1369
+ mkdirSync(dirname(out), { recursive: true });
1370
+ writeFileSync(out, source);
1371
+ return out;
1372
+ }
1373
+ /**
1374
+ * Evaluates each database's schema as its migrations make it now, in place of its file, so the
1375
+ * Models load with every table and with no list of Models to be checked against. Returns each
1376
+ * schema value, with its database.
1377
+ */
1378
+ async function freshSchemas(jiti, project, placeholders) {
1379
+ const schemas = /* @__PURE__ */ new Map();
1380
+ for (const db of project.databases) {
1381
+ const { database, out } = db.target;
1382
+ const { migrationsTable, entry } = database;
1383
+ const result = await project.adapter.readSchema(db.migrations ?? [], {
1384
+ migrationsTable,
1385
+ entry
1386
+ });
1387
+ if (db.migrations === void 0 || !result.ok) continue;
1388
+ const source = renderSchema({
1389
+ adapter: schemaAdapterOf(project.adapter),
1390
+ tables: result.tables,
1391
+ binding: database.binding,
1392
+ models: []
1393
+ }, "");
1394
+ if (!existsSync(out)) placeholders.push(placeholder(out, source));
1395
+ const exported = await jiti.evalModule(source, {
1396
+ filename: out,
1397
+ async: true
1398
+ });
1399
+ delete exported.schema.models;
1400
+ schemas.set(exported.schema, db);
1401
+ }
1402
+ return schemas;
1403
+ }
1404
+ /** The database whose schema a class's nearest base holds, if it's one being generated. */
1405
+ function databaseOf(value, schemas) {
1406
+ const holder = ancestors(value).find((each) => Object.hasOwn(each, "schema"));
1407
+ return holder === void 0 ? void 0 : schemas.get(holder.schema);
1408
+ }
1409
+ /** Whether `file` declares the class itself, rather than exporting it from another file. */
1410
+ function declares(file, name) {
1411
+ return new RegExp(`\\bclass\\s+${name}\\b`).test(readFileSync(file, "utf8"));
1412
+ }
1413
+ /** Adds a class from `file` if it's a Model directly below a base: one whose table it is. */
1414
+ function addModel(cwd, file, { name, model }, found) {
1415
+ if (isBase(model) || !isBase(Object.getPrototypeOf(model))) return;
1416
+ if (name === "default") {
1417
+ 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`);
1418
+ return;
1419
+ }
1420
+ if (!isIdentifier(model.name)) {
1421
+ found.errors.push(`${shown$1(cwd, file)} exports a Model named ${JSON.stringify(model.name)}, which isn't a name active-record schema can write as code; name the class with letters, digits, _ and \$`);
1422
+ return;
1423
+ }
1424
+ if (found.models.get(model) !== void 0 && !declares(file, model.name)) return;
1425
+ try {
1426
+ model.attributeDefinitions;
1427
+ } catch (error) {
1428
+ found.errors.push(`${shown$1(cwd, file)}: ${error.message}`);
1429
+ return;
1430
+ }
1431
+ found.models.set(model, {
1432
+ className: model.name,
1433
+ table: model.table,
1434
+ file
1435
+ });
1436
+ }
1437
+ /** Imports a Model file, or says why it couldn't be loaded. */
1438
+ async function importFile(cwd, jiti, file) {
1439
+ try {
1440
+ return await jiti.import(file);
1441
+ } catch (error) {
1442
+ const message = error.message.replaceAll(`${resolve(cwd)}${sep}`, "");
1443
+ return `Couldn't load ${shown$1(cwd, file)}: ${message}`;
1444
+ }
1445
+ }
1446
+ /** Adds the Models a file exports that are built on a schema being generated. */
1447
+ function addExported(cwd, file, exported, context) {
1448
+ for (const [name, value] of Object.entries(exported)) if (typeof value === "function" && value.prototype instanceof context.library.Model && databaseOf(value, context.schemas) !== void 0) addModel(cwd, file, {
1449
+ name,
1450
+ model: value
1451
+ }, context.found);
1452
+ }
1453
+ /** Loads the Model files, finding the Models built on the schemas being generated. */
1454
+ async function modelsIn(cwd, jiti, files, schemas) {
1455
+ const found = {
1456
+ models: /* @__PURE__ */ new Map(),
1457
+ errors: []
1458
+ };
1459
+ const library = await loadLibrary(cwd, jiti, {
1460
+ command: "schema",
1461
+ packages: [corePackage]
1462
+ });
1463
+ if (typeof library === "string") return {
1464
+ found,
1465
+ library
1466
+ };
1467
+ for (const file of files) {
1468
+ const exported = await importFile(cwd, jiti, file);
1469
+ if (typeof exported === "string") found.errors.push(exported);
1470
+ else addExported(cwd, file, exported, {
1471
+ library,
1472
+ schemas,
1473
+ found
1474
+ });
1475
+ }
1476
+ return {
1477
+ found,
1478
+ library
1479
+ };
1480
+ }
1481
+ /**
1482
+ * The project with each database's Models, found by loading its Model files as its own code
1483
+ * would; or with why they couldn't be, on every database. With no Model files, there are none.
1484
+ */
1485
+ async function withModels(project, { models = defaultModels, check = false } = {}) {
1486
+ const { cwd } = project;
1487
+ const files = modelFiles(cwd, models);
1488
+ if (typeof files === "string" || files.length === 0) return project;
1489
+ if (check && project.databases.some((db) => db.schema === void 0)) return project;
1490
+ const jiti = projectJiti(cwd);
1491
+ const loadedBefore = new Set(Object.keys(jiti.cache));
1492
+ const placeholders = [];
1493
+ try {
1494
+ const schemas = await freshSchemas(jiti, project, placeholders);
1495
+ const { found, library } = await modelsIn(cwd, jiti, files, schemas);
1496
+ const errors = typeof library === "string" ? [library] : found.errors;
1497
+ const databases = project.databases.map((db) => ({
1498
+ ...db,
1499
+ models: [...found.models.entries()].filter(([model]) => databaseOf(model, schemas) === db).map(([, model]) => model),
1500
+ modelErrors: errors
1501
+ }));
1502
+ return {
1503
+ ...project,
1504
+ databases
1505
+ };
1506
+ } finally {
1507
+ for (const path of placeholders) rmSync(path);
1508
+ forgetProjectFiles(cwd, jiti, loadedBefore);
1509
+ }
1510
+ }
1511
+ //#endregion
1512
+ //#region cli/generate/columns.ts
1513
+ const types$1 = [
1514
+ "string",
1515
+ "integer",
1516
+ "real",
1517
+ "boolean",
1518
+ "datetime",
1519
+ "json",
1520
+ "references"
1521
+ ];
1522
+ const syntax = /^([A-Za-z_]\w*)(?::(?!(?:unique|index)\b)(\w+))?(!)?(?:=(.*?))?((?::(?:unique|index))*)$/;
1523
+ /** A `=value` default as its type's literal, or why it can't be one. */
1524
+ function defaultOf(type, value) {
1525
+ const number = Number(value);
1526
+ switch (type) {
1527
+ case "string": return {
1528
+ ok: true,
1529
+ value
1530
+ };
1531
+ case "boolean": return value === "true" || value === "false" ? {
1532
+ ok: true,
1533
+ value: value === "true"
1534
+ } : {
1535
+ ok: false,
1536
+ error: `${value} isn't true or false`
1537
+ };
1538
+ case "integer": return /^-?\d+$/.test(value) && Number.isSafeInteger(number) ? {
1539
+ ok: true,
1540
+ value: number
1541
+ } : {
1542
+ ok: false,
1543
+ error: `${value} isn't an integer`
1544
+ };
1545
+ case "real": return /^-?\d+(\.\d+)?$/.test(value) ? {
1546
+ ok: true,
1547
+ value: number
1548
+ } : {
1549
+ ok: false,
1550
+ error: `${value} isn't a number`
1551
+ };
1552
+ default: return {
1553
+ ok: false,
1554
+ error: "only string, integer, real and boolean columns can have a default here"
1555
+ };
1556
+ }
1557
+ }
1558
+ /** The index `:unique` or `:index` asks for. */
1559
+ function indexOf(modifiers) {
1560
+ if (modifiers.includes("unique")) return "unique";
1561
+ return modifiers.includes("index") ? "index" : "none";
1562
+ }
1563
+ /** One column argument, or why it can't be read. */
1564
+ function parseColumn(arg) {
1565
+ const match = syntax.exec(arg);
1566
+ if (match === null) return `${arg}: write a column as name:type, with ! for NOT NULL, =value for a default, and :unique or :index`;
1567
+ const [, given, typeName = "string", bang, value, indexes = ""] = match;
1568
+ const type = typeName;
1569
+ if (!types$1.includes(type)) return `${arg}: ${typeName} isn't a type; use string, integer, real, boolean, datetime, json or references`;
1570
+ const name = underscore(given);
1571
+ const index = indexOf(indexes);
1572
+ if (type === "references") {
1573
+ const association = camelize(name);
1574
+ return {
1575
+ name: `${name}_id`,
1576
+ type,
1577
+ notNull: true,
1578
+ index: index === "none" ? "index" : index,
1579
+ references: pluralize(name),
1580
+ association
1581
+ };
1582
+ }
1583
+ const column = {
1584
+ name,
1585
+ type,
1586
+ notNull: bang !== void 0,
1587
+ index
1588
+ };
1589
+ if (value === void 0) return column;
1590
+ const literal = defaultOf(type, value);
1591
+ return literal.ok ? {
1592
+ ...column,
1593
+ default: literal.value
1594
+ } : `${arg}: ${literal.error}`;
1595
+ }
1596
+ /** The columns given to a generator, or every one that can't be read. */
1597
+ function parseColumns(args) {
1598
+ const parsed = args.map(parseColumn);
1599
+ const errors = parsed.filter((each) => typeof each === "string");
1600
+ return errors.length > 0 ? {
1601
+ ok: false,
1602
+ errors
1603
+ } : {
1604
+ ok: true,
1605
+ columns: parsed
1606
+ };
1607
+ }
1608
+ //#endregion
1609
+ //#region cli/generate/model-file.ts
1610
+ const library = "@forestfuture/active-record";
1611
+ /** A Model's file name: its class name in kebab-case (`LineItem` → `line-item.ts`). */
1612
+ function modelFileName(className) {
1613
+ return `${moduleName(className)}.ts`;
1614
+ }
1615
+ /**
1616
+ * The class itself: `export class LineItem extends ApplicationRecord { … }`. Its table,
1617
+ * `line_items`, comes from its class name, as `g model` named the table.
1618
+ */
1619
+ function classSource({ className, associations, base }) {
1620
+ const head = `export class ${className} extends ${base.className}`;
1621
+ if (associations.length === 0) return `${head} {}\n`;
1622
+ return `${head} {\n${associations.map(({ name, className: target }) => ` ${name} = belongsTo(${target});\n`).join("")}}\n`;
1623
+ }
1624
+ /**
1625
+ * A Model's source, with its imports: the library's `belongsTo` when it has one, the app's
1626
+ * base class (`ApplicationRecord`), and, in a file of its own, each target's file (`./order`), as Rails assumes it exists.
1627
+ */
1628
+ function modelSource(model, { separateFiles }) {
1629
+ const imports = [];
1630
+ if (model.associations.length > 0) imports.push(`import { belongsTo } from "${library}";`);
1631
+ imports.push(`import { ${model.base.className} } from ${stringLiteral(model.base.importPath)};`);
1632
+ if (separateFiles) for (const { className } of model.associations) imports.push(`import { ${className} } from "./${moduleName(className)}";`);
1633
+ return `${imports.join("\n")}\n\n${classSource(model)}`;
1634
+ }
1635
+ /** `source` with `belongsTo` among its imports from the library, adding the import if it has none. */
1636
+ function importingBelongsTo(source) {
1637
+ const existing = new RegExp(`^import \\{([^}]*)\\} from "${library}";$`, "m");
1638
+ const match = existing.exec(source);
1639
+ if (match === null) return `import { belongsTo } from "${library}";\n${source}`;
1640
+ const names = match[1].split(",").map((name) => name.trim()).filter(Boolean);
1641
+ if (names.includes("belongsTo")) return source;
1642
+ const sorted = [...names, "belongsTo"].sort();
1643
+ return source.replace(existing, `import { ${sorted.join(", ")} } from "${library}";`);
1644
+ }
1645
+ /**
1646
+ * `source` importing the base class, adding the import if it has none; or why not, when it
1647
+ * imports a class of that name from somewhere else.
1648
+ */
1649
+ function importingBase(source, { className, importPath }) {
1650
+ const existing = new RegExp(`^import \\{[^}]*\\b${className}\\b[^}]*\\} from (${stringLiteralPattern});$`, "m").exec(source);
1651
+ if (existing === null) return {
1652
+ ok: true,
1653
+ source: `import { ${className} } from ${stringLiteral(importPath)};\n${source}`
1654
+ };
1655
+ const imported = JSON.parse(existing[1]);
1656
+ return imported === importPath ? {
1657
+ ok: true,
1658
+ source
1659
+ } : {
1660
+ ok: false,
1661
+ error: `it imports ${className} from ${imported}, not ${importPath}`
1662
+ };
1663
+ }
1664
+ /** A models file with one more Model at its end (`--models src/models.ts`), or why it can't be. */
1665
+ function appendModel(existing, model) {
1666
+ if (existing.trim() === "") return {
1667
+ ok: true,
1668
+ source: modelSource(model, { separateFiles: false })
1669
+ };
1670
+ const imported = importingBase(existing, model.base);
1671
+ if (!imported.ok) return imported;
1672
+ return {
1673
+ ok: true,
1674
+ source: `${(model.associations.length > 0 ? importingBelongsTo(imported.source) : imported.source).trimEnd()}\n\n${classSource(model)}`
1675
+ };
1676
+ }
1677
+ //#endregion
1678
+ //#region cli/generate/migration-file.ts
1679
+ /** `20261108090503`: the UTC second, as 14 digits. */
1680
+ function stamp(now) {
1681
+ return Number(now.toISOString().slice(0, 19).replaceAll(/\D/g, ""));
1682
+ }
1683
+ /**
1684
+ * The next migration's file name: the current UTC second as its version, or one past the highest
1685
+ * version there when that's later, as Rails numbers them, so two written in one second stay in
1686
+ * order. Files numbered `0001_…` sort before it, on every adapter.
1687
+ */
1688
+ function migrationFileName(existing, name, now) {
1689
+ const highest = Math.max(0, ...existing.map(leadingNumber).filter(Number.isFinite));
1690
+ const version = Math.max(stamp(now), highest + 1);
1691
+ return `${String(version).padStart(14, "0")}_${underscore(name)}.sql`;
1692
+ }
1693
+ //#endregion
1694
+ //#region cli/generate/names.ts
1695
+ /** A name the generators accept: letters, digits and `_`, starting with a letter. */
1696
+ const allowed$1 = /^[A-Za-z][A-Za-z0-9_]*$/;
1697
+ /**
1698
+ * The class a `g model` name asks for, singular as Rails makes it (`line_items` → `LineItem`),
1699
+ * with a note when it was plural; or why the name won't do.
1700
+ */
1701
+ function modelName(given) {
1702
+ if (!allowed$1.test(given)) return {
1703
+ ok: false,
1704
+ error: `${given} isn't a Model name; use letters and digits, like LineItem`
1705
+ };
1706
+ const className = classify(singularize(underscore(given)));
1707
+ return className === classify(given) ? {
1708
+ ok: true,
1709
+ className
1710
+ } : {
1711
+ ok: true,
1712
+ className,
1713
+ note: `${given} looks plural, so the Model is ${className}, as Rails names it`
1714
+ };
1715
+ }
1716
+ /** Whether a migration's name is usable as its file's name, or why not. */
1717
+ function migrationNameError(given) {
1718
+ return allowed$1.test(given) ? void 0 : `${given} isn't a migration name; use letters, digits and _, like AddSkuToProducts`;
1719
+ }
1720
+ //#endregion
1721
+ //#region cli/generate/command.ts
1722
+ /** A refusal: these errors, then "Wrote nothing". */
1723
+ function refused(...errors) {
1724
+ return printing([...errors, "Wrote nothing"], 1);
1725
+ }
1726
+ /**
1727
+ * A refusal for a problem with the project itself (its config, or a database to choose), where
1728
+ * "Wrote nothing" would say nothing useful.
1729
+ */
1730
+ function unusable(error) {
1731
+ return printing([error], 1);
1732
+ }
1733
+ /** Whether a step's result is a refusal, rather than what it checked. */
1734
+ function isPlan(value) {
1735
+ return "steps" in value;
1736
+ }
1737
+ /** The database to generate for: the only one, or the one `--database` names. */
1738
+ function databaseFor(project, options) {
1739
+ const chosen = chooseDatabase(project.databases.map((db) => db.target.database), options.database);
1740
+ if (typeof chosen === "string") return chosen;
1741
+ return project.databases.find((db) => db.target.database === chosen);
1742
+ }
1743
+ /** Only migrations a database's pattern matches are applied, so refuse any other file. */
1744
+ function patternRefusal({ project, db }, path) {
1745
+ const { target } = db;
1746
+ const pattern = target.database.migrationsPattern;
1747
+ const relativePath = slashed(relative(target.configDir, path));
1748
+ if (pattern === void 0 || process.getBuiltinModule("node:path").matchesGlob(relativePath, pattern)) return;
1749
+ return `${shown$1(project.cwd, path)} wouldn't match ${project.adapter.patternSetting ?? "the pattern"} (${pattern}) in ${shown$1(project.cwd, target.configFile)}, so it wouldn't be applied; write the migration with your migration tool instead`;
1750
+ }
1751
+ /**
1752
+ * Each table's key column's type, for the columns that reference it: as the adapter read it, or
1753
+ * else by its attribute's type.
1754
+ */
1755
+ function keyTypes(tables) {
1756
+ return new Map(tables.map((table) => {
1757
+ const spec = table.attributes[table.primaryKey];
1758
+ return [table.name, table.keyType ?? (spec.type === "integer" ? "INTEGER" : "TEXT")];
1759
+ }));
1760
+ }
1761
+ /** Where `g model` writes a Model: its own file, or the one file Models are appended to. */
1762
+ function modelPathOf(cwd, options, className) {
1763
+ const models = options.models ?? "src/models";
1764
+ return resolve(cwd, models, oneModelsFile(models) ? "" : modelFileName(className));
1765
+ }
1766
+ /** The Model `g model` writes, and where (its own file, or appended to one); or why it can't. */
1767
+ function modelFile(request) {
1768
+ const { project, db, options, columns } = request;
1769
+ const { cwd } = project;
1770
+ const { target } = db;
1771
+ const className = request.className;
1772
+ const separateFiles = !oneModelsFile(options.models ?? "src/models");
1773
+ const path = modelPathOf(cwd, options, className);
1774
+ const model = {
1775
+ className,
1776
+ table: tableize(className),
1777
+ associations: columns.filter((column) => column.type === "references").map((column) => ({
1778
+ name: column.association,
1779
+ className: classify(column.association)
1780
+ })),
1781
+ base: {
1782
+ className: target.base.className,
1783
+ importPath: importPath(dirname(path), target.base.path)
1784
+ }
1785
+ };
1786
+ const existing = project.files.get(path);
1787
+ if (existing === void 0) return {
1788
+ path,
1789
+ source: modelSource(model, { separateFiles })
1790
+ };
1791
+ if (separateFiles) return refused(`${shown$1(cwd, path)} already exists`);
1792
+ if (new RegExp(`^export class ${className}\\b`, "m").test(existing)) return refused(`${shown$1(cwd, path)} already has ${className}`);
1793
+ const appended = appendModel(existing, model);
1794
+ return appended.ok ? {
1795
+ path,
1796
+ source: appended.source
1797
+ } : refused(`${shown$1(cwd, path)}: ${appended.error}`);
1798
+ }
1799
+ /** The migration, checked by applying it after the others in memory; or why it was refused. */
1800
+ async function checkedMigration(request, existing) {
1801
+ const { project, db, options, columns } = request;
1802
+ const { adapter } = project;
1803
+ const { target } = db;
1804
+ const { migrationsTable, entry } = target.database;
1805
+ const current = await adapter.readSchema(existing, {
1806
+ migrationsTable,
1807
+ entry
1808
+ });
1809
+ if (!current.ok) return refused(...current.errors);
1810
+ const keys = keyTypes(current.tables);
1811
+ const stem = request.className === void 0 ? options.name : `create_${tableize(request.className)}`;
1812
+ const result = adapter.migration({
1813
+ name: stem,
1814
+ columns,
1815
+ keys,
1816
+ options
1817
+ });
1818
+ if (!result.ok) return refused(result.error);
1819
+ const name = migrationFileName(existing.map((each) => each.name), stem, /* @__PURE__ */ new Date());
1820
+ const after = [...existing, {
1821
+ name,
1822
+ sql: result.sql
1823
+ }].sort((a, b) => byVersion(a.name, b.name));
1824
+ const checked = await adapter.readSchema(after, {
1825
+ migrationsTable,
1826
+ entry
1827
+ });
1828
+ if (!checked.ok) return refused(...checked.errors);
1829
+ return {
1830
+ migration: {
1831
+ path: join(target.migrationsDir, name),
1832
+ source: result.sql
1833
+ },
1834
+ after,
1835
+ schema: checked,
1836
+ notes: result.notes ?? []
1837
+ };
1838
+ }
1839
+ /** The request: the database, the columns and the names, each checked. */
1840
+ function requestFor(project, options) {
1841
+ const db = databaseFor(project, options);
1842
+ if (typeof db === "string") return unusable(db);
1843
+ const refusal = schemaRefusal(project.cwd, db);
1844
+ if (refusal !== void 0) return refused(refusal);
1845
+ if (db.modelErrors.length > 0) return refused(...db.modelErrors);
1846
+ const parsed = parseColumns(options.columns);
1847
+ if (!parsed.ok) return refused(...parsed.errors);
1848
+ const request = {
1849
+ project,
1850
+ db,
1851
+ options,
1852
+ columns: parsed.columns,
1853
+ notes: []
1854
+ };
1855
+ if (options.kind === "migration") {
1856
+ const error = migrationNameError(options.name);
1857
+ return error === void 0 ? request : refused(error);
1858
+ }
1859
+ const model = modelName(options.name);
1860
+ if (!model.ok) return refused(model.error);
1861
+ if (model.note !== void 0) request.notes.push(model.note);
1862
+ return {
1863
+ ...request,
1864
+ className: model.className
1865
+ };
1866
+ }
1867
+ /** The Models found, with the one `g model` writes in place of any of its name. */
1868
+ function withModel(models, added) {
1869
+ return [...models.filter((each) => each.className !== added.className), added];
1870
+ }
1871
+ /** Checks everything a generator would write, before anything is written. */
1872
+ async function checkedFor(project, options) {
1873
+ const request = requestFor(project, options);
1874
+ if (isPlan(request)) return request;
1875
+ const model = request.className === void 0 ? void 0 : modelFile(request);
1876
+ if (model !== void 0 && isPlan(model)) return model;
1877
+ const checked = await checkedMigration(request, request.db.migrations ?? []);
1878
+ if (isPlan(checked)) return checked;
1879
+ const refusal = patternRefusal(request, checked.migration.path);
1880
+ if (refusal !== void 0) return unusable(refusal);
1881
+ const { migration, schema } = checked;
1882
+ const models = model === void 0 || request.className === void 0 ? request.db.models : withModel(request.db.models, {
1883
+ className: request.className,
1884
+ table: tableize(request.className),
1885
+ file: model.path
1886
+ });
1887
+ return {
1888
+ db: {
1889
+ ...request.db,
1890
+ migrations: checked.after,
1891
+ models
1892
+ },
1893
+ migration,
1894
+ model,
1895
+ schema,
1896
+ notes: [...request.notes, ...checked.notes]
1897
+ };
1898
+ }
1899
+ /**
1900
+ * What `g model` or `g migration` writes and prints for a project: a migration (and a Model),
1901
+ * checked against the existing migrations, then the schema regenerated with it.
1902
+ */
1903
+ async function planGenerate(project, options) {
1904
+ const checked = await checkedFor(project, options);
1905
+ if (isPlan(checked)) return checked;
1906
+ const { db, migration, model, notes } = checked;
1907
+ const { cwd } = project;
1908
+ const own = model === void 0 ? [migration] : [migration, model];
1909
+ const schema = schemaWrites(project, db, checked.schema);
1910
+ const named = project.databases.length > 1 ? ` --database ${db.target.database.binding}` : "";
1911
+ return {
1912
+ steps: [
1913
+ ...own.map((file) => written(file, `Wrote ${shown$1(cwd, file.path)}`)),
1914
+ ...schema.steps,
1915
+ ...notes.map((note) => printed(`Note: ${note}`)),
1916
+ printed(`Next: npx active-record migrate${named}`)
1917
+ ],
1918
+ code: 0
1919
+ };
1920
+ }
1921
+ /**
1922
+ * `active-record g model` and `g migration` (#66, #70): write a migration (and a Model), checked
1923
+ * against the existing migrations first, then regenerate the schema with the project's Models.
1924
+ * Resolves to the exit code.
1925
+ */
1926
+ async function runGenerate(options, print) {
1927
+ const cwd = resolve(options.cwd ?? process.cwd());
1928
+ const { config, models, out } = options;
1929
+ const adapter = await loadAdapter(cwd, options.config);
1930
+ if (typeof adapter === "string") {
1931
+ print(adapter);
1932
+ return 1;
1933
+ }
1934
+ for (const note of configNotes(adapter)) print(note);
1935
+ const model = options.kind === "model" ? modelName(options.name) : void 0;
1936
+ const files = model?.ok === true ? [modelPathOf(cwd, options, model.className)] : [];
1937
+ const read = readProject(adapter, cwd, {
1938
+ config,
1939
+ models,
1940
+ out
1941
+ }, files);
1942
+ if (typeof read === "string") {
1943
+ print(read);
1944
+ return 1;
1945
+ }
1946
+ return apply(await planGenerate(await withModels(read, { models }), options), cwd, print);
1947
+ }
1948
+ //#endregion
1949
+ //#region cli/generate/flags.ts
1950
+ /** `active-record g model …` and `active-record g migration …`. */
1951
+ const generateSubcommand = defineSubcommand({
1952
+ options: {
1953
+ id: { type: "string" },
1954
+ "no-timestamps": { type: "boolean" },
1955
+ models: { type: "string" },
1956
+ database: { type: "string" },
1957
+ out: { type: "string" }
1958
+ },
1959
+ usage: ` active-record g model <Name> [columns] Write a CREATE TABLE migration and a Model
1960
+ active-record g migration <Name> [columns] Write a migration: Create…, Add…To…, Remove…From…, or empty`,
1961
+ notes: `Columns are name:type, where the type is string (the default), integer, real, boolean,
1962
+ datetime, json or references; then ! for NOT NULL, =value for a default, and :unique or
1963
+ :index for an index. For example: email:string!:unique active:boolean!=false user:references`,
1964
+ flagHelp: `Options for g:
1965
+ --id integer Give the table an integer key the database generates (a key made in code by default)
1966
+ --no-timestamps Leave out created_at and updated_at
1967
+ --models <path> Write Models here (src/models), or append them to one file (src/models.ts);
1968
+ ApplicationRecord is imported from the same folder
1969
+ --database <name> The database to use, when the config has several
1970
+ --out <file> The schema file to regenerate, when it isn't src/db/schema.ts`,
1971
+ action({ values, positionals }, print, fail) {
1972
+ const [kind, name, ...columns] = positionals;
1973
+ const { id, "no-timestamps": noTimestamps, help: _, ...flags } = values;
1974
+ if (kind !== "model" && kind !== "migration" || name === void 0) return fail("Name what to generate: g model <Name> or g migration <Name>");
1975
+ if (id !== void 0 && id !== "integer" && id !== "text") return fail(`--id is integer or text, not ${id}`);
1976
+ const timestamps = !noTimestamps;
1977
+ return runGenerate({
1978
+ ...flags,
1979
+ kind,
1980
+ name,
1981
+ columns,
1982
+ integerId: id === "integer",
1983
+ timestamps
1984
+ }, print);
1985
+ }
1986
+ });
1987
+ //#endregion
1988
+ //#region cli/init/insert.ts
1989
+ /** Just past the comment starting at `index`, or `index` when none starts there. */
1990
+ function pastComment(text, index) {
1991
+ if (text.startsWith("//", index)) {
1992
+ const end = text.indexOf("\n", index);
1993
+ return end < 0 ? text.length : end;
1994
+ }
1995
+ if (text.startsWith("/*", index)) {
1996
+ const end = text.indexOf("*/", index + 2);
1997
+ return end < 0 ? text.length : end + 2;
1998
+ }
1999
+ return index;
2000
+ }
2001
+ /** Just past the string starting at `start`. */
2002
+ function pastString(text, start) {
2003
+ let index = start + 1;
2004
+ while (index < text.length && text[index] !== "\"") index += text[index] === "\\" ? 2 : 1;
2005
+ return index + 1;
2006
+ }
2007
+ /** The text's tokens, in order: strings, and each other character that isn't space or a comment. */
2008
+ function tokensOf(text) {
2009
+ const tokens = [];
2010
+ let index = 0;
2011
+ while (index < text.length) {
2012
+ const comment = pastComment(text, index);
2013
+ if (comment > index) index = comment;
2014
+ else if (/\s/.test(text[index])) index += 1;
2015
+ else if (text[index] === "\"") {
2016
+ const end = pastString(text, index);
2017
+ tokens.push({
2018
+ start: index,
2019
+ end,
2020
+ value: JSON.parse(text.slice(index, end)),
2021
+ string: true
2022
+ });
2023
+ index = end;
2024
+ } else {
2025
+ tokens.push({
2026
+ start: index,
2027
+ end: index + 1,
2028
+ value: text[index],
2029
+ string: false
2030
+ });
2031
+ index += 1;
2032
+ }
2033
+ }
2034
+ return tokens;
2035
+ }
2036
+ /** How a token changes the depth of nesting: an opening bracket 1, a closing one -1. */
2037
+ function depthChange({ value, string }) {
2038
+ if (string) return 0;
2039
+ if (value === "{" || value === "[") return 1;
2040
+ return value === "}" || value === "]" ? -1 : 0;
2041
+ }
2042
+ /** The index of the token that closes the object or array opened at `open`. */
2043
+ function closing(tokens, open) {
2044
+ let depth = 0;
2045
+ for (let index = open; index < tokens.length; index++) {
2046
+ depth += depthChange(tokens[index]);
2047
+ if (depth === 0) return index;
2048
+ }
2049
+ return tokens.length - 1;
2050
+ }
2051
+ /** Whether the tokens at `index` are the key `databases`, then `:` and an object's `{`. */
2052
+ function isDatabasesKey(tokens, index) {
2053
+ const key = tokens[index];
2054
+ return key.string && key.value === "databases" && tokens[index + 1]?.value === ":" && tokens[index + 2]?.value === "{";
2055
+ }
2056
+ /**
2057
+ * The indexes of the top-level `databases` object's `{` and `}`, if the text has one: the last,
2058
+ * when it has two, as JSON.parse (and so the command) reads it.
2059
+ */
2060
+ function databasesObject(tokens) {
2061
+ let depth = 0;
2062
+ let found;
2063
+ for (let index = 0; index < tokens.length; index++) {
2064
+ depth += depthChange(tokens[index]);
2065
+ if (depth === 1 && isDatabasesKey(tokens, index)) found = {
2066
+ open: index + 2,
2067
+ close: closing(tokens, index + 2)
2068
+ };
2069
+ }
2070
+ return found;
2071
+ }
2072
+ /** The whitespace a line starts with, for the line holding `at`. */
2073
+ function indentAt(text, at) {
2074
+ const lineStart = text.lastIndexOf("\n", at - 1) + 1;
2075
+ return /^[ \t]*/.exec(text.slice(lineStart))[0];
2076
+ }
2077
+ /** The end of `at`'s line, before any `\r`, when only space and comments follow it there, or `at`. */
2078
+ function endOfLine(text, at) {
2079
+ const found = text.indexOf("\n", at);
2080
+ const end = found < 0 ? text.length : found;
2081
+ const lineEnd = text[end - 1] === "\r" ? end - 1 : end;
2082
+ for (let index = at; index < lineEnd;) {
2083
+ if (text.startsWith("//", index)) return lineEnd;
2084
+ const past = pastComment(text, index);
2085
+ if (past > lineEnd) return at;
2086
+ if (past > index) index = past;
2087
+ else if (text[index] === " " || text[index] === " ") index += 1;
2088
+ else return at;
2089
+ }
2090
+ return lineEnd;
2091
+ }
2092
+ /**
2093
+ * The text with `entries` added at the end of its top-level `databases` object, each on a line of
2094
+ * its own (with the file's line endings), as the entries before it are indented, with a trailing
2095
+ * comma if the last one had one;
2096
+ * undefined when the text has no such object with an entry in it.
2097
+ */
2098
+ function withEntries(text, entries) {
2099
+ const tokens = tokensOf(text);
2100
+ const object = databasesObject(tokens);
2101
+ if (object === void 0 || object.close - object.open < 2) return void 0;
2102
+ const last = tokens[object.close - 1];
2103
+ const trailing = last.value === "," && !last.string;
2104
+ const indent = indentAt(text, tokens[object.open + 1].start);
2105
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
2106
+ const lines = entries.map(([key, value]) => {
2107
+ const fields = Object.entries(value).map(([name, field]) => `${JSON.stringify(name)}: ${JSON.stringify(field)}`);
2108
+ return `${eol}${indent}${JSON.stringify(key)}: { ${fields.join(", ")} }`;
2109
+ });
2110
+ const after = endOfLine(text, last.end);
2111
+ const added = trailing ? lines.map((line) => `${line},`).join("") : lines.join(",");
2112
+ return `${text.slice(0, last.end)}${trailing ? "" : ","}${text.slice(last.end, after)}${added}${text.slice(after)}`;
2113
+ }
2114
+ //#endregion
2115
+ //#region cli/init/command.ts
2116
+ /** The JSON Schema the package ships for the file, which editors complete its keys from. */
2117
+ const schemaFile = "config-schema.json";
2118
+ /** The core package as the nearest `node_modules` holds it, or as the project's own will. */
2119
+ function installedCore(cwd, dir) {
2120
+ for (let at = dir;; at = dirname(at)) {
2121
+ const here = join(at, "node_modules", corePackage);
2122
+ if (existsSync(here)) return here;
2123
+ if (dirname(at) === at) return join(cwd, "node_modules", corePackage);
2124
+ }
2125
+ }
2126
+ /** The `$schema` link, from the file's folder to the schema in the installed package. */
2127
+ function schemaLink(cwd, dir) {
2128
+ const link = slashed(relative(dir, join(installedCore(cwd, dir), schemaFile)));
2129
+ return link.startsWith("../") ? link : `./${link}`;
2130
+ }
2131
+ /** The plugin `name`'s entries, chosen with `--adapter`, or why there are none. */
2132
+ async function chosenEntries(dir, name) {
2133
+ if (!adapterNames.includes(name)) return `--adapter takes ${listed(adapterNames)}, not ${name}`;
2134
+ const result = (await pluginOf(name)).init(dir, true);
2135
+ if (result === void 0) return `Nothing here declares a database for ${name}`;
2136
+ return typeof result === "string" ? result : {
2137
+ name,
2138
+ result
2139
+ };
2140
+ }
2141
+ /** The entries of the one adapter something in the project points to, or why there isn't one. */
2142
+ async function foundEntries(dir) {
2143
+ const found = [];
2144
+ for (const name of adapterNames) {
2145
+ const result = (await pluginOf(name)).init(dir, false);
2146
+ if (typeof result === "string") return result;
2147
+ if (result !== void 0) found.push({
2148
+ name,
2149
+ result
2150
+ });
2151
+ }
2152
+ if (found.length === 1) return found[0];
2153
+ if (found.length === 0) return `Nothing here says which database the project uses; choose ${listed(adapterNames)} with --adapter`;
2154
+ return `This project could use ${listed(found.map((each) => each.name))}; choose one with --adapter`;
2155
+ }
2156
+ /** The file's text: the schema link, then each database with its adapter first. */
2157
+ function source(link, { name, result }) {
2158
+ const databases = Object.fromEntries(Object.entries(result.databases).map(([binding, entry]) => [binding, {
2159
+ adapter: name,
2160
+ ...entry
2161
+ }]));
2162
+ return `${JSON.stringify({
2163
+ $schema: link,
2164
+ databases
2165
+ }, null, 2)}\n`;
2166
+ }
2167
+ /**
2168
+ * What `init` does when the file is there: add each database the adapter the file names finds and
2169
+ * the file doesn't name, keeping the rest of the text as written; or say why it can't.
2170
+ */
2171
+ async function planAdding(cwd, path, options) {
2172
+ const name = shown$1(cwd, path);
2173
+ const adapter = await loadAdapter(cwd, options.config);
2174
+ if (typeof adapter === "string") return printing([adapter], 1);
2175
+ if (options.adapter !== void 0 && options.adapter !== adapter.name) return printing([`${name} names ${adapter.name}; a project uses one adapter, for now, so --adapter ${options.adapter} adds nothing`], 1);
2176
+ const found = adapter.init(dirname(path), false);
2177
+ if (typeof found === "string") return printing([found], 1);
2178
+ const text = readFileSync(path, "utf8");
2179
+ const named = parseJsonc(text).databases;
2180
+ const missing = Object.entries(found?.databases ?? {}).filter(([key]) => !Object.hasOwn(named, key));
2181
+ if (missing.length === 0) return printing([`${name} names every database init finds; it wrote nothing`]);
2182
+ const source = withEntries(text, missing.map(([key, entry]) => [key, {
2183
+ adapter: adapter.name,
2184
+ ...entry
2185
+ }]));
2186
+ if (source === void 0) return printing([`${name}'s databases couldn't be found to add to`], 1);
2187
+ const bindings = missing.map(([key]) => key);
2188
+ const notes = bindings.flatMap((key) => found?.notes?.[key] ?? []).map((note) => printed(`Note: ${note}`));
2189
+ const added = `Added ${listed(bindings, "and")} to ${name} (on ${adapter.name})`;
2190
+ return {
2191
+ steps: [written({
2192
+ path,
2193
+ source
2194
+ }, added), ...notes],
2195
+ code: 0
2196
+ };
2197
+ }
2198
+ /** What `init` does: write the file, and say what's next; or say why it can't. */
2199
+ async function planInit(options) {
2200
+ const cwd = resolve(options.cwd ?? process.cwd());
2201
+ const path = resolve(cwd, options.config ?? "active-record.jsonc");
2202
+ const name = shown$1(cwd, path);
2203
+ const there = lstatSync(path, { throwIfNoEntry: false });
2204
+ if (there?.isSymbolicLink() === true) return printing([`${name} is a link; init writes nothing through it`], 1);
2205
+ if (there !== void 0) return planAdding(cwd, path, options);
2206
+ const dir = dirname(path);
2207
+ const found = options.adapter === void 0 ? await foundEntries(dir) : await chosenEntries(dir, options.adapter);
2208
+ if (typeof found === "string") return printing([found], 1);
2209
+ const bindings = listed(Object.keys(found.result.databases), "and");
2210
+ const notes = Object.values(found.result.notes ?? {}).map((note) => printed(`Note: ${note}`));
2211
+ return {
2212
+ steps: [
2213
+ written({
2214
+ path,
2215
+ source: source(schemaLink(cwd, dir), found)
2216
+ }, `Wrote ${name} (${bindings}, on ${found.name})`),
2217
+ ...notes,
2218
+ printed("Next: npx active-record schema")
2219
+ ],
2220
+ code: 0
2221
+ };
2222
+ }
2223
+ /** `active-record init`: resolves to the exit code. */
2224
+ async function runInit(options, print) {
2225
+ return apply(await planInit(options), resolve(options.cwd ?? process.cwd()), print);
2226
+ }
2227
+ //#endregion
2228
+ //#region cli/init/flags.ts
2229
+ /** `active-record init`: writes the project's active-record.jsonc. */
2230
+ const initSubcommand = defineSubcommand({
2231
+ options: { adapter: { type: "string" } },
2232
+ usage: ` active-record init Write active-record.jsonc, which names your databases`,
2233
+ flagHelp: `Options for init:
2234
+ --adapter <name> The adapter, when the project could use several, or nothing says which`,
2235
+ action({ values, positionals }, print, fail) {
2236
+ if (positionals.length > 0) return fail(`Unexpected ${positionals[0]}`);
2237
+ const { help: _, ...options } = values;
2238
+ return runInit(options, print);
2239
+ }
2240
+ });
2241
+ //#endregion
2242
+ //#region cli/migrate/command.ts
2243
+ const standardIo = () => ({
2244
+ input: process.stdin,
2245
+ output: process.stdout,
2246
+ terminal: process.stdin.isTTY === true && process.stdout instanceof WriteStream
2247
+ });
2248
+ /** Whether the real database may be migrated: `--yes`, or its name typed on a terminal. */
2249
+ async function allowed(target, options, io) {
2250
+ if (options.yes === true) return void 0;
2251
+ if (!io.terminal) return "Migrating a remote database asks you to confirm it: run this on a terminal, or add --yes";
2252
+ const { confirmed, release } = await confirmRemote({
2253
+ input: io.input,
2254
+ output: io.output,
2255
+ target,
2256
+ consequence: "Its pending migrations are applied to it, and can't be undone from here."
2257
+ });
2258
+ await release();
2259
+ return confirmed ? void 0 : "Not migrated.";
2260
+ }
2261
+ /** `active-record migrate`: resolves to the exit code, the adapter's own when it ran. */
2262
+ async function runMigrate(options, print, io = standardIo()) {
2263
+ const cwd = options.cwd ?? process.cwd();
2264
+ const adapter = await loadAdapter(cwd, options.config);
2265
+ if (typeof adapter === "string") {
2266
+ print(adapter);
2267
+ return 1;
2268
+ }
2269
+ for (const note of configNotes(adapter)) print(note);
2270
+ const chosen = chosenDatabase(adapter, cwd, options);
2271
+ if (typeof chosen === "string") {
2272
+ print(chosen);
2273
+ return 1;
2274
+ }
2275
+ const remote = options.remote === true;
2276
+ if (remote) {
2277
+ const target = adapter.remote(chosen, "migrate");
2278
+ const refusal = typeof target === "string" ? target : await allowed(target, options, io);
2279
+ if (refusal !== void 0) {
2280
+ print(refusal);
2281
+ return 1;
2282
+ }
2283
+ }
2284
+ return adapter.migrate(cwd, chosen, { remote }, { output: (text) => io.output.write(text) });
2285
+ }
2286
+ //#endregion
2287
+ //#region cli/migrate/flags.ts
2288
+ /** `active-record migrate`: applies the pending migrations, to the local database or the real one. */
2289
+ const migrateSubcommand = defineSubcommand({
2290
+ options: {
2291
+ database: { type: "string" },
2292
+ remote: { type: "boolean" },
2293
+ yes: { type: "boolean" }
2294
+ },
2295
+ usage: ` active-record migrate Apply your pending migrations to the local database`,
2296
+ flagHelp: `Options for migrate:
2297
+ --database <name> The database to migrate, when the config has several
2298
+ --remote Migrate your remote database instead, after asking you to type its name
2299
+ --yes Don't ask first (with --remote); also how to migrate it without a terminal`,
2300
+ action({ values, positionals }, print, fail) {
2301
+ if (positionals.length > 0) return fail(`Unexpected ${positionals[0]}`);
2302
+ const { help: _, ...options } = values;
2303
+ if (options.yes && !options.remote) return fail("--yes only goes with --remote");
2304
+ return runMigrate(options, print);
2305
+ }
2306
+ });
2307
+ //#endregion
2308
+ //#region cli/schema/command.ts
2309
+ /** A schema that couldn't be generated: the errors, and that the last good file stays as it was. */
2310
+ function failed(errors, cwd, db) {
2311
+ const out = shown$1(cwd, db.target.out);
2312
+ const kept = db.schema === void 0 ? `Wrote nothing to ${out}` : `Kept ${out} as it was`;
2313
+ return printing([...errors, kept], 1);
2314
+ }
2315
+ /** `--check`: whether the file on disk was generated from these tables (its fingerprint, not its format). */
2316
+ function checkPlan(project, db, tables) {
2317
+ const out = shown$1(project.cwd, db.target.out);
2318
+ const schema = schemaSourceOf(project, db, tables);
2319
+ const current = db.schema !== void 0 && fingerprintIn(db.schema) === fingerprintOf(schema);
2320
+ return printing([current ? `${out} is up to date` : `${out} is out of date: run \`active-record schema\``], current ? 0 : 1);
2321
+ }
2322
+ /** One database's schema, generated (or, with `check`, checked). */
2323
+ async function planDatabase(project, db, check) {
2324
+ const { adapter, cwd } = project;
2325
+ if (db.migrations === void 0) return failed([`No migrations folder at ${shown$1(cwd, db.target.migrationsDir)}/`], cwd, db);
2326
+ const refusal = check ? void 0 : schemaRefusal(cwd, db);
2327
+ if (refusal !== void 0) return failed([refusal], cwd, db);
2328
+ if (db.modelErrors.length > 0) return failed(db.modelErrors, cwd, db);
2329
+ const { migrationsTable, entry } = db.target.database;
2330
+ const result = await adapter.readSchema(db.migrations, {
2331
+ migrationsTable,
2332
+ entry
2333
+ });
2334
+ if (!result.ok) return failed(result.errors, cwd, db);
2335
+ return check ? checkPlan(project, db, result.tables) : schemaWrites(project, db, result);
2336
+ }
2337
+ /** What `active-record schema` writes and prints for a project (or, with `check`, only prints). */
2338
+ async function planSchema(project, check) {
2339
+ return combined(await Promise.all(project.databases.map((db) => planDatabase(project, db, check))));
2340
+ }
2341
+ /**
2342
+ * `active-record schema`: generates each database's `schema.ts` from its migrations and the Models
2343
+ * built on it (#66, #68, #232). Resolves to the exit code: 0, or 1 when anything failed or, with
2344
+ * `check`, is out of date.
2345
+ */
2346
+ async function runSchema(options, print) {
2347
+ const cwd = resolve(options.cwd ?? process.cwd());
2348
+ const adapter = await loadAdapter(cwd, options.config);
2349
+ if (typeof adapter === "string") {
2350
+ print(adapter);
2351
+ return 1;
2352
+ }
2353
+ for (const note of configNotes(adapter)) print(note);
2354
+ const read = readProject(adapter, cwd, options);
2355
+ if (typeof read === "string") {
2356
+ print(read);
2357
+ return 1;
2358
+ }
2359
+ const project = await withModels(read, {
2360
+ models: options.models,
2361
+ check: options.check
2362
+ });
2363
+ return apply(await planSchema(project, options.check === true), project.cwd, print);
2364
+ }
2365
+ /**
2366
+ * `active-record schema --watch` from the command line: watching, once its adapter loads; or, when
2367
+ * it can't (none installed, or a Node it can't run on), 1, having said why, as a run without
2368
+ * `--watch` would.
2369
+ */
2370
+ async function watchFromCommandLine(options, print) {
2371
+ const adapter = await loadAdapter(resolve(options.cwd ?? process.cwd()), options.config);
2372
+ if (typeof adapter === "string") {
2373
+ print(adapter);
2374
+ return 1;
2375
+ }
2376
+ watchSchema(options, print);
2377
+ return "watching";
2378
+ }
2379
+ /**
2380
+ * `active-record schema --watch`: generates, then again whenever a migration or a Model file changes,
2381
+ * keeping the last good file when one fails. Returns a function that stops watching.
2382
+ */
2383
+ async function watchSchema(options, print) {
2384
+ let running = runSchema(options, print);
2385
+ const cwd = resolve(options.cwd ?? process.cwd());
2386
+ const adapter = await loadAdapter(cwd, options.config);
2387
+ if (typeof adapter === "string") return () => {};
2388
+ const project = readProject(adapter, cwd, options);
2389
+ if (typeof project === "string") return () => {};
2390
+ let pending;
2391
+ const regenerate = () => {
2392
+ clearTimeout(pending);
2393
+ pending = setTimeout(() => {
2394
+ running = running.then(() => runSchema(options, print));
2395
+ }, 50);
2396
+ };
2397
+ const watchers = [...project.databases.filter((db) => db.migrations !== void 0).map((db) => db.target.migrationsDir), ...modelsFolders(cwd, options.models)].map((folder) => watch(folder, { recursive: true }, regenerate));
2398
+ return () => {
2399
+ clearTimeout(pending);
2400
+ for (const watcher of watchers) watcher.close();
2401
+ };
2402
+ }
2403
+ //#endregion
2404
+ //#region cli/main.ts
2405
+ /** Each subcommand by the names it answers to. */
2406
+ const subcommands = {
2407
+ init: initSubcommand,
2408
+ schema: defineSubcommand({
2409
+ options: {
2410
+ check: { type: "boolean" },
2411
+ watch: { type: "boolean" },
2412
+ out: { type: "string" },
2413
+ migrations: { type: "string" },
2414
+ models: { type: "string" }
2415
+ },
2416
+ usage: ` active-record schema [options] Generate src/db/schema.ts from your migrations`,
2417
+ flagHelp: `Options for schema:
2418
+ --check Fail if the generated schema is out of date (for CI)
2419
+ --watch Regenerate whenever a migration changes
2420
+ --out <file> Write here instead (a folder, with several databases)
2421
+ --migrations <dir> Read migrations from here instead
2422
+ --models <dir> Write ApplicationRecord here (src/models by default)`,
2423
+ action({ values, positionals }, print, fail) {
2424
+ const { watch, help: _, ...options } = values;
2425
+ if (positionals.length > 0) return fail(`Unexpected ${positionals[0]}`);
2426
+ return watch ? watchFromCommandLine(options, print) : runSchema(options, print);
2427
+ }
2428
+ }),
2429
+ g: generateSubcommand,
2430
+ generate: generateSubcommand,
2431
+ console: consoleSubcommand,
2432
+ c: consoleSubcommand,
2433
+ migrate: migrateSubcommand
2434
+ };
2435
+ const help = helpFor([...new Set(Object.values(subcommands))]);
2436
+ /** Prints the usage, after what went wrong; 1. */
2437
+ function usage(print, problem) {
2438
+ print(`${problem}\n\n${help}`);
2439
+ return 1;
2440
+ }
2441
+ /**
2442
+ * Whether this Node has what the command itself uses: `process.getBuiltinModule`, `fs.globSync`
2443
+ * and `path.matchesGlob` (Node 22.5; Node 20 has only the first and last). A plugin says what
2444
+ * it needs itself, with `unsupported`.
2445
+ */
2446
+ function isSupportedNode() {
2447
+ if (typeof process.getBuiltinModule !== "function") return false;
2448
+ const { globSync } = process.getBuiltinModule("node:fs");
2449
+ return globSync !== void 0 && process.getBuiltinModule("node:path").matchesGlob !== void 0;
2450
+ }
2451
+ /** Runs the command line: the exit code, or "watching" while `schema --watch` runs on. */
2452
+ function main(argv, print = console.log) {
2453
+ const [command = "", ...rest] = argv;
2454
+ const subcommand = Object.hasOwn(subcommands, command) ? subcommands[command] : void 0;
2455
+ const asked = [command, ...rest].some((arg) => arg === "--help" || arg === "-h");
2456
+ if (subcommand === void 0 || asked) {
2457
+ print(help);
2458
+ return asked ? 0 : 1;
2459
+ }
2460
+ if (!isSupportedNode()) {
2461
+ print(`active-record ${command} needs Node 22.5 or later (this is Node ${process.versions.node})`);
2462
+ return 1;
2463
+ }
2464
+ return subcommand.run(rest, print, (problem) => usage(print, problem));
2465
+ }
2466
+ //#endregion
2467
+ //#region cli/bin.ts
2468
+ const code = await main(process.argv.slice(2));
2469
+ if (code !== "watching") process.exitCode = code;
2470
+ //#endregion
2471
+ export {};