@forestfuture/active-record 0.6.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,600 @@
1
+ import { a as underscore } from "./epoch-storage-o2aoOH7H.mjs";
2
+ import { i as indexName, n as migrationSql, r as quotedName, t as generatedSchema } from "./for-adapters-Ch6CoHD4.mjs";
3
+ import { l as parseJsonc, n as attributeName, o as listed, t as storageOverride } from "./storage-override-CpbkdIqE.mjs";
4
+ import { createRequire } from "node:module";
5
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { createJiti } from "jiti";
8
+ import { tmpdir } from "node:os";
9
+ import { fileURLToPath } from "node:url";
10
+ import { spawn } from "node:child_process";
11
+ //#region cli/adapters/d1/remote.ts
12
+ const text = (value) => typeof value === "string" && value !== "" ? value : void 0;
13
+ /**
14
+ * The remote database this binding's entry points at, or why there's none: for the console,
15
+ * `preview_database_id` when there is one, as `wrangler dev` opens it, or else `database_id`; for
16
+ * `migrate`, always `database_id`, the one `wrangler d1 migrations apply --remote` changes.
17
+ */
18
+ function remoteTarget({ binding, entry, configFile }, use = "open") {
19
+ const previewId = use === "open" ? text(entry["preview_database_id"]) : void 0;
20
+ const id = previewId ?? text(entry["database_id"]);
21
+ if (id === void 0) return `${binding} has no database_id in ${basename(configFile)}, which --remote needs`;
22
+ const name = text(entry["database_name"]) ?? binding;
23
+ const target = {
24
+ name,
25
+ description: `Remote ${previewId === void 0 ? "database" : "preview database"} ${binding} (${name}, id ${id})`
26
+ };
27
+ return previewId === void 0 ? target : {
28
+ ...target,
29
+ note: "That is the config's preview_database_id, which Wrangler opens in place of database_id."
30
+ };
31
+ }
32
+ //#endregion
33
+ //#region cli/adapters/d1/wrangler.ts
34
+ const candidates = [
35
+ "wrangler.jsonc",
36
+ "wrangler.json",
37
+ "wrangler.toml"
38
+ ];
39
+ /** A TOML basic string's contents, its escapes decoded (`\\` → `\`, `\u00e9` → `é`). */
40
+ function basicString(body) {
41
+ return JSON.parse(`"${body.replace(/\\U([0-9a-fA-F]{8})/g, (_, hex) => {
42
+ return JSON.stringify(String.fromCodePoint(Number.parseInt(hex, 16))).slice(1, -1);
43
+ })}"`);
44
+ }
45
+ /** A TOML line's `key = "string"` as `[key, value]`, or undefined for any other line. */
46
+ function tomlPair(line) {
47
+ const pair = /^([\w-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)')/.exec(line);
48
+ if (pair === null) return void 0;
49
+ return [pair[1], pair[2] === void 0 ? pair[3] : basicString(pair[2])];
50
+ }
51
+ /** The `[[d1_databases]]` entries and top-level `account_id` of a wrangler.toml: the keys read. */
52
+ function parseToml(text) {
53
+ const databases = [];
54
+ const topLevel = {};
55
+ let current = topLevel;
56
+ for (const line of text.split("\n").map((each) => each.trim())) {
57
+ if (line.startsWith("[")) {
58
+ current = /^\[\[\s*d1_databases\s*\]\](\s*#.*)?$/.test(line) ? {} : void 0;
59
+ if (current !== void 0) databases.push(current);
60
+ continue;
61
+ }
62
+ const pair = tomlPair(line);
63
+ if (current !== void 0 && pair !== void 0) current[pair[0]] = pair[1];
64
+ }
65
+ return {
66
+ d1_databases: databases,
67
+ account_id: topLevel.account_id
68
+ };
69
+ }
70
+ /** The parsed config file, or why it couldn't be read. */
71
+ function parsed(file) {
72
+ const text = readFileSync(file, "utf8");
73
+ try {
74
+ return file.endsWith(".toml") ? parseToml(text) : parseJsonc(text);
75
+ } catch (error) {
76
+ return `${basename(file)} couldn't be read: ${error.message}`;
77
+ }
78
+ }
79
+ /** A config entry as a database: its binding, and its migrations' folder, pattern and table. */
80
+ function databaseOf(entry) {
81
+ const database = {
82
+ binding: String(entry.binding),
83
+ migrationsDir: typeof entry.migrations_dir === "string" ? entry.migrations_dir : "migrations",
84
+ entry
85
+ };
86
+ if (typeof entry.migrations_pattern === "string") database.migrationsPattern = entry.migrations_pattern;
87
+ if (typeof entry.migrations_table === "string") database.migrationsTable = entry.migrations_table;
88
+ return database;
89
+ }
90
+ /** The Wrangler config in `dir`: `wrangler.jsonc`, `wrangler.json` or `wrangler.toml`, if any. */
91
+ function wranglerConfigIn(dir) {
92
+ return candidates.map((each) => join(dir, each)).find((path) => existsSync(path));
93
+ }
94
+ /** The Wrangler config's `d1_databases` entries, each with a binding, or why they can't be read. */
95
+ function d1Entries(file) {
96
+ const config = parsed(file);
97
+ if (typeof config === "string") return config;
98
+ const entries = config.d1_databases ?? [];
99
+ if (entries.some((entry) => typeof entry.binding !== "string")) return `${basename(file)} has a d1_databases entry with no binding`;
100
+ return entries;
101
+ }
102
+ /**
103
+ * A note for the D1 databases the Wrangler config has that `active-record.jsonc` doesn't name, which
104
+ * the command leaves out, so one added to Wrangler's config alone isn't missed in silence (#301).
105
+ */
106
+ function unnamed(entries, project, file) {
107
+ const left = entries.map((entry) => String(entry.binding)).filter((binding) => !Object.hasOwn(project.databases, binding));
108
+ if (left.length === 0) return [];
109
+ const one = left.length === 1;
110
+ const which = `the D1 database${one ? "" : "s"} ${listed(left, "and")}`;
111
+ return [`${basename(file)} has ${which}, which ${basename(project.file)} doesn't name; run \`npx active-record init\` to add ${one ? "it" : "them"}`];
112
+ }
113
+ /**
114
+ * The D1 databases a project's `active-record.jsonc` names, as its Wrangler config declares them:
115
+ * `wrangler.jsonc`, `wrangler.json` or `wrangler.toml`, beside `active-record.jsonc`. Wrangler's
116
+ * other D1 databases are left out.
117
+ */
118
+ function readWranglerConfig(project) {
119
+ const name = basename(project.file);
120
+ const file = wranglerConfigIn(project.dir);
121
+ if (file === void 0) return {
122
+ ok: false,
123
+ error: `No wrangler.jsonc, wrangler.json or wrangler.toml beside ${name}`
124
+ };
125
+ const entries = d1Entries(file);
126
+ if (typeof entries === "string") return {
127
+ ok: false,
128
+ error: entries
129
+ };
130
+ const databases = [];
131
+ for (const binding of Object.keys(project.databases)) {
132
+ const entry = entries.find((each) => each.binding === binding);
133
+ if (entry === void 0) return {
134
+ ok: false,
135
+ error: `${name} names ${binding}, which isn't in ${basename(file)}'s d1_databases`
136
+ };
137
+ databases.push(databaseOf(entry));
138
+ }
139
+ return {
140
+ ok: true,
141
+ file,
142
+ dir: dirname(file),
143
+ databases,
144
+ notes: unnamed(entries, project, file)
145
+ };
146
+ }
147
+ /** The account a Wrangler config names (`account_id`), if it names one and can be read. */
148
+ function accountIdIn(configFile) {
149
+ const config = parsed(configFile);
150
+ if (typeof config === "string") return void 0;
151
+ return typeof config.account_id === "string" ? config.account_id : void 0;
152
+ }
153
+ //#endregion
154
+ //#region cli/adapters/d1/binding.ts
155
+ /**
156
+ * A Wrangler config holding only this D1 binding, in a folder of its own. `getPlatformProxy`
157
+ * starts every binding a config declares, so the project's own config would bring its Durable
158
+ * Objects, services and secrets (with their warnings, or failures) into a console that only
159
+ * needs the database. The entry is the project's, verbatim, so Wrangler names the same local D1;
160
+ * the `account_id` is carried so a remote proxy signs in to the project's account.
161
+ */
162
+ function d1OnlyConfig(entry, accountId) {
163
+ const dir = mkdtempSync(join(tmpdir(), "d1-record-console-"));
164
+ const file = join(dir, "wrangler.jsonc");
165
+ writeFileSync(file, JSON.stringify({
166
+ name: "d1-record-console",
167
+ account_id: accountId,
168
+ d1_databases: [entry]
169
+ }));
170
+ return {
171
+ file,
172
+ remove: () => rmSync(dir, {
173
+ recursive: true,
174
+ force: true
175
+ })
176
+ };
177
+ }
178
+ /** The project's own wrangler, loaded; or why it can't be. */
179
+ async function projectWrangler(cwd) {
180
+ let file;
181
+ try {
182
+ file = createJiti(`${cwd}/`).esmResolve("wrangler");
183
+ } catch {
184
+ return "wrangler isn't installed here (install it, then run active-record console again)";
185
+ }
186
+ try {
187
+ return createRequire(import.meta.url)(fileURLToPath(file));
188
+ } catch (error) {
189
+ return `Couldn't load wrangler: ${error.message}`;
190
+ }
191
+ }
192
+ async function open(cwd, { binding, configFile }, opening) {
193
+ const wrangler = await projectWrangler(cwd);
194
+ if (typeof wrangler === "string") return wrangler;
195
+ const config = d1OnlyConfig(opening.entry, accountIdIn(configFile));
196
+ let proxy;
197
+ try {
198
+ proxy = await wrangler.getPlatformProxy({
199
+ configPath: config.file,
200
+ persist: opening.persist,
201
+ remoteBindings: opening.remoteBindings
202
+ });
203
+ } catch (error) {
204
+ config.remove();
205
+ return opening.failure(binding, error.message);
206
+ }
207
+ process.once("exit", config.remove);
208
+ return {
209
+ binding: proxy.env[binding],
210
+ description: opening.describe(binding),
211
+ dispose: async () => {
212
+ process.off("exit", config.remove);
213
+ try {
214
+ await proxy.dispose();
215
+ } finally {
216
+ config.remove();
217
+ }
218
+ }
219
+ };
220
+ }
221
+ /**
222
+ * The chosen binding on the project's local D1, in the `.wrangler/state` beside the config that
223
+ * `wrangler dev` and `wrangler d1 migrations apply --local` use (`getPlatformProxy`'s own default
224
+ * is relative to the working directory, which can be anywhere). `remoteBindings: false` keeps it
225
+ * local even for a binding the config marks `remote: true`, which Wrangler would otherwise use.
226
+ */
227
+ function openLocalBinding(cwd, chosen) {
228
+ return open(cwd, chosen, {
229
+ entry: chosen.entry,
230
+ persist: { path: join(dirname(chosen.configFile), ".wrangler/state/v3") },
231
+ remoteBindings: false,
232
+ describe: (binding) => `Local database ${binding} (.wrangler/state)`,
233
+ failure: (binding, reason) => `Wrangler couldn't open ${binding}: ${reason}`
234
+ });
235
+ }
236
+ const signInHint = "Sign in with 'wrangler login', or set CLOUDFLARE_API_TOKEN (and CLOUDFLARE_ACCOUNT_ID).";
237
+ /**
238
+ * The chosen binding on the project's real D1, through Wrangler's remote proxy: its entry is
239
+ * marked `remote: true` whatever the config says, since asking for `--remote` is the consent.
240
+ * Nothing is kept locally. Which database that is follows Wrangler: `preview_database_id` first.
241
+ */
242
+ function openRemoteBinding(cwd, chosen) {
243
+ const target = remoteTarget(chosen);
244
+ if (typeof target === "string") return Promise.resolve(target);
245
+ return open(cwd, chosen, {
246
+ entry: {
247
+ ...chosen.entry,
248
+ remote: true
249
+ },
250
+ persist: false,
251
+ remoteBindings: true,
252
+ describe: () => target.description,
253
+ failure: (binding, reason) => `Wrangler couldn't open ${binding} remotely: ${reason}\n${signInHint}`
254
+ });
255
+ }
256
+ //#endregion
257
+ //#region cli/adapters/d1/init.ts
258
+ /**
259
+ * The D1 databases in the Wrangler config in `dir`, each as an entry with nothing but its
260
+ * adapter: Wrangler's config keeps the rest. Undefined when there are none, unless `--adapter` named D1.
261
+ */
262
+ function init(dir, named) {
263
+ const file = wranglerConfigIn(dir);
264
+ if (file === void 0) {
265
+ if (!named) return void 0;
266
+ return "No wrangler.jsonc, wrangler.json or wrangler.toml here: declare your D1 database in one first";
267
+ }
268
+ const entries = d1Entries(file);
269
+ if (typeof entries === "string") return entries;
270
+ if (entries.length === 0) return named ? `${basename(file)} has no d1_databases: declare your database there first` : void 0;
271
+ return { databases: Object.fromEntries(entries.map((entry) => [String(entry.binding), {}])) };
272
+ }
273
+ //#endregion
274
+ //#region cli/adapters/d1/migrate.ts
275
+ /** The project's own Wrangler's command line script, or why there's none. */
276
+ function wranglerBin(cwd) {
277
+ try {
278
+ const manifest = fileURLToPath(createJiti(`${cwd}/`).esmResolve("wrangler/package.json"));
279
+ return join(dirname(manifest), "bin", "wrangler.js");
280
+ } catch {
281
+ return ["wrangler isn't installed here (install it, then run active-record migrate again)"];
282
+ }
283
+ }
284
+ /**
285
+ * Runs `wrangler d1 migrations apply <binding>`, `--local` or `--remote`, with the project's
286
+ * config, as a person would. What Wrangler prints goes to `io`; it resolves to Wrangler's exit code.
287
+ */
288
+ function migrate(cwd, { binding, configFile }, { remote }, io) {
289
+ const bin = wranglerBin(cwd);
290
+ if (Array.isArray(bin)) {
291
+ io.output(`${bin[0]}\n`);
292
+ return Promise.resolve(1);
293
+ }
294
+ const args = [
295
+ bin,
296
+ "d1",
297
+ "migrations",
298
+ "apply",
299
+ binding,
300
+ remote ? "--remote" : "--local",
301
+ "--config",
302
+ configFile
303
+ ];
304
+ const child = spawn(process.execPath, args, {
305
+ cwd: dirname(configFile),
306
+ env: {
307
+ ...process.env,
308
+ CI: "1"
309
+ },
310
+ stdio: [
311
+ "ignore",
312
+ "pipe",
313
+ "pipe"
314
+ ]
315
+ });
316
+ child.stdout.on("data", (chunk) => io.output(chunk.toString()));
317
+ child.stderr.on("data", (chunk) => io.output(chunk.toString()));
318
+ return new Promise((resolve) => {
319
+ child.on("error", (error) => {
320
+ io.output(`Couldn't run wrangler: ${error.message}\n`);
321
+ resolve(1);
322
+ });
323
+ child.on("close", (code) => resolve(code ?? 1));
324
+ });
325
+ }
326
+ //#endregion
327
+ //#region cli/adapters/d1/migration.ts
328
+ /** SQLite's SQL for a generated migration. */
329
+ const sqlite = {
330
+ reserved: new Set("abort action add after all alter always analyze and as asc attach autoincrement before begin between by cascade case cast check collate column commit conflict constraint create cross current current_date current_time current_timestamp database default deferrable deferred delete desc detach distinct do drop each else end escape except exclude exclusive exists explain fail filter first following for foreign from full generated glob group groups having if ignore immediate in index indexed initially inner insert instead intersect into is isnull join key last left like limit match materialized natural no not nothing notnull null nulls of offset on or order others outer over partition plan pragma preceding primary query raise range recursive references regexp reindex release rename replace restrict returning right rollback row rows savepoint select set table temp temporary then ties to transaction trigger unbounded union unique update using vacuum values view virtual when where window with without".split(" ")),
331
+ types: {
332
+ string: "TEXT",
333
+ integer: "INTEGER",
334
+ real: "REAL",
335
+ boolean: "BOOLEAN",
336
+ datetime: "DATETIME",
337
+ json: "TEXT"
338
+ },
339
+ key: (integerId) => integerId ? "id INTEGER PRIMARY KEY" : "id TEXT PRIMARY KEY NOT NULL",
340
+ timestampType: "DATETIME",
341
+ guessedKeyType: "TEXT",
342
+ check: (column, name) => column.type === "json" ? `CHECK (json_valid(${name}))` : void 0,
343
+ addRefusal: (table, column) => column.type !== "references" && column.notNull && column.default === void 0 ? `${table}.${column.name}: SQLite can't add a NOT NULL column without a default; give one (${column.name}:${column.type}!=…) or leave out the !` : void 0,
344
+ dropColumn: (table, column) => `DROP INDEX IF EXISTS ${indexName(table, column)};\nALTER TABLE ${quotedName(sqlite, table)} DROP COLUMN ${quotedName(sqlite, column)};\n`
345
+ };
346
+ /** A migration's SQL, for SQLite as D1 runs it, with a note for each key type it guessed. */
347
+ function migration(change) {
348
+ return migrationSql(change, sqlite);
349
+ }
350
+ //#endregion
351
+ //#region cli/adapters/d1/conventions.ts
352
+ const declaredTypes = [
353
+ [/^BOOL/, "boolean"],
354
+ [/^(DATETIME|TIMESTAMP|DATE)$/, "datetime"],
355
+ [/^JSON$/, "json"],
356
+ [/INT/, "integer"],
357
+ [/CHAR|CLOB|TEXT/, "string"],
358
+ [/REAL|FLOA|DOUB/, "real"]
359
+ ];
360
+ /** The declared type's name, without its size or precision: `VARCHAR(40)` → `VARCHAR`. */
361
+ function baseType(declared) {
362
+ return declared.toUpperCase().replace(/\(.*\)/, "").trim();
363
+ }
364
+ /** Why a declared type can't be an attribute, if it can't. */
365
+ function unsupported$1(declared, name, where) {
366
+ if (/^(NUMERIC|DECIMAL)$/.test(declared)) return `${where}: ${declared} loses precision as a number; store money as integer cents (${name}_cents INTEGER)`;
367
+ return declared === "BLOB" ? `${where}: BLOB columns aren't supported yet (#20)` : void 0;
368
+ }
369
+ /** A default that's a number or an epoch function, which a datetime in ISO text wouldn't hold. */
370
+ const epochDefault = /^\(?\s*-?\d+(\.\d+)?\s*\)?$|unixepoch|strftime\s*\(\s*'%s'/i;
371
+ /** A note for a datetime column whose default looks like a Unix time (#73). */
372
+ function epochDefaultNote(column, type) {
373
+ if (type !== "datetime" || column.defaultValue === null) return void 0;
374
+ if (!epochDefault.test(column.defaultValue.trim())) return void 0;
375
+ return `${column.table}.${column.name}: a datetime with a number as its default; if it holds a Unix time, override it in its Model as ${storageOverride(false)}`;
376
+ }
377
+ /** A column's attribute type: its declared type first, then its name for plain TEXT/INTEGER. */
378
+ function typeOf(column) {
379
+ const declared = baseType(column.declaredType || (column.referencedType ?? ""));
380
+ const where = `${column.table}.${column.name}`;
381
+ const error = unsupported$1(declared, column.name, where);
382
+ if (error !== void 0) return { error };
383
+ return typeOfDeclared(column, declared, where);
384
+ }
385
+ /** The attribute type for a supported declared type; a guess (`string`) comes with a note (#159). */
386
+ function typeOfDeclared(column, declared, where) {
387
+ const matched = declaredTypes.find(([pattern]) => pattern.test(declared))?.[1];
388
+ if ((matched === void 0 || matched === "string") && column.jsonChecked) return { type: "json" };
389
+ if (matched === void 0) return {
390
+ type: "string",
391
+ note: unmatchedNote(declared, where)
392
+ };
393
+ return declared === "TEXT" || declared === "INTEGER" ? refinedByName(column, matched, where) : { type: matched };
394
+ }
395
+ /** A note for a column whose declared type is none of the types SQLite gives an affinity (#159). */
396
+ function unmatchedNote(declared, where) {
397
+ return `${where}: ${declared === "" ? "has no declared type" : `is declared ${declared}`}, so it's read as a string; a number in it fails when the record loads, so override it in its Model with the type it holds`;
398
+ }
399
+ /** A column declared exactly TEXT or INTEGER, refined by its name (Rails' conventions). */
400
+ function refinedByName(column, type, where) {
401
+ if (type === "string" && column.name.endsWith("_at")) return { type: "datetime" };
402
+ const prefix = /^(is|has)_/.exec(column.name)?.[1];
403
+ if (type === "integer" && prefix !== void 0 && !column.primaryKey) return {
404
+ type: "boolean",
405
+ note: `${where}: INTEGER read as boolean, from its ${prefix}_ name`
406
+ };
407
+ return { type };
408
+ }
409
+ /** A quoted SQL string literal's text: `'it''s'` → `it's`; undefined if it isn't one. */
410
+ function quoted(value) {
411
+ return /^'(?:[^']|'')*'$/.test(value) ? value.slice(1, -1).replaceAll("''", "'") : void 0;
412
+ }
413
+ function booleanDefault(value) {
414
+ if (/^(TRUE|1)$/i.test(value)) return { literal: true };
415
+ return /^(FALSE|0)$/i.test(value) ? { literal: false } : void 0;
416
+ }
417
+ /** A number, when JavaScript holds it exactly; larger integers are left to D1. */
418
+ function numberDefault(value, type) {
419
+ if (type === "integer" && /^(TRUE|FALSE)$/i.test(value)) return { literal: /^TRUE$/i.test(value) ? 1 : 0 };
420
+ if (!/^-?\d+(\.\d+)?$/.test(value)) return void 0;
421
+ const number = Number(value);
422
+ return type === "integer" && !Number.isSafeInteger(number) ? void 0 : { literal: number };
423
+ }
424
+ /** A quoted default for a json column (its JSON) or a datetime column (its date). */
425
+ function textDefault(text, type) {
426
+ if (type === "string") return { literal: text };
427
+ if (type === "datetime") return Number.isNaN(Date.parse(text)) ? void 0 : { date: text };
428
+ try {
429
+ return { literal: JSON.parse(text) };
430
+ } catch {
431
+ return;
432
+ }
433
+ }
434
+ /** A SQL literal default as a value of the attribute's type; undefined for anything else. */
435
+ function literalDefault(sql, type) {
436
+ if (sql === null) return void 0;
437
+ const value = sql.trim();
438
+ if (type === "boolean") return booleanDefault(value);
439
+ if (type === "integer" || type === "real") return numberDefault(value, type);
440
+ const text = quoted(value);
441
+ return text === void 0 ? void 0 : textDefault(text, type);
442
+ }
443
+ /** A default that SQLite writes as date text with a space (`2026-10-12 06:38:30`), not ISO. */
444
+ const dateTextDefault = /^\(?\s*(current_timestamp|datetime\s*\(\s*'now'[^)]*\))\s*\)?$/i;
445
+ /** Whether a datetime column's default writes SQLite's date text, which sorts apart from ISO (#143). */
446
+ function hasDateTextDefault(column, type) {
447
+ return type === "datetime" && dateTextDefault.test(column.defaultValue?.trim() ?? "");
448
+ }
449
+ /** A column's spec: nullability, a mapped column name, and its default or generated key. */
450
+ function specOf(column, type, attribute) {
451
+ const spec = { type };
452
+ if (column.notNull || column.primaryKey) spec.null = false;
453
+ if (underscore(attribute) !== column.name) spec.column = column.name;
454
+ const defaultValue = literalDefault(column.defaultValue, type);
455
+ if (defaultValue !== void 0) spec.default = defaultValue;
456
+ else if (column.primaryKey && type === "string") spec.generateId = true;
457
+ return spec;
458
+ }
459
+ /** A column as an attribute, by the conventions (#66): name, type, nullability and default. */
460
+ function convert(column) {
461
+ const { type, error, note: typeNote } = typeOf(column);
462
+ if (type === void 0) return {
463
+ ok: false,
464
+ error
465
+ };
466
+ const note = typeNote ?? epochDefaultNote(column, type);
467
+ const attribute = attributeName(column.name);
468
+ return {
469
+ ok: true,
470
+ attribute,
471
+ spec: specOf(column, type, attribute),
472
+ ...note !== void 0 && { note },
473
+ ...hasDateTextDefault(column, type) && { textDate: true }
474
+ };
475
+ }
476
+ //#endregion
477
+ //#region cli/adapters/d1/schema.ts
478
+ /** Each table's definition (`CREATE TABLE …`), by name. */
479
+ function definitions(db) {
480
+ const rows = db.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'table'").all();
481
+ return new Map(rows.map((row) => [String(row.name), String(row.sql)]));
482
+ }
483
+ /**
484
+ * Applies the migrations in order to an in-memory SQLite database, noting which one last
485
+ * changed each table. A migration that fails is reported by its file name.
486
+ */
487
+ function applied(migrations) {
488
+ const changedBy = /* @__PURE__ */ new Map();
489
+ const { DatabaseSync: Database } = process.getBuiltinModule("node:sqlite");
490
+ const db = new Database(":memory:");
491
+ let before = definitions(db);
492
+ for (const { name, sql } of migrations) {
493
+ try {
494
+ db.exec(sql);
495
+ } catch (error) {
496
+ return {
497
+ changedBy,
498
+ error: `${name}: ${error.message}`
499
+ };
500
+ }
501
+ const after = definitions(db);
502
+ for (const [table, definition] of after) if (before.get(table) !== definition) changedBy.set(table, name);
503
+ before = after;
504
+ }
505
+ return {
506
+ db,
507
+ changedBy
508
+ };
509
+ }
510
+ /**
511
+ * The tables a Model can be built on: not SQLite's, Cloudflare's or Wrangler's own, and not a
512
+ * virtual table (full-text search, say) or the shadow tables SQLite keeps for one.
513
+ */
514
+ function ownTables(all, migrationsTable) {
515
+ const virtual = [...all].filter(([, sql]) => /^CREATE\s+VIRTUAL\s+TABLE/i.test(sql)).map(([name]) => name);
516
+ const shadow = (name) => virtual.some((table) => name === table || name.startsWith(`${table}_`));
517
+ const internal = (name) => name.startsWith("sqlite_") || name.startsWith("_cf_") || name === migrationsTable;
518
+ return [...all].filter(([name]) => !internal(name) && !shadow(name));
519
+ }
520
+ /** The columns `json_valid` checks in a table's definition: `CHECK (json_valid(settings))`. */
521
+ function jsonChecked(definition) {
522
+ return new Set([...definition.matchAll(/json_valid\(\s*(?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|(\w+))\s*\)/gi)].map((match) => match.slice(1).find(Boolean)));
523
+ }
524
+ /** The declared type of each column a foreign key references, by the referencing column. */
525
+ function referencedTypes(db, table) {
526
+ const keys = db.prepare("SELECT \"from\", \"table\", \"to\" FROM pragma_foreign_key_list(?)").all(table);
527
+ const types = /* @__PURE__ */ new Map();
528
+ for (const key of keys) {
529
+ const target = db.prepare("SELECT name, type, pk FROM pragma_table_info(?)").all(String(key.table)).find((column) => key.to === null ? Number(column.pk) > 0 : column.name === key.to);
530
+ if (target !== void 0) types.set(String(key.from), String(target.type));
531
+ }
532
+ return types;
533
+ }
534
+ /** A table's columns, as the conventions read them. */
535
+ function columnsOf(db, table, definition) {
536
+ const json = jsonChecked(definition);
537
+ const referenced = referencedTypes(db, table);
538
+ return db.prepare("SELECT name, type, \"notnull\", dflt_value, pk FROM pragma_table_info(?)").all(table).map((row) => ({
539
+ table,
540
+ name: String(row.name),
541
+ declaredType: String(row.type),
542
+ notNull: row.notnull === 1,
543
+ defaultValue: row.dflt_value === null ? null : String(row.dflt_value),
544
+ primaryKey: Number(row.pk) > 0,
545
+ jsonChecked: json.has(String(row.name)),
546
+ referencedType: referenced.get(String(row.name))
547
+ }));
548
+ }
549
+ /** The error for a table without a primary key, saying what D1 takes. */
550
+ const missingKey = (name) => `${name}: no primary key; Active Record needs one (id INTEGER PRIMARY KEY, or id TEXT PRIMARY KEY)`;
551
+ /**
552
+ * The tables a project's migrations make, by active-record's conventions (#66): applied in order to
553
+ * an in-memory SQLite database (`node:sqlite`), then read column by column. Tables are in
554
+ * alphabetical order and columns in the table's order, so the result only changes with the
555
+ * schema. SQLite's, Cloudflare's and Wrangler's own tables, and views, are left out.
556
+ */
557
+ function schemaOf(migrations, options = {}) {
558
+ const { db, changedBy, error } = applied(migrations);
559
+ if (db === void 0) return {
560
+ ok: false,
561
+ errors: [error]
562
+ };
563
+ const migrationsTable = options.migrationsTable ?? "d1_migrations";
564
+ const tables = ownTables(definitions(db), migrationsTable).map(([name, definition]) => ({
565
+ name,
566
+ columns: columnsOf(db, name, definition),
567
+ lastChangedBy: changedBy.get(name)
568
+ }));
569
+ db.close();
570
+ return generatedSchema(tables, {
571
+ convert,
572
+ missingKey
573
+ });
574
+ }
575
+ //#endregion
576
+ //#region cli/adapters/d1/plugin.ts
577
+ /**
578
+ * Why this Node can't read D1 migrations: no node:sqlite, unflagged from 22.13 and 23.4.
579
+ * `getBuiltinModule` itself is there: the command checks for it before it loads a plugin.
580
+ */
581
+ function unsupported() {
582
+ if (process.getBuiltinModule("node:sqlite") !== void 0) return void 0;
583
+ return `The D1 adapter needs Node 22.13 or later (23.4 on Node 23), for node:sqlite (this is Node ${process.versions.node})`;
584
+ }
585
+ /** D1, as the command line sees it: Wrangler's config and migrations, SQLite's schema, and its bindings. */
586
+ const cli = {
587
+ name: "d1",
588
+ patternSetting: "migrations_pattern",
589
+ unsupported,
590
+ init,
591
+ databases: readWranglerConfig,
592
+ readSchema: async (migrations, options) => schemaOf(migrations, options),
593
+ migration,
594
+ remote: (chosen, use) => remoteTarget(chosen, use),
595
+ stateFolder: ({ configFile }) => join(dirname(configFile), ".wrangler"),
596
+ open: (cwd, chosen, { remote }) => remote ? openRemoteBinding(cwd, chosen) : openLocalBinding(cwd, chosen),
597
+ migrate
598
+ };
599
+ //#endregion
600
+ export { cli };