@forestfuture/active-record 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/config-schema.json +6 -2
  2. package/dist/adapter.d.mts +3 -3
  3. package/dist/adapter.mjs +5 -4
  4. package/dist/batch-Ms5p9lKq.mjs +9777 -0
  5. package/dist/cli.d.mts +55 -33
  6. package/dist/cli.mjs +4 -4
  7. package/dist/command.mjs +530 -271
  8. package/dist/d1.d.mts +2 -10
  9. package/dist/d1.mjs +0 -0
  10. package/dist/{for-adapters-t3-LukJQ.d.mts → for-adapters-BT2GDjIA.d.mts} +8 -6
  11. package/dist/{for-adapters-Ch6CoHD4.mjs → for-adapters-BbIMUNcz.mjs} +46 -10
  12. package/dist/{for-adapters-D_Iu0gS_.mjs → for-adapters-C-MQxaIx.mjs} +3 -5
  13. package/dist/{generated-model-Cnt0Ot9q.mjs → generated-model-DJA8vmNE.mjs} +705 -508
  14. package/dist/identifiers-Dh5DFACX.mjs +989 -0
  15. package/dist/index-D5getfHx.d.mts +242 -0
  16. package/dist/index.d.mts +4 -3
  17. package/dist/index.mjs +5 -4
  18. package/dist/metadata-CzntpYzC.d.mts +182 -0
  19. package/dist/{plugin-Cyoej7qV.mjs → plugin-CZPDqguF.mjs} +211 -112
  20. package/dist/{plugin-XOHYndhP.mjs → plugin-Cf-5Z0_h.mjs} +148 -52
  21. package/dist/postgresql.d.mts +1 -9
  22. package/dist/postgresql.mjs +42 -26
  23. package/dist/src-BAVZKQ7J.mjs +46 -0
  24. package/dist/{storage-override-CpbkdIqE.mjs → storage-override-0ZgeP2sc.mjs} +61 -28
  25. package/dist/validations-BSZ5gVeI.d.mts +2024 -0
  26. package/llms-full.txt +2326 -229
  27. package/package.json +1 -1
  28. package/skills/active-record/SKILL.md +24 -15
  29. package/dist/adapter-AGKp6wfO.d.mts +0 -1326
  30. package/dist/batch-BS_WseLf.mjs +0 -4255
  31. package/dist/epoch-storage-o2aoOH7H.mjs +0 -112
  32. package/dist/index-CyCJuM96.d.mts +0 -149
  33. package/dist/src-la_KkjCS.mjs +0 -1
@@ -1,14 +1,14 @@
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";
1
+ import { i as attributeName, n as castDefault, s as listed, t as storageOverride, u as parseJsonc } from "./storage-override-0ZgeP2sc.mjs";
2
+ import { a as migrationSql, i as withDigits, n as namesInList, o as quotedName, r as withGeneratedEnum, s as indexName, t as generatedSchema } from "./for-adapters-BbIMUNcz.mjs";
3
+ import { E as underscore } from "./identifiers-Dh5DFACX.mjs";
4
4
  import { createRequire } from "node:module";
5
- import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
- import { basename, dirname, join } from "node:path";
5
+ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
7
7
  import { createJiti } from "jiti";
8
8
  import { tmpdir } from "node:os";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { spawn } from "node:child_process";
11
- //#region cli/adapters/d1/remote.ts
11
+ // cli/adapters/d1/remote.ts
12
12
  const text = (value) => typeof value === "string" && value !== "" ? value : void 0;
13
13
  /**
14
14
  * The remote database this binding's entry points at, or why there's none: for the console,
@@ -29,8 +29,8 @@ function remoteTarget({ binding, entry, configFile }, use = "open") {
29
29
  note: "That is the config's preview_database_id, which Wrangler opens in place of database_id."
30
30
  };
31
31
  }
32
- //#endregion
33
- //#region cli/adapters/d1/wrangler.ts
32
+ // cli/adapters/d1/wrangler.ts
33
+ /** The names a Wrangler config has, in the order Wrangler looks for them. */
34
34
  const candidates = [
35
35
  "wrangler.jsonc",
36
36
  "wrangler.json",
@@ -99,59 +99,25 @@ function d1Entries(file) {
99
99
  if (entries.some((entry) => typeof entry.binding !== "string")) return `${basename(file)} has a d1_databases entry with no binding`;
100
100
  return entries;
101
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
102
  /** The account a Wrangler config names (`account_id`), if it names one and can be read. */
148
103
  function accountIdIn(configFile) {
149
104
  const config = parsed(configFile);
150
105
  if (typeof config === "string") return void 0;
151
106
  return typeof config.account_id === "string" ? config.account_id : void 0;
152
107
  }
153
- //#endregion
154
- //#region cli/adapters/d1/binding.ts
108
+ // cli/adapters/d1/installed-wrangler.ts
109
+ /**
110
+ * `specifier` (`wrangler`, or a file of its package) as it resolves from the folder of the
111
+ * database's Wrangler config, or else from `cwd`; undefined when it resolves from neither.
112
+ */
113
+ function resolveWrangler(cwd, configFile, specifier) {
114
+ for (const from of [dirname(configFile), cwd]) try {
115
+ return createJiti(`${from}/`).esmResolve(specifier);
116
+ } catch {
117
+ continue;
118
+ }
119
+ }
120
+ // cli/adapters/d1/binding.ts
155
121
  /**
156
122
  * A Wrangler config holding only this D1 binding, in a folder of its own. `getPlatformProxy`
157
123
  * starts every binding a config declares, so the project's own config would bring its Durable
@@ -175,14 +141,10 @@ function d1OnlyConfig(entry, accountId) {
175
141
  })
176
142
  };
177
143
  }
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
- }
144
+ /** The project's own wrangler, loaded (the Worker's, beside its config, first); or why it can't be. */
145
+ async function projectWrangler(cwd, configFile) {
146
+ const file = resolveWrangler(cwd, configFile, "wrangler");
147
+ if (file === void 0) return "wrangler isn't installed here (install it, then run active-record console again)";
186
148
  try {
187
149
  return createRequire(import.meta.url)(fileURLToPath(file));
188
150
  } catch (error) {
@@ -190,7 +152,7 @@ async function projectWrangler(cwd) {
190
152
  }
191
153
  }
192
154
  async function open(cwd, { binding, configFile }, opening) {
193
- const wrangler = await projectWrangler(cwd);
155
+ const wrangler = await projectWrangler(cwd, configFile);
194
156
  if (typeof wrangler === "string") return wrangler;
195
157
  const config = d1OnlyConfig(opening.entry, accountIdIn(configFile));
196
158
  let proxy;
@@ -253,8 +215,89 @@ function openRemoteBinding(cwd, chosen) {
253
215
  failure: (binding, reason) => `Wrangler couldn't open ${binding} remotely: ${reason}\n${signInHint}`
254
216
  });
255
217
  }
256
- //#endregion
257
- //#region cli/adapters/d1/init.ts
218
+ // cli/adapters/d1/databases.ts
219
+ /**
220
+ * A path as a message names it: relative to `active-record.jsonc`'s folder, with forward slashes,
221
+ * and that folder itself as `.`.
222
+ */
223
+ function shown(project, path) {
224
+ return relative(project.dir, path).split(sep).join("/") || ".";
225
+ }
226
+ /** The Wrangler config a database's entry names with `wranglerConfig`, or why it can't be read. */
227
+ function namedConfig(binding, named, project) {
228
+ const setting = `${basename(project.file)}: databases.${binding}.wranglerConfig`;
229
+ if (typeof named !== "string") return { error: `${setting} isn't a string` };
230
+ const file = resolve(project.dir, named);
231
+ const settingNames = `${setting} names ${shown(project, file)}`;
232
+ const stat = statSync(file, { throwIfNoEntry: false });
233
+ if (stat === void 0) return { error: `${settingNames}, which isn't there` };
234
+ if (stat.isDirectory()) return { error: `${settingNames}, which is a folder; name its ${listed(candidates)}` };
235
+ return { file };
236
+ }
237
+ /**
238
+ * A database's Wrangler config: the one its entry names, or else `beside`, the one beside the file.
239
+ */
240
+ function configOf(binding, entry, project, beside) {
241
+ if (entry.wranglerConfig !== void 0) return namedConfig(binding, entry.wranglerConfig, project);
242
+ if (beside !== void 0) return { file: beside };
243
+ return { error: `No ${listed(candidates)} beside ${basename(project.file)}` };
244
+ }
245
+ /**
246
+ * A note for the D1 databases a Wrangler config has that `active-record.jsonc` doesn't name, which
247
+ * the command leaves out, so one added to Wrangler's config alone isn't missed in silence (#301).
248
+ * `init` adds those in the config beside the file; one elsewhere is added by hand (#306).
249
+ */
250
+ function unnamed(entries, project, file, beside) {
251
+ const left = entries.map((entry) => String(entry.binding)).filter((binding) => !Object.hasOwn(project.databases, binding));
252
+ if (left.length === 0) return [];
253
+ const one = left.length === 1;
254
+ const which = `the D1 database${one ? "" : "s"} ${listed(left, "and")}`;
255
+ const path = shown(project, file);
256
+ const add = file === beside ? `run \`npx active-record init\` to add ${one ? "it" : "them"}` : `add ${one ? "it" : "each"} with "wranglerConfig": ${JSON.stringify(path)}`;
257
+ return [`${path} has ${which}, which ${basename(project.file)} doesn't name; ${add}`];
258
+ }
259
+ /**
260
+ * The D1 databases a project's `active-record.jsonc` names, each as its Wrangler config declares
261
+ * it: the config its entry's `wranglerConfig` names, relative to the file, or else `wrangler.jsonc`,
262
+ * `wrangler.json` or `wrangler.toml` beside the file. Wrangler's other D1 databases are left out.
263
+ */
264
+ function readDatabases(project) {
265
+ const name = basename(project.file);
266
+ const beside = wranglerConfigIn(project.dir);
267
+ const entriesByConfig = /* @__PURE__ */ new Map();
268
+ const databases = [];
269
+ for (const [binding, settings] of Object.entries(project.databases)) {
270
+ const found = configOf(binding, settings, project, beside);
271
+ if ("error" in found) return {
272
+ ok: false,
273
+ error: found.error
274
+ };
275
+ const entries = entriesByConfig.get(found.file) ?? d1Entries(found.file);
276
+ if (typeof entries === "string") return {
277
+ ok: false,
278
+ error: entries
279
+ };
280
+ entriesByConfig.set(found.file, entries);
281
+ const entry = entries.find((each) => each.binding === binding);
282
+ if (entry === void 0) return {
283
+ ok: false,
284
+ error: `${name} names ${binding}, which isn't in ${shown(project, found.file)}'s d1_databases`
285
+ };
286
+ databases.push({
287
+ ...databaseOf(entry),
288
+ configFile: found.file
289
+ });
290
+ }
291
+ const notes = [...entriesByConfig].flatMap(([file, entries]) => unnamed(entries, project, file, beside));
292
+ return {
293
+ ok: true,
294
+ file: project.file,
295
+ dir: project.dir,
296
+ databases,
297
+ notes
298
+ };
299
+ }
300
+ // cli/adapters/d1/init.ts
258
301
  /**
259
302
  * The D1 databases in the Wrangler config in `dir`, each as an entry with nothing but its
260
303
  * adapter: Wrangler's config keeps the rest. Undefined when there are none, unless `--adapter` named D1.
@@ -270,23 +313,19 @@ function init(dir, named) {
270
313
  if (entries.length === 0) return named ? `${basename(file)} has no d1_databases: declare your database there first` : void 0;
271
314
  return { databases: Object.fromEntries(entries.map((entry) => [String(entry.binding), {}])) };
272
315
  }
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
- }
316
+ // cli/adapters/d1/migrate.ts
317
+ /** The project's own Wrangler's command line script (the Worker's, beside its config, first), or why there's none. */
318
+ function wranglerBin(cwd, configFile) {
319
+ const manifest = resolveWrangler(cwd, configFile, "wrangler/package.json");
320
+ if (manifest === void 0) return ["wrangler isn't installed here (install it, then run active-record migrate again)"];
321
+ return join(dirname(fileURLToPath(manifest)), "bin", "wrangler.js");
283
322
  }
284
323
  /**
285
324
  * Runs `wrangler d1 migrations apply <binding>`, `--local` or `--remote`, with the project's
286
325
  * config, as a person would. What Wrangler prints goes to `io`; it resolves to Wrangler's exit code.
287
326
  */
288
327
  function migrate(cwd, { binding, configFile }, { remote }, io) {
289
- const bin = wranglerBin(cwd);
328
+ const bin = wranglerBin(cwd, configFile);
290
329
  if (Array.isArray(bin)) {
291
330
  io.output(`${bin[0]}\n`);
292
331
  return Promise.resolve(1);
@@ -323,8 +362,7 @@ function migrate(cwd, { binding, configFile }, { remote }, io) {
323
362
  child.on("close", (code) => resolve(code ?? 1));
324
363
  });
325
364
  }
326
- //#endregion
327
- //#region cli/adapters/d1/migration.ts
365
+ // cli/adapters/d1/migration.ts
328
366
  /** SQLite's SQL for a generated migration. */
329
367
  const sqlite = {
330
368
  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(" ")),
@@ -332,9 +370,13 @@ const sqlite = {
332
370
  string: "TEXT",
333
371
  integer: "INTEGER",
334
372
  real: "REAL",
373
+ decimal: "DECIMAL",
335
374
  boolean: "BOOLEAN",
336
375
  datetime: "DATETIME",
337
- json: "TEXT"
376
+ date: "DATE",
377
+ time: "TIME",
378
+ json: "TEXT",
379
+ binary: "BLOB"
338
380
  },
339
381
  key: (integerId) => integerId ? "id INTEGER PRIMARY KEY" : "id TEXT PRIMARY KEY NOT NULL",
340
382
  timestampType: "DATETIME",
@@ -347,24 +389,69 @@ const sqlite = {
347
389
  function migration(change) {
348
390
  return migrationSql(change, sqlite);
349
391
  }
350
- //#endregion
351
- //#region cli/adapters/d1/conventions.ts
392
+ // cli/adapters/d1/checks.ts
393
+ /**
394
+ * A column name as SQLite takes it: bare, or quoted with "", ``, or [], on one line and at most
395
+ * 128 characters, so an unclosed quote can't make a search scan the rest of the text each time.
396
+ */
397
+ const columnName = String.raw`(?:"[^"\n]{1,128}"|\x60[^\x60\n]{1,128}\x60|\[[^\]\n]{1,128}\]|\w+)`;
398
+ /** A list of SQL string literals: `'draft', 'it''s'`. */
399
+ const stringList = String.raw`'(?:[^']|'')*'(?:\s*,\s*'(?:[^']|'')*')*`;
400
+ /**
401
+ * `CHECK (status IN ('draft', 'published'))`, or with `status IS NULL OR` before it or
402
+ * `OR status IS NULL` after it: the columns named, and the list.
403
+ */
404
+ const inCheck = new RegExp(String.raw`CHECK\s*\(\s*(?:(${columnName})\s+IS\s+NULL\s+OR\s+)?(${columnName})\s+IN\s*\(\s*(${stringList})\s*\)(?:\s+OR\s+(${columnName})\s+IS\s+NULL)?\s*\)`, "gi");
405
+ /**
406
+ * A string literal or a name quoted any of SQLite's ways, kept, or a comment, dropped: whichever
407
+ * starts first, so a `'` or `--` inside a name doesn't start or hide anything. An unclosed `[`,
408
+ * like an unclosed block comment, runs to the end, so a run of them isn't rescanned from each.
409
+ */
410
+ const literalOrComment = /'(?:[^']|'')*'|"(?:[^"]|"")*"|`(?:[^`]|``)*`|\[[^\]]*\]?|--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/g;
411
+ /** A definition without its comments, which SQLite keeps in it: `a TEXT -- CHECK (…)` → `a TEXT `. */
412
+ function withoutComments(definition) {
413
+ return definition.replace(literalOrComment, (token) => token.startsWith("--") || token.startsWith("/*") ? " " : token);
414
+ }
415
+ /** A column name as a key, as SQLite compares them: unquoted, any case. `"Status"` → `status`. */
416
+ function columnKey(name) {
417
+ return (/^["`[]/.test(name) ? name.slice(1, -1) : name).toLowerCase();
418
+ }
419
+ /** The column a match restricts, unless its `IS NULL` names another one. */
420
+ function restricted(match) {
421
+ const column = columnKey(match[2]);
422
+ return [match[1], match[4]].filter((name) => name !== void 0).map(columnKey).every((name) => name === column) ? column : void 0;
423
+ }
424
+ /**
425
+ * Each column a table's definition restricts to a list of strings, with the list, by its name in
426
+ * lower case. A column two lists restrict isn't one: which list holds isn't the schema's to say.
427
+ */
428
+ function checkedNames(definition) {
429
+ const lists = /* @__PURE__ */ new Map();
430
+ for (const match of withoutComments(definition).matchAll(inCheck)) {
431
+ const column = restricted(match);
432
+ if (column === void 0) continue;
433
+ lists.set(column, lists.has(column) ? void 0 : namesInList(match[3]));
434
+ }
435
+ return new Map([...lists].filter((entry) => entry[1] !== void 0));
436
+ }
437
+ // cli/adapters/d1/conventions.ts
352
438
  const declaredTypes = [
353
439
  [/^BOOL/, "boolean"],
354
- [/^(DATETIME|TIMESTAMP|DATE)$/, "datetime"],
440
+ [/^(DATETIME|TIMESTAMP)$/, "datetime"],
441
+ [/^DATE$/, "date"],
442
+ [/^TIME$/, "time"],
443
+ [/^(NUMERIC|DECIMAL)$/, "decimal"],
355
444
  [/^JSON$/, "json"],
445
+ [/^BLOB$/, "binary"],
356
446
  [/INT/, "integer"],
357
447
  [/CHAR|CLOB|TEXT/, "string"],
358
448
  [/REAL|FLOA|DOUB/, "real"]
359
449
  ];
360
450
  /** The declared type's name, without its size or precision: `VARCHAR(40)` → `VARCHAR`. */
361
451
  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;
452
+ const open = declared.indexOf("(");
453
+ const close = declared.lastIndexOf(")");
454
+ return (open !== -1 && close > open ? declared.slice(0, open) + declared.slice(close + 1) : declared).toUpperCase().trim();
368
455
  }
369
456
  /** A default that's a number or an epoch function, which a datetime in ISO text wouldn't hold. */
370
457
  const epochDefault = /^\(?\s*-?\d+(\.\d+)?\s*\)?$|unixepoch|strftime\s*\(\s*'%s'/i;
@@ -376,11 +463,7 @@ function epochDefaultNote(column, type) {
376
463
  }
377
464
  /** A column's attribute type: its declared type first, then its name for plain TEXT/INTEGER. */
378
465
  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);
466
+ return typeOfDeclared(column, baseType(column.declaredType || (column.referencedType ?? "")), `${column.table}.${column.name}`);
384
467
  }
385
468
  /** The attribute type for a supported declared type; a guess (`string`) comes with a note (#159). */
386
469
  function typeOfDeclared(column, declared, where) {
@@ -421,9 +504,13 @@ function numberDefault(value, type) {
421
504
  const number = Number(value);
422
505
  return type === "integer" && !Number.isSafeInteger(number) ? void 0 : { literal: number };
423
506
  }
424
- /** A quoted default for a json column (its JSON) or a datetime column (its date). */
507
+ /**
508
+ * A quoted default's text as the attribute's: a string's as it is, a date's or a time's in its
509
+ * one form (#391), a datetime's as its date, and a json column's as its JSON.
510
+ */
425
511
  function textDefault(text, type) {
426
512
  if (type === "string") return { literal: text };
513
+ if (type === "date" || type === "time") return castDefault(type, text);
427
514
  if (type === "datetime") return Number.isNaN(Date.parse(text)) ? void 0 : { date: text };
428
515
  try {
429
516
  return { literal: JSON.parse(text) };
@@ -432,11 +519,15 @@ function textDefault(text, type) {
432
519
  }
433
520
  }
434
521
  /** 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;
522
+ function literalDefault(sql, { type, precision, scale }) {
523
+ if (sql === null || type === "binary") return void 0;
437
524
  const value = sql.trim();
438
525
  if (type === "boolean") return booleanDefault(value);
439
526
  if (type === "integer" || type === "real") return numberDefault(value, type);
527
+ if (type === "decimal") return castDefault(type, quoted(value) ?? value, {
528
+ precision,
529
+ scale
530
+ });
440
531
  const text = quoted(value);
441
532
  return text === void 0 ? void 0 : textDefault(text, type);
442
533
  }
@@ -448,21 +539,30 @@ function hasDateTextDefault(column, type) {
448
539
  }
449
540
  /** A column's spec: nullability, a mapped column name, and its default or generated key. */
450
541
  function specOf(column, type, attribute) {
451
- const spec = { type };
542
+ const spec = withSizeDigits({ type }, column.declaredType);
452
543
  if (column.notNull || column.primaryKey) spec.null = false;
453
544
  if (underscore(attribute) !== column.name) spec.column = column.name;
454
- const defaultValue = literalDefault(column.defaultValue, type);
545
+ const defaultValue = literalDefault(column.defaultValue, spec);
455
546
  if (defaultValue !== void 0) spec.default = defaultValue;
456
547
  else if (column.primaryKey && type === "string") spec.generateId = true;
457
- return spec;
548
+ return withGeneratedEnum(spec, column.restrictedTo);
549
+ }
550
+ /**
551
+ * A decimal's precision and scale from its declared type's size: `DECIMAL(10, 2)` gives 10 and
552
+ * 2, `NUMERIC(6)` a precision of 6 (#398). A size that isn't whole numbers gives neither.
553
+ */
554
+ function withSizeDigits(spec, declared) {
555
+ const open = declared.indexOf("(");
556
+ const close = declared.indexOf(")", open);
557
+ if (open === -1 || close === -1) return spec;
558
+ const digits = declared.slice(open + 1, close).split(",").map((part) => part.trim());
559
+ if (digits.length > 2 || !digits.every((part) => /^\d+$/.test(part))) return spec;
560
+ const [precision, scale] = digits.map(Number);
561
+ return withDigits(spec, precision, scale);
458
562
  }
459
563
  /** A column as an attribute, by the conventions (#66): name, type, nullability and default. */
460
564
  function convert(column) {
461
- const { type, error, note: typeNote } = typeOf(column);
462
- if (type === void 0) return {
463
- ok: false,
464
- error
465
- };
565
+ const { type, note: typeNote } = typeOf(column);
466
566
  const note = typeNote ?? epochDefaultNote(column, type);
467
567
  const attribute = attributeName(column.name);
468
568
  return {
@@ -473,8 +573,7 @@ function convert(column) {
473
573
  ...hasDateTextDefault(column, type) && { textDate: true }
474
574
  };
475
575
  }
476
- //#endregion
477
- //#region cli/adapters/d1/schema.ts
576
+ // cli/adapters/d1/schema.ts
478
577
  /** Each table's definition (`CREATE TABLE …`), by name. */
479
578
  function definitions(db) {
480
579
  const rows = db.prepare("SELECT name, sql FROM sqlite_master WHERE type = 'table'").all();
@@ -534,6 +633,7 @@ function referencedTypes(db, table) {
534
633
  /** A table's columns, as the conventions read them. */
535
634
  function columnsOf(db, table, definition) {
536
635
  const json = jsonChecked(definition);
636
+ const lists = checkedNames(definition);
537
637
  const referenced = referencedTypes(db, table);
538
638
  return db.prepare("SELECT name, type, \"notnull\", dflt_value, pk FROM pragma_table_info(?)").all(table).map((row) => ({
539
639
  table,
@@ -543,7 +643,8 @@ function columnsOf(db, table, definition) {
543
643
  defaultValue: row.dflt_value === null ? null : String(row.dflt_value),
544
644
  primaryKey: Number(row.pk) > 0,
545
645
  jsonChecked: json.has(String(row.name)),
546
- referencedType: referenced.get(String(row.name))
646
+ referencedType: referenced.get(String(row.name)),
647
+ restrictedTo: lists.get(String(row.name).toLowerCase())
547
648
  }));
548
649
  }
549
650
  /** The error for a table without a primary key, saying what D1 takes. */
@@ -572,8 +673,7 @@ function schemaOf(migrations, options = {}) {
572
673
  missingKey
573
674
  });
574
675
  }
575
- //#endregion
576
- //#region cli/adapters/d1/plugin.ts
676
+ // cli/adapters/d1/plugin.ts
577
677
  /**
578
678
  * Why this Node can't read D1 migrations: no node:sqlite, unflagged from 22.13 and 23.4.
579
679
  * `getBuiltinModule` itself is there: the command checks for it before it loads a plugin.
@@ -588,7 +688,7 @@ const cli = {
588
688
  patternSetting: "migrations_pattern",
589
689
  unsupported,
590
690
  init,
591
- databases: readWranglerConfig,
691
+ databases: readDatabases,
592
692
  readSchema: async (migrations, options) => schemaOf(migrations, options),
593
693
  migration,
594
694
  remote: (chosen, use) => remoteTarget(chosen, use),
@@ -596,5 +696,4 @@ const cli = {
596
696
  open: (cwd, chosen, { remote }) => remote ? openRemoteBinding(cwd, chosen) : openLocalBinding(cwd, chosen),
597
697
  migrate
598
698
  };
599
- //#endregion
600
699
  export { cli };