@marktiderman/genesis-cli 1.14.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync, existsSync, readdirSync, mkdirSync, writeFileSync, mkdtempSync, rmSync, realpathSync, statSync, lstatSync } from 'fs';
3
- import * as path23 from 'path';
3
+ import * as path26 from 'path';
4
4
  import { FEATURE_PLATFORMS, defineBlock, BlockError } from '@marktiderman/genesis-features/blocks';
5
5
  import { createHash } from 'crypto';
6
6
  import { fileURLToPath, pathToFileURL } from 'url';
@@ -26,7 +26,7 @@ var __export = (target, all) => {
26
26
  function buildCatalog(packagesDir) {
27
27
  const packages = {};
28
28
  for (const dir of readdirSync(packagesDir).sort()) {
29
- const file = path23.join(packagesDir, dir, "package.json");
29
+ const file = path26.join(packagesDir, dir, "package.json");
30
30
  if (!existsSync(file)) continue;
31
31
  const pkg = JSON.parse(readFileSync(file, "utf8"));
32
32
  if (!pkg.name || !pkg.version || pkg.private || !pkg.name.startsWith("@marktiderman/genesis")) continue;
@@ -51,17 +51,17 @@ function parseManifest(home, id, raw, version, options = {}) {
51
51
  if (!GENESIS_PACKAGE.test(home) && !options.local) problems.push(`${home}: only Genesis packages (@marktiderman/genesis*) and the app's local packages declare blocks`);
52
52
  if (!BLOCK_ID.test(id)) problems.push(`${at}: "${id}" is not a feature id`);
53
53
  if (!isObject(raw)) throw new ManifestError([...problems, `${at}: must be an object`]);
54
- const pkgOf = (value, where) => {
54
+ const pkgOf = (value, where2) => {
55
55
  if (value === void 0) return home;
56
56
  if (typeof value !== "string" || !(GENESIS_PACKAGE.test(value) || options.local && value === home)) {
57
- problems.push(`${where}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
57
+ problems.push(`${where2}: package must be a Genesis package${options.local ? " or this local package" : ""}, not ${JSON.stringify(value)}`);
58
58
  return home;
59
59
  }
60
60
  return value;
61
61
  };
62
- const pathOf = (value, where) => {
62
+ const pathOf = (value, where2) => {
63
63
  const safe = safeRelative(value);
64
- if (!safe) problems.push(`${where}: ${JSON.stringify(value)} is not a plain path inside the package`);
64
+ if (!safe) problems.push(`${where2}: ${JSON.stringify(value)} is not a plain path inside the package`);
65
65
  return safe ?? "";
66
66
  };
67
67
  const list = (key2) => {
@@ -93,43 +93,43 @@ function parseManifest(home, id, raw, version, options = {}) {
93
93
  return ok;
94
94
  });
95
95
  const migrations = list("migrations").map((m, i) => {
96
- const where = `${at}.migrations[${i}]`;
96
+ const where2 = `${at}.migrations[${i}]`;
97
97
  if (!isObject(m)) {
98
- problems.push(`${where}: must be an object`);
98
+ problems.push(`${where2}: must be an object`);
99
99
  return { package: home, file: "" };
100
100
  }
101
- const file = pathOf(m["file"], `${where}.file`);
102
- if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
103
- const out = { package: pkgOf(m["package"], where), file };
101
+ const file = pathOf(m["file"], `${where2}.file`);
102
+ if (file && !MIGRATION_FILE.test(file.split("/").pop())) problems.push(`${where2}.file: "${file}" must be named NNNN_name.sql (lowercase letters, digits, _)`);
103
+ const out = { package: pkgOf(m["package"], where2), file };
104
104
  if (m["test"] !== void 0) {
105
- out.test = pathOf(m["test"], `${where}.test`);
106
- if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
105
+ out.test = pathOf(m["test"], `${where2}.test`);
106
+ if (out.test && !/^[a-z0-9_]+\.test\.sql$/.test(out.test.split("/").pop().replace(/^\d{4}_/, ""))) problems.push(`${where2}.test: "${out.test}" must be named [NNNN_]name.test.sql`);
107
107
  }
108
108
  return out;
109
109
  });
110
110
  const functions = list("functions").map((f, i) => {
111
- const where = `${at}.functions[${i}]`;
111
+ const where2 = `${at}.functions[${i}]`;
112
112
  if (!isObject(f)) {
113
- problems.push(`${where}: must be an object`);
113
+ problems.push(`${where2}: must be an object`);
114
114
  return { package: home, dir: "" };
115
115
  }
116
- const dir = pathOf(f["dir"], `${where}.dir`);
117
- if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
118
- const out = { package: pkgOf(f["package"], where), dir };
116
+ const dir = pathOf(f["dir"], `${where2}.dir`);
117
+ if (dir && !FUNCTION_NAME.test(dir.split("/").pop())) problems.push(`${where2}.dir: the folder's name "${dir.split("/").pop()}" is not a function name`);
118
+ const out = { package: pkgOf(f["package"], where2), dir };
119
119
  if (f["verifyJwt"] !== void 0) {
120
- if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where}.verifyJwt: must be true or false`);
120
+ if (typeof f["verifyJwt"] !== "boolean") problems.push(`${where2}.verifyJwt: must be true or false`);
121
121
  else out.verifyJwt = f["verifyJwt"];
122
122
  }
123
123
  if (f["secrets"] !== void 0) {
124
- if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where}.secrets: must be a list of UPPER_CASE names`);
124
+ if (!strings(f["secrets"]) || f["secrets"].some((s) => !SECRET.test(s))) problems.push(`${where2}.secrets: must be a list of UPPER_CASE names`);
125
125
  else out.secrets = f["secrets"];
126
126
  }
127
127
  return out;
128
128
  });
129
129
  const routes = list("routes").map((r, i) => {
130
- const where = `${at}.routes[${i}]`;
130
+ const where2 = `${at}.routes[${i}]`;
131
131
  if (!isObject(r) || typeof r["path"] !== "string" || !ROUTE.test(r["path"]) || r["path"].split("/").includes("..")) {
132
- problems.push(`${where}: needs a path like /settings/notifications`);
132
+ problems.push(`${where2}: needs a path like /settings/notifications`);
133
133
  return { path: "/" };
134
134
  }
135
135
  const out = { path: r["path"] };
@@ -234,14 +234,14 @@ ${problems.map((p) => ` - ${p}`).join("\n")}`);
234
234
  }
235
235
  });
236
236
  function inside(parent, child) {
237
- const rel = path23.relative(parent, child);
238
- return rel === "" || !rel.startsWith("..") && !path23.isAbsolute(rel);
237
+ const rel = path26.relative(parent, child);
238
+ return rel === "" || !rel.startsWith("..") && !path26.isAbsolute(rel);
239
239
  }
240
240
  function readPackageFile(packageDir2, rel) {
241
241
  const safe = safeRelative(rel);
242
242
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
243
243
  const root = realpathSync(packageDir2);
244
- const file = path23.join(root, ...safe.split("/"));
244
+ const file = path26.join(root, ...safe.split("/"));
245
245
  if (!existsSync(file)) return null;
246
246
  const real2 = realpathSync(file);
247
247
  if (!inside(root, real2)) throw new Error(`${rel} in ${packageDir2} points outside the package`);
@@ -252,7 +252,7 @@ function readPackageDir(packageDir2, rel, skipped = []) {
252
252
  const safe = safeRelative(rel);
253
253
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the package`);
254
254
  const root = realpathSync(packageDir2);
255
- const dir = path23.join(root, ...safe.split("/"));
255
+ const dir = path26.join(root, ...safe.split("/"));
256
256
  if (!existsSync(dir)) return null;
257
257
  const real2 = realpathSync(dir);
258
258
  if (!inside(root, real2) || !statSync(real2).isDirectory()) throw new Error(`${rel} in ${packageDir2} is not a folder inside the package`);
@@ -272,7 +272,7 @@ function appPath(root, rel) {
272
272
  if (!safe) throw new Error(`"${rel}" is not a plain path inside the app`);
273
273
  if (safe.split("/").some((s) => s.toLowerCase() === ".git")) throw new Error(`"${rel}" is inside .git; refused`);
274
274
  const realRoot = realpathSync(root);
275
- const target = path23.join(realRoot, ...safe.split("/"));
275
+ const target = path26.join(realRoot, ...safe.split("/"));
276
276
  const there = (p) => {
277
277
  try {
278
278
  lstatSync(p);
@@ -281,13 +281,13 @@ function appPath(root, rel) {
281
281
  return false;
282
282
  }
283
283
  };
284
- let probe = path23.dirname(target);
285
- while (!there(probe)) probe = path23.dirname(probe);
284
+ let probe = path26.dirname(target);
285
+ while (!there(probe)) probe = path26.dirname(probe);
286
286
  let real2;
287
287
  try {
288
288
  real2 = realpathSync(probe);
289
289
  } catch {
290
- throw new Error(`${rel} goes through a broken symlink (${path23.relative(realRoot, probe)}); refused`);
290
+ throw new Error(`${rel} goes through a broken symlink (${path26.relative(realRoot, probe)}); refused`);
291
291
  }
292
292
  if (!inside(realRoot, real2)) throw new Error(`${rel} is outside the app (a symlinked folder?)`);
293
293
  if (there(target) && lstatSync(target).isSymbolicLink()) throw new Error(`${rel} is a symlink; left alone`);
@@ -299,20 +299,20 @@ function readApp(root, rel) {
299
299
  }
300
300
  function createApp(root, rel, content) {
301
301
  const file = appPath(root, rel);
302
- mkdirSync(path23.dirname(file), { recursive: true });
302
+ mkdirSync(path26.dirname(file), { recursive: true });
303
303
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
304
304
  }
305
305
  function replaceApp(root, rel, content) {
306
306
  const file = appPath(root, rel);
307
- mkdirSync(path23.dirname(file), { recursive: true });
307
+ mkdirSync(path26.dirname(file), { recursive: true });
308
308
  writeFileSync(file, content, "utf8");
309
309
  }
310
310
  function listApp(root, rel, options = {}) {
311
- const dir = path23.join(root, rel);
311
+ const dir = path26.join(root, rel);
312
312
  if (!existsSync(dir)) return [];
313
313
  const out = [];
314
314
  const walk2 = (r) => {
315
- for (const entry of readdirSync(path23.join(root, r), { withFileTypes: true })) {
315
+ for (const entry of readdirSync(path26.join(root, r), { withFileTypes: true })) {
316
316
  const child = `${r}/${entry.name}`;
317
317
  if (entry.isDirectory()) walk2(child);
318
318
  else if (entry.isFile() || options.symlinks && entry.isSymbolicLink()) out.push(child);
@@ -331,21 +331,21 @@ var init_files = __esm({
331
331
  function validateLocalPackages(raw, source = "genesis.config.json") {
332
332
  if (!Array.isArray(raw)) throw new LocalPackagesError(`${source}: ${LOCAL_PACKAGES_KEY} must be a list of folders`);
333
333
  return raw.map((entry, i) => {
334
- const where = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
335
- if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where} must be a non-empty folder`);
336
- if (path23.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where} must be relative to the app ("${entry}")`);
337
- const norm = path23.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
338
- if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where} must name a package folder, not the app or a parent of it ("${entry}")`);
334
+ const where2 = `${source}: ${LOCAL_PACKAGES_KEY}[${i}]`;
335
+ if (typeof entry !== "string" || !entry.trim()) throw new LocalPackagesError(`${where2} must be a non-empty folder`);
336
+ if (path26.isAbsolute(entry) || /^[A-Za-z]:[\\/]/.test(entry)) throw new LocalPackagesError(`${where2} must be relative to the app ("${entry}")`);
337
+ const norm = path26.posix.normalize(entry.replace(/\\/g, "/")).replace(/\/+$/, "");
338
+ if (norm === "." || /^(\.\.\/)*\.\.$/.test(norm)) throw new LocalPackagesError(`${where2} must name a package folder, not the app or a parent of it ("${entry}")`);
339
339
  const parts = norm.split("/");
340
340
  if (parts.some((p, k) => p.includes("*") && (p !== "*" || k !== parts.length - 1))) {
341
- throw new LocalPackagesError(`${where}: only a final "/*" is supported ("${entry}")`);
341
+ throw new LocalPackagesError(`${where2}: only a final "/*" is supported ("${entry}")`);
342
342
  }
343
- if (parts.includes("node_modules")) throw new LocalPackagesError(`${where} can't point into node_modules ("${entry}")`);
343
+ if (parts.includes("node_modules")) throw new LocalPackagesError(`${where2} can't point into node_modules ("${entry}")`);
344
344
  return norm;
345
345
  });
346
346
  }
347
347
  function localPackageGlobs(root) {
348
- const file = path23.join(root, "genesis.config.json");
348
+ const file = path26.join(root, "genesis.config.json");
349
349
  if (!existsSync(file)) return [];
350
350
  let raw;
351
351
  try {
@@ -358,14 +358,14 @@ function localPackageGlobs(root) {
358
358
  }
359
359
  function repositoryRoot(appRoot) {
360
360
  for (let dir = appRoot; ; ) {
361
- if (existsSync(path23.join(dir, ".git"))) return dir;
362
- const parent = path23.dirname(dir);
361
+ if (existsSync(path26.join(dir, ".git"))) return dir;
362
+ const parent = path26.dirname(dir);
363
363
  if (parent === dir) return appRoot;
364
364
  dir = parent;
365
365
  }
366
366
  }
367
367
  function localPackages(root) {
368
- const appRoot = path23.resolve(root);
368
+ const appRoot = path26.resolve(root);
369
369
  const globs = localPackageGlobs(appRoot);
370
370
  const key2 = `${appRoot}
371
371
  ${globs.join("\n")}`;
@@ -374,24 +374,24 @@ ${globs.join("\n")}`;
374
374
  const dirs = /* @__PURE__ */ new Set();
375
375
  for (const glob of globs) {
376
376
  if (glob.endsWith("/*") || glob === "*") {
377
- const parent = path23.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
377
+ const parent = path26.join(appRoot, glob === "*" ? "" : glob.slice(0, -2));
378
378
  if (!existsSync(parent) || !statSync(parent).isDirectory()) continue;
379
379
  for (const entry of readdirSync(parent).sort()) {
380
380
  if (entry.startsWith(".") || entry === "node_modules") continue;
381
- dirs.add(path23.join(parent, entry));
381
+ dirs.add(path26.join(parent, entry));
382
382
  }
383
383
  } else {
384
- dirs.add(path23.join(appRoot, glob));
384
+ dirs.add(path26.join(appRoot, glob));
385
385
  }
386
386
  }
387
387
  const real2 = realpathSync(repositoryRoot(appRoot));
388
388
  const out = [];
389
389
  const byName = /* @__PURE__ */ new Map();
390
390
  for (const dir of [...dirs].sort()) {
391
- const manifest = path23.join(dir, "package.json");
391
+ const manifest = path26.join(dir, "package.json");
392
392
  if (!existsSync(manifest)) continue;
393
393
  if (!inside(real2, realpathSync(dir))) {
394
- throw new LocalPackagesError(`${path23.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
394
+ throw new LocalPackagesError(`${path26.relative(appRoot, dir) || dir} is outside the repository; localPackages may only list folders inside it`);
395
395
  }
396
396
  let pkg;
397
397
  try {
@@ -400,7 +400,7 @@ ${globs.join("\n")}`;
400
400
  continue;
401
401
  }
402
402
  if (typeof pkg.name !== "string" || !pkg.name) continue;
403
- const rel = path23.relative(appRoot, dir).split(path23.sep).join("/");
403
+ const rel = path26.relative(appRoot, dir).split(path26.sep).join("/");
404
404
  const other = byName.get(pkg.name);
405
405
  if (other) throw new LocalPackagesError(`${other} and ${rel} are both named ${pkg.name}`);
406
406
  byName.set(pkg.name, rel);
@@ -443,41 +443,41 @@ __export(discover_exports, {
443
443
  workspacePackagesDir: () => workspacePackagesDir
444
444
  });
445
445
  function cliPackageDir() {
446
- let dir = path23.dirname(fileURLToPath(import.meta.url));
446
+ let dir = path26.dirname(fileURLToPath(import.meta.url));
447
447
  for (; ; ) {
448
- const file = path23.join(dir, "package.json");
448
+ const file = path26.join(dir, "package.json");
449
449
  if (existsSync(file) && JSON.parse(readFileSync(file, "utf8")).name === CLI_PACKAGE) return dir;
450
- const parent = path23.dirname(dir);
450
+ const parent = path26.dirname(dir);
451
451
  if (parent === dir) throw new Error("Can't find the genesis-cli package folder.");
452
452
  dir = parent;
453
453
  }
454
454
  }
455
455
  function workspacePackagesDir() {
456
- const dir = path23.resolve(cliPackageDir(), "..");
457
- return existsSync(path23.join(dir, "features", "package.json")) && existsSync(path23.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
456
+ const dir = path26.resolve(cliPackageDir(), "..");
457
+ return existsSync(path26.join(dir, "features", "package.json")) && existsSync(path26.join(dir, "..", "pnpm-workspace.yaml")) ? dir : null;
458
458
  }
459
459
  function readCatalog() {
460
460
  if (catalogCache) return catalogCache;
461
461
  const workspace = workspacePackagesDir();
462
462
  if (workspace) return catalogCache = buildCatalog(workspace);
463
- const file = path23.join(cliPackageDir(), "dist", "genesis-catalog.json");
463
+ const file = path26.join(cliPackageDir(), "dist", "genesis-catalog.json");
464
464
  catalogCache = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : { packages: {} };
465
465
  return catalogCache;
466
466
  }
467
467
  function installedGenesis(root) {
468
468
  const found = /* @__PURE__ */ new Map();
469
- let dir = path23.resolve(root);
469
+ let dir = path26.resolve(root);
470
470
  for (; ; ) {
471
- const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path23.join(dir, m)));
472
- const scope = path23.join(dir, "node_modules", "@marktiderman");
471
+ const atInstallRoot = INSTALL_ROOT_MARKERS.some((m) => existsSync(path26.join(dir, m)));
472
+ const scope = path26.join(dir, "node_modules", "@marktiderman");
473
473
  if (existsSync(scope)) {
474
474
  for (const entry of readdirSync(scope)) {
475
475
  const name = `@marktiderman/${entry}`;
476
476
  if (!GENESIS_PACKAGE.test(name) || found.has(name)) continue;
477
- if (existsSync(path23.join(scope, entry, "package.json"))) found.set(name, path23.join(scope, entry));
477
+ if (existsSync(path26.join(scope, entry, "package.json"))) found.set(name, path26.join(scope, entry));
478
478
  }
479
479
  }
480
- const parent = path23.dirname(dir);
480
+ const parent = path26.dirname(dir);
481
481
  if (atInstallRoot || parent === dir) return found;
482
482
  dir = parent;
483
483
  }
@@ -491,10 +491,10 @@ function packageDir(root, name) {
491
491
  return null;
492
492
  }
493
493
  function packageVersion(dir) {
494
- return JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8")).version;
494
+ return JSON.parse(readFileSync(path26.join(dir, "package.json"), "utf8")).version;
495
495
  }
496
496
  function declarationsOf(dir, warnings) {
497
- const pkg = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
497
+ const pkg = JSON.parse(readFileSync(path26.join(dir, "package.json"), "utf8"));
498
498
  const key2 = `${realpathSync(dir)}@${pkg.version ?? ""}`;
499
499
  let cached = declarationCache.get(key2);
500
500
  if (!cached) {
@@ -504,15 +504,15 @@ function declarationsOf(dir, warnings) {
504
504
  return cached;
505
505
  }
506
506
  async function loadDeclarations(dir, warnings) {
507
- const pkg = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
507
+ const pkg = JSON.parse(readFileSync(path26.join(dir, "package.json"), "utf8"));
508
508
  const entry = pkg.exports?.["./blocks"];
509
509
  const target = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry["import"] ?? entry["default"] : void 0;
510
510
  if (typeof target !== "string") return {};
511
511
  const rel = safeRelative(target.replace(/^\.\//, ""));
512
- const file = rel && path23.join(dir, ...rel.split("/"));
512
+ const file = rel && path26.join(dir, ...rel.split("/"));
513
513
  if (!file || !inside(dir, file) || !existsSync(file)) return {};
514
514
  try {
515
- const jiti = createJiti(path23.join(dir, "package.json"), { moduleCache: false });
515
+ const jiti = createJiti(path26.join(dir, "package.json"), { moduleCache: false });
516
516
  const mod = await jiti.import(file);
517
517
  const out = {};
518
518
  for (const value of Object.values(mod)) if (isBlockDef(value)) out[value.id] = declarationFields(value);
@@ -523,7 +523,7 @@ async function loadDeclarations(dir, warnings) {
523
523
  }
524
524
  }
525
525
  async function blocksOfInstalled(dir, warnings = [], options = {}) {
526
- const pkg = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
526
+ const pkg = JSON.parse(readFileSync(path26.join(dir, "package.json"), "utf8"));
527
527
  const raw = rawBlocksOf(pkg);
528
528
  const declared = await declarationsOf(dir, warnings);
529
529
  const ids = /* @__PURE__ */ new Set([...Object.keys(raw), ...Object.keys(declared)]);
@@ -606,7 +606,7 @@ function emptyLock() {
606
606
  return { version: 1, blocks: {}, files: {} };
607
607
  }
608
608
  function readLock(root) {
609
- const file = path23.join(root, LOCK_FILE);
609
+ const file = path26.join(root, LOCK_FILE);
610
610
  if (!existsSync(file)) return emptyLock();
611
611
  const raw = JSON.parse(readFileSync(file, "utf8"));
612
612
  if (raw.version !== 1) throw new Error(`${LOCK_FILE} has version ${String(raw.version)}; this CLI reads version 1.`);
@@ -661,7 +661,7 @@ function migrationHeader(pkg, file, source) {
661
661
  `;
662
662
  }
663
663
  function stemOrNull(file) {
664
- return MIGRATION_FILE.exec(path23.posix.basename(file))?.[2] ?? null;
664
+ return MIGRATION_FILE.exec(path26.posix.basename(file))?.[2] ?? null;
665
665
  }
666
666
  function stemOf(file) {
667
667
  const stem = stemOrNull(file);
@@ -671,7 +671,7 @@ function stemOf(file) {
671
671
  function readAppMigrations(root, dir = MIGRATIONS_DIR) {
672
672
  return listApp(root, dir, { symlinks: true }).filter((p) => p.endsWith(".sql")).map((p) => {
673
673
  const content = readApp(root, p) ?? "";
674
- const name = path23.posix.basename(p);
674
+ const name = path26.posix.basename(p);
675
675
  const m = HEADER.exec(content);
676
676
  if (m) return { path: p, name, content, tracked: { package: m[1], file: m[2], sha256: m[3], body: content.slice(m[0].length) } };
677
677
  const f = FORWARD.exec(content);
@@ -753,7 +753,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
753
753
  detail = copy.tracked ? renamed.trim() : "copied before headers; matches the package";
754
754
  } else if (copy.tracked) {
755
755
  state = "changed-upstream";
756
- detail = `${src.package} now ships a different ${path23.posix.basename(src.file)}; the applied copy is never rewritten`;
756
+ detail = `${src.package} now ships a different ${path26.posix.basename(src.file)}; the applied copy is never rewritten`;
757
757
  } else {
758
758
  state = "differs";
759
759
  detail = "has the package migration's name but other text and no header; treated as the app's own";
@@ -775,7 +775,7 @@ function planMigrations(root, sources, options = { now: /* @__PURE__ */ new Date
775
775
  row.target = target2;
776
776
  creates.push({ path: target2, content: migrationHeader(src.package, src.file, src.source) + src.source, kind, source: { package: src.package, file: src.file } });
777
777
  if (options.tests !== false && src.test && src.testSource != null) {
778
- const test2 = `${TESTS_DIR}/${path23.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
778
+ const test2 = `${TESTS_DIR}/${path26.posix.basename(src.test).replace(/^\d{4}_/, "")}`;
779
779
  if (readApp(root, test2) === null && !creates.some((c) => c.path === test2)) creates.push({ path: test2, content: src.testSource, kind: "test", source: { package: src.package, file: src.test } });
780
780
  }
781
781
  return;
@@ -812,9 +812,9 @@ function formatMigrationRows(rows) {
812
812
  if (!rows.length) return "No package migrations to compare.";
813
813
  const mark = { current: "=", new: "+", edited: "!", "changed-upstream": "!", differs: "!", unavailable: "?" };
814
814
  return rows.map((r) => {
815
- const where = r.target ? ` \u2192 ${r.target}` : r.copy ? ` (${r.copy})` : "";
815
+ const where2 = r.target ? ` \u2192 ${r.target}` : r.copy ? ` (${r.copy})` : "";
816
816
  const fwd = r.forward && !r.target ? `; carried by ${r.forward}` : "";
817
- return `${r.forward && !r.target ? "~" : mark[r.state]} ${r.state.padEnd(16)} ${r.package} ${r.file}${where}${r.detail ? `: ${r.detail}` : ""}${fwd}`;
817
+ return `${r.forward && !r.target ? "~" : mark[r.state]} ${r.state.padEnd(16)} ${r.package} ${r.file}${where2}${r.detail ? `: ${r.detail}` : ""}${fwd}`;
818
818
  }).join("\n");
819
819
  }
820
820
  var MIGRATIONS_DIR, TESTS_DIR, HEADER, FORWARD, normal, textSha;
@@ -833,33 +833,44 @@ var init_migrations = __esm({
833
833
  function privacyDataType(type) {
834
834
  return PRIVACY_DATA_TYPES[type.toLowerCase()];
835
835
  }
836
- function appPath2(v, where, fail) {
837
- if (typeof v !== "string" || !v.trim()) return fail(`${where} must be a non-empty path`);
838
- if (path23.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where} must be relative to the app, not absolute ("${v}")`);
839
- const norm = path23.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
840
- if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where} must be a folder inside the app ("${v}")`);
836
+ function appPath2(v, where2, fail) {
837
+ if (typeof v !== "string" || !v.trim()) return fail(`${where2} must be a non-empty path`);
838
+ if (path26.isAbsolute(v) || /^[A-Za-z]:[\\/]/.test(v)) fail(`${where2} must be relative to the app, not absolute ("${v}")`);
839
+ const norm = path26.posix.normalize(v.replace(/\\/g, "/")).replace(/\/+$/, "");
840
+ if (norm === "." || norm === ".." || norm.startsWith("../")) fail(`${where2} must be a folder inside the app ("${v}")`);
841
841
  return norm;
842
842
  }
843
843
  function loadConfig(root, configPath) {
844
844
  if (configPath) {
845
- const file = path23.resolve(root, configPath);
845
+ const file = path26.resolve(root, configPath);
846
846
  if (!existsSync(file)) throw new DoctorConfigError(`Config file not found: ${configPath}`);
847
847
  const json = readJson(file);
848
- const block = path23.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
849
- return { config: validateConfig(block ?? {}, file), file, dir: path23.dirname(file) };
848
+ const block = path26.basename(file) === "package.json" ? json?.genesis?.doctor : json?.doctor ?? json;
849
+ return { config: validateConfig(block ?? {}, file), file, dir: path26.dirname(file) };
850
850
  }
851
- const own = path23.join(root, "genesis.config.json");
851
+ const own = path26.join(root, "genesis.config.json");
852
852
  if (existsSync(own)) {
853
853
  const block = readGenesisConfig(root)?.raw.doctor;
854
854
  return { config: validateConfig(block ?? {}, own), file: own, dir: root };
855
855
  }
856
- const pkg = path23.join(root, "package.json");
856
+ const pkg = path26.join(root, "package.json");
857
857
  if (existsSync(pkg)) {
858
858
  const block = readJson(pkg)?.genesis?.doctor;
859
- if (block !== void 0) return { config: validateConfig(block, pkg), file: pkg, dir: root };
859
+ if (block !== void 0 && !isPackageDeclaration(block)) return { config: validateConfig(block, pkg), file: pkg, dir: root };
860
860
  }
861
861
  return { config: {}, file: null, dir: root };
862
862
  }
863
+ function doctorBlock(json, file, explicit) {
864
+ const j = json;
865
+ if (path26.basename(file) === "package.json") return j?.genesis?.doctor;
866
+ return explicit ? j?.doctor ?? j : j?.doctor;
867
+ }
868
+ function isPackageDeclaration(block) {
869
+ if (typeof block === "string") return true;
870
+ if (!isObject2(block)) return false;
871
+ const keys = Object.keys(block).filter((k) => k !== "$comment");
872
+ return keys.some((k) => ["prefer", "primitives", "plugin", "enforce"].includes(k)) && !keys.some((k) => KNOWN.has(k));
873
+ }
863
874
  function readJson(file) {
864
875
  try {
865
876
  return JSON.parse(readFileSync(file, "utf8"));
@@ -868,7 +879,7 @@ function readJson(file) {
868
879
  }
869
880
  }
870
881
  function readGenesisConfig(root) {
871
- const file = path23.join(root, "genesis.config.json");
882
+ const file = path26.join(root, "genesis.config.json");
872
883
  if (!existsSync(file)) return null;
873
884
  const raw = readJson(file);
874
885
  if (!isObject2(raw)) throw new GenesisConfigError(`${file}: the config must be a JSON object`);
@@ -896,18 +907,18 @@ function validatePrivacy(raw, source = "config") {
896
907
  if (c.collects !== void 0) {
897
908
  if (!Array.isArray(c.collects)) fail(`privacy.collects must be a list`);
898
909
  out.collects = c.collects.map((entry, i) => {
899
- const where = `privacy.collects[${i}]`;
900
- if (!isObject2(entry)) return fail(`${where} must be an object`);
901
- for (const key2 of Object.keys(entry)) if (!DATA_USE_KEYS.has(key2)) fail(`${where}: unknown setting "${key2}"`);
910
+ const where2 = `privacy.collects[${i}]`;
911
+ if (!isObject2(entry)) return fail(`${where2} must be an object`);
912
+ for (const key2 of Object.keys(entry)) if (!DATA_USE_KEYS.has(key2)) fail(`${where2}: unknown setting "${key2}"`);
902
913
  if (typeof entry.type !== "string" || !privacyDataType(entry.type)) {
903
- fail(`${where}.type "${String(entry.type)}" is not one of ${Object.keys(PRIVACY_DATA_TYPES).join(", ")}`);
914
+ fail(`${where2}.type "${String(entry.type)}" is not one of ${Object.keys(PRIVACY_DATA_TYPES).join(", ")}`);
904
915
  }
905
- if (!isStringList(entry.purposes) || entry.purposes.length === 0) fail(`${where}.purposes must be a non-empty list`);
916
+ if (!isStringList(entry.purposes) || entry.purposes.length === 0) fail(`${where2}.purposes must be a non-empty list`);
906
917
  for (const p of entry.purposes) {
907
- if (!(p in PRIVACY_PURPOSES)) fail(`${where}.purposes: "${p}" is not one of ${Object.keys(PRIVACY_PURPOSES).join(", ")}`);
918
+ if (!(p in PRIVACY_PURPOSES)) fail(`${where2}.purposes: "${p}" is not one of ${Object.keys(PRIVACY_PURPOSES).join(", ")}`);
908
919
  }
909
- if (typeof entry.linked !== "boolean") fail(`${where}.linked must be true or false`);
910
- if (typeof entry.tracking !== "boolean") fail(`${where}.tracking must be true or false`);
920
+ if (typeof entry.linked !== "boolean") fail(`${where2}.linked must be true or false`);
921
+ if (typeof entry.tracking !== "boolean") fail(`${where2}.tracking must be true or false`);
911
922
  return { type: entry.type, purposes: [...new Set(entry.purposes)], linked: entry.linked, tracking: entry.tracking };
912
923
  });
913
924
  }
@@ -974,6 +985,7 @@ function validateConfig(raw, source = "config") {
974
985
  if (!isObject2(c.rules)) fail(`"rules" must be an object of rule \u2192 level`);
975
986
  for (const [rule, level] of Object.entries(c.rules)) {
976
987
  if (!LEVELS.has(level)) fail(`rules.${rule} must be "error", "warn", "info" or "off"`);
988
+ if (META_RULES.has(rule)) fail(`rules can't set ${rule}: it guards the config itself`);
977
989
  }
978
990
  }
979
991
  if (c.allow !== void 0) {
@@ -983,6 +995,7 @@ function validateConfig(raw, source = "config") {
983
995
  const entry = e;
984
996
  if (typeof entry.rule !== "string" || !entry.rule) fail(`allow[${i}] needs a "rule"`);
985
997
  if (typeof entry.reason !== "string" || !entry.reason.trim()) fail(`allow[${i}] (${entry.rule}) needs a "reason"`);
998
+ if (META_RULES.has(entry.rule)) fail(`allow[${i}] can't allow ${entry.rule}: it guards the allow list itself`);
986
999
  for (const k of ["file", "match"]) {
987
1000
  if (entry[k] !== void 0 && typeof entry[k] !== "string") fail(`allow[${i}].${k} must be a string`);
988
1001
  }
@@ -998,13 +1011,42 @@ function validateConfig(raw, source = "config") {
998
1011
  for (const k of ["files", "exclude"]) {
999
1012
  if (rule[k] !== void 0 && !isStringList(rule[k])) fail(`patterns[${i}].${k} must be a list of globs`);
1000
1013
  }
1014
+ if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") fail(`patterns[${i}].newOnly must be true or false`);
1001
1015
  });
1002
1016
  }
1017
+ if (c.packageRules !== void 0) {
1018
+ if (!isObject2(c.packageRules)) fail(`"packageRules" must be an object of package rule id \u2192 { level?, files?, exclude?, reason }`);
1019
+ for (const [id, v] of Object.entries(c.packageRules)) {
1020
+ const where2 = `packageRules["${id}"]`;
1021
+ if (!id.includes("/")) fail(`${where2}: package rule ids are namespaced by package, e.g. "ui/lists-use-resource-view"`);
1022
+ if (!isObject2(v)) fail(`${where2} must be an object`);
1023
+ const setting = v;
1024
+ for (const k of Object.keys(setting)) if (!PACKAGE_RULE_KEYS.has(k)) fail(`${where2}: unknown key "${k}" (known: level, files, exclude, reason)`);
1025
+ if (typeof setting.reason !== "string" || !setting.reason.trim()) fail(`${where2} needs a "reason": a package rule is never changed silently`);
1026
+ if (setting.level !== void 0 && !LEVELS.has(setting.level)) fail(`${where2}.level must be "error", "warn", "info" or "off"`);
1027
+ for (const k of ["files", "exclude"]) if (setting[k] !== void 0 && !isStringList(setting[k])) fail(`${where2}.${k} must be a list of globs`);
1028
+ }
1029
+ }
1030
+ if (c.ratchet !== void 0 && typeof c.ratchet !== "boolean" && !isStringList(c.ratchet)) fail(`"ratchet" must be true, false or a list of rule ids`);
1003
1031
  if (c.packs !== void 0) {
1004
1032
  if (!isStringList(c.packs)) fail(`"packs" must be a list, e.g. ["native", "supabase"]`);
1005
1033
  for (const p of c.packs) if (!PACKS.has(p)) fail(`packs: unknown pack "${p}" (known: ${[...PACKS].join(", ")})`);
1006
1034
  if (new Set(c.packs).size !== c.packs.length) fail(`packs: lists a pack twice`);
1007
1035
  }
1036
+ if (c.contracts !== void 0) {
1037
+ if (!isObject2(c.contracts)) fail(`"contracts" must be an object: { out?, schemas?, databaseEnv? }`);
1038
+ const contracts = c.contracts;
1039
+ for (const k of Object.keys(contracts)) if (!CONTRACT_KEYS.has(k)) fail(`contracts: unknown setting "${k}" (known: out, schemas, databaseEnv)`);
1040
+ if (!(c.packs ?? []).includes("supabase")) fail(`"contracts" is set but the supabase pack is not in "packs"`);
1041
+ if (contracts.out !== void 0) {
1042
+ if (typeof contracts.out !== "string" || !contracts.out.trim()) fail(`contracts.out must be a file path`);
1043
+ if (path26.isAbsolute(contracts.out) || contracts.out.replace(/\\/g, "/").split("/").includes("..")) fail(`contracts.out must be a file inside the app`);
1044
+ }
1045
+ if (contracts.schemas !== void 0 && !isStringList(contracts.schemas)) fail(`contracts.schemas must be a list of schema names`);
1046
+ if (contracts.databaseEnv !== void 0 && (typeof contracts.databaseEnv !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(contracts.databaseEnv))) {
1047
+ fail(`contracts.databaseEnv must be an environment variable name`);
1048
+ }
1049
+ }
1008
1050
  for (const [pack, keys] of Object.entries(PACK_KEYS)) {
1009
1051
  const block = c[pack];
1010
1052
  if (block === void 0) continue;
@@ -1027,11 +1069,11 @@ function validateConfig(raw, source = "config") {
1027
1069
  }
1028
1070
  return c;
1029
1071
  }
1030
- function checkRegExp(source, where, fail) {
1072
+ function checkRegExp(source, where2, fail) {
1031
1073
  try {
1032
1074
  new RegExp(source);
1033
1075
  } catch (err) {
1034
- fail(`${where} is not a valid regular expression: ${err.message}`);
1076
+ fail(`${where2} is not a valid regular expression: ${err.message}`);
1035
1077
  }
1036
1078
  }
1037
1079
  function isObject2(v) {
@@ -1040,7 +1082,7 @@ function isObject2(v) {
1040
1082
  function isStringList(v) {
1041
1083
  return Array.isArray(v) && v.every((x) => typeof x === "string");
1042
1084
  }
1043
- var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, STRING_LISTS, STRINGS, KNOWN, LEVELS, PATTERN_KEYS, PACKS, PACK_KEYS, PRIVACY_KEYS, DATA_USE_KEYS, LINK_KEYS, HOST;
1085
+ var GenesisConfigError, DoctorConfigError, PRIVACY_DATA_TYPES, PRIVACY_PURPOSES, STRING_LISTS, STRINGS, KNOWN, LEVELS, META_RULES, PATTERN_KEYS, PACKAGE_RULE_KEYS, CONTRACT_KEYS, PACKS, PACK_KEYS, PRIVACY_KEYS, DATA_USE_KEYS, LINK_KEYS, HOST;
1044
1086
  var init_config = __esm({
1045
1087
  "src/doctor/config.ts"() {
1046
1088
  GenesisConfigError = class extends Error {
@@ -1111,11 +1153,17 @@ var init_config = __esm({
1111
1153
  "supabase",
1112
1154
  "packages",
1113
1155
  "routesDir",
1156
+ "packageRules",
1157
+ "ratchet",
1158
+ "contracts",
1114
1159
  "$schema",
1115
1160
  "$comment"
1116
1161
  ]);
1117
1162
  LEVELS = /* @__PURE__ */ new Set(["error", "warn", "info", "off"]);
1118
- PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message"]);
1163
+ META_RULES = /* @__PURE__ */ new Set(["allow-grew", "rules-weakened", "ratchet-skipped"]);
1164
+ PATTERN_KEYS = /* @__PURE__ */ new Set(["id", "level", "files", "exclude", "forbid", "require", "path", "message", "newOnly"]);
1165
+ PACKAGE_RULE_KEYS = /* @__PURE__ */ new Set(["level", "files", "exclude", "reason"]);
1166
+ CONTRACT_KEYS = /* @__PURE__ */ new Set(["out", "schemas", "databaseEnv"]);
1119
1167
  PACKS = /* @__PURE__ */ new Set(["native", "supabase", "packages"]);
1120
1168
  PACK_KEYS = {
1121
1169
  native: { routerRoot: "path" },
@@ -1129,11 +1177,11 @@ var init_config = __esm({
1129
1177
  }
1130
1178
  });
1131
1179
  function findPackageDir(from, name) {
1132
- let dir = path23.resolve(from);
1180
+ let dir = path26.resolve(from);
1133
1181
  for (; ; ) {
1134
- const candidate = path23.join(dir, "node_modules", name);
1135
- if (existsSync(path23.join(candidate, "package.json"))) return candidate;
1136
- const parent = path23.dirname(dir);
1182
+ const candidate = path26.join(dir, "node_modules", name);
1183
+ if (existsSync(path26.join(candidate, "package.json"))) return candidate;
1184
+ const parent = path26.dirname(dir);
1137
1185
  if (parent === dir) return null;
1138
1186
  dir = parent;
1139
1187
  }
@@ -1185,7 +1233,7 @@ function loadCompanions(root, config, uiPackage) {
1185
1233
  function readPackageExports(root, uiPackage) {
1186
1234
  const uiDir = findPackageDir(root, uiPackage);
1187
1235
  if (!uiDir) return null;
1188
- const uiPkg = JSON.parse(readFileSync(path23.join(uiDir, "package.json"), "utf8"));
1236
+ const uiPkg = JSON.parse(readFileSync(path26.join(uiDir, "package.json"), "utf8"));
1189
1237
  const typeEntries = /* @__PURE__ */ new Set();
1190
1238
  const mainTypes = uiPkg.types ?? uiPkg.typings ?? exportTypes(uiPkg.exports?.["."] ?? uiPkg.exports);
1191
1239
  if (typeof mainTypes === "string") typeEntries.add(mainTypes);
@@ -1197,7 +1245,7 @@ function readPackageExports(root, uiPackage) {
1197
1245
  const reexportedPackages = /* @__PURE__ */ new Set();
1198
1246
  let readAny = false;
1199
1247
  for (const entry of typeEntries) {
1200
- const file = path23.join(uiDir, entry);
1248
+ const file = path26.join(uiDir, entry);
1201
1249
  if (!existsSync(file)) continue;
1202
1250
  readAny = true;
1203
1251
  const dts = readFileSync(file, "utf8");
@@ -1211,11 +1259,11 @@ function readPackageExports(root, uiPackage) {
1211
1259
  }
1212
1260
  const valueDecls = /* @__PURE__ */ new Set();
1213
1261
  const typeDecls = /* @__PURE__ */ new Set();
1214
- const declRoot = typeof mainTypes === "string" ? path23.dirname(path23.join(uiDir, mainTypes)) : uiDir;
1262
+ const declRoot = typeof mainTypes === "string" ? path26.dirname(path26.join(uiDir, mainTypes)) : uiDir;
1215
1263
  const declFiles = walkDts(declRoot);
1216
1264
  for (const pkg of reexportedPackages) {
1217
1265
  const dir = findPackageDir(uiDir, pkg);
1218
- if (dir) walkDts(path23.join(dir, "dist"), declFiles);
1266
+ if (dir) walkDts(path26.join(dir, "dist"), declFiles);
1219
1267
  }
1220
1268
  for (const file of declFiles) {
1221
1269
  const text = readFileSync(file, "utf8");
@@ -1261,7 +1309,7 @@ function walkDts(dir, out = []) {
1261
1309
  if (!existsSync(dir)) return out;
1262
1310
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
1263
1311
  if (entry.name === "node_modules") continue;
1264
- const p = path23.join(dir, entry.name);
1312
+ const p = path26.join(dir, entry.name);
1265
1313
  if (entry.isDirectory()) walkDts(p, out);
1266
1314
  else if (/\.d\.[cm]?ts$/.test(entry.name)) out.push(p);
1267
1315
  }
@@ -1278,27 +1326,27 @@ function resolveThemeFiles(root, config, uiDir) {
1278
1326
  }
1279
1327
  const files = [];
1280
1328
  const ds = findPackageDir(root, DESIGN_SYSTEM_PACKAGE);
1281
- const themes = ds && path23.join(ds, "dist", "themes");
1329
+ const themes = ds && path26.join(ds, "dist", "themes");
1282
1330
  if (themes && existsSync(themes)) {
1283
- for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path23.join(themes, name));
1331
+ for (const name of readdirSync(themes).sort()) if (name.endsWith(".css")) files.push(path26.join(themes, name));
1284
1332
  }
1285
1333
  if (files.length === 0) {
1286
1334
  throw new DoctorConfigError(
1287
1335
  `No Genesis theme stylesheet found (${DESIGN_SYSTEM_PACKAGE}/dist/themes/*.css). Install the design system, or set doctor.themeCss.`
1288
1336
  );
1289
1337
  }
1290
- const uiStyles = path23.join(uiDir, "dist", "styles.css");
1338
+ const uiStyles = path26.join(uiDir, "dist", "styles.css");
1291
1339
  if (existsSync(uiStyles)) files.push(uiStyles);
1292
1340
  return files;
1293
1341
  }
1294
1342
  function resolveSpec(root, spec) {
1295
- const local = path23.resolve(root, spec);
1296
- if (spec.startsWith(".") || path23.isAbsolute(spec)) return existsSync(local) ? local : null;
1343
+ const local = path26.resolve(root, spec);
1344
+ if (spec.startsWith(".") || path26.isAbsolute(spec)) return existsSync(local) ? local : null;
1297
1345
  const parts = spec.split("/");
1298
1346
  const nameLength = spec.startsWith("@") ? 2 : 1;
1299
1347
  const dir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
1300
1348
  if (dir) {
1301
- const file = path23.join(dir, ...parts.slice(nameLength));
1349
+ const file = path26.join(dir, ...parts.slice(nameLength));
1302
1350
  if (existsSync(file) && statSync(file).isFile()) return file;
1303
1351
  }
1304
1352
  return existsSync(local) ? local : null;
@@ -1306,7 +1354,7 @@ function resolveSpec(root, spec) {
1306
1354
  function loadPalette(root) {
1307
1355
  const names = new Set(TAILWIND_PALETTE);
1308
1356
  try {
1309
- const req = createRequire(path23.join(root, "package.json"));
1357
+ const req = createRequire(path26.join(root, "package.json"));
1310
1358
  const colors = req("tailwindcss/colors");
1311
1359
  for (const key2 of Object.keys(colors?.default ?? colors ?? {})) {
1312
1360
  if (/^[a-z]+$/.test(key2) && !["inherit", "current", "transparent"].includes(key2)) names.add(key2);
@@ -1360,7 +1408,7 @@ var init_genesis = __esm({
1360
1408
  });
1361
1409
  function readReleaseManifest(root) {
1362
1410
  const dir = findPackageDir(root, UMBRELLA_PACKAGE);
1363
- const file = dir && path23.join(dir, "dist", "versions.json");
1411
+ const file = dir && path26.join(dir, "dist", "versions.json");
1364
1412
  if (!file || !existsSync(file)) return null;
1365
1413
  return JSON.parse(readFileSync(file, "utf8"));
1366
1414
  }
@@ -1370,7 +1418,7 @@ function checkVersionSkew(ctx) {
1370
1418
  for (const [name, want] of Object.entries(manifest.packages)) {
1371
1419
  const dir = findPackageDir(ctx.root, name);
1372
1420
  if (!dir) continue;
1373
- const have = JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8")).version;
1421
+ const have = JSON.parse(readFileSync(path26.join(dir, "package.json"), "utf8")).version;
1374
1422
  if (have === want) continue;
1375
1423
  ctx.report({
1376
1424
  rule: "version-skew",
@@ -1389,13 +1437,13 @@ var init_versions = __esm({
1389
1437
  }
1390
1438
  });
1391
1439
  function detectPackageManager(root) {
1392
- let dir = path23.resolve(root);
1440
+ let dir = path26.resolve(root);
1393
1441
  for (; ; ) {
1394
- if (existsSync(path23.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1395
- if (existsSync(path23.join(dir, "bun.lock")) || existsSync(path23.join(dir, "bun.lockb"))) return "bun";
1396
- if (existsSync(path23.join(dir, "yarn.lock"))) return "yarn";
1397
- if (existsSync(path23.join(dir, "package-lock.json"))) return "npm";
1398
- const parent = path23.dirname(dir);
1442
+ if (existsSync(path26.join(dir, "pnpm-lock.yaml"))) return "pnpm";
1443
+ if (existsSync(path26.join(dir, "bun.lock")) || existsSync(path26.join(dir, "bun.lockb"))) return "bun";
1444
+ if (existsSync(path26.join(dir, "yarn.lock"))) return "yarn";
1445
+ if (existsSync(path26.join(dir, "package-lock.json"))) return "npm";
1446
+ const parent = path26.dirname(dir);
1399
1447
  if (parent === dir) return "npm";
1400
1448
  dir = parent;
1401
1449
  }
@@ -1431,10 +1479,10 @@ var init_pm = __esm({
1431
1479
  function walk(dir, exclude = []) {
1432
1480
  const out = [];
1433
1481
  const visit = (rel) => {
1434
- for (const name of readdirSync(path23.join(dir, rel)).sort()) {
1482
+ for (const name of readdirSync(path26.join(dir, rel)).sort()) {
1435
1483
  const child = rel ? `${rel}/${name}` : name;
1436
1484
  if (exclude.some((r) => r.test(child))) continue;
1437
- const stat = statSync(path23.join(dir, child));
1485
+ const stat = statSync(path26.join(dir, child));
1438
1486
  if (stat.isDirectory()) visit(child);
1439
1487
  else if (stat.isFile()) out.push(child);
1440
1488
  }
@@ -1463,17 +1511,17 @@ var init_walk = __esm({
1463
1511
  });
1464
1512
  function starterDir() {
1465
1513
  const workspace = workspacePackagesDir();
1466
- const live = workspace && path23.join(workspace, "..", "apps", "genesis-rn-starter");
1467
- if (live && existsSync(path23.join(live, "package.json"))) return live;
1468
- const packaged = path23.join(cliPackageDir(), "dist", "starter");
1469
- if (existsSync(path23.join(packaged, "package.json"))) return packaged;
1514
+ const live = workspace && path26.join(workspace, "..", "apps", "genesis-rn-starter");
1515
+ if (live && existsSync(path26.join(live, "package.json"))) return live;
1516
+ const packaged = path26.join(cliPackageDir(), "dist", "starter");
1517
+ if (existsSync(path26.join(packaged, "package.json"))) return packaged;
1470
1518
  throw new Error("This genesis-cli has no starter (dist/starter is missing): reinstall @marktiderman/genesis-cli.");
1471
1519
  }
1472
1520
  function templatesDir(cliDir = cliPackageDir()) {
1473
1521
  const workspace = workspacePackagesDir();
1474
- const live = workspace && cliDir === cliPackageDir() ? path23.join(workspace, "..", "templates") : null;
1475
- if (live && existsSync(path23.join(live, "eas"))) return live;
1476
- const packaged = path23.join(cliDir, "dist", "templates");
1522
+ const live = workspace && cliDir === cliPackageDir() ? path26.join(workspace, "..", "templates") : null;
1523
+ if (live && existsSync(path26.join(live, "eas"))) return live;
1524
+ const packaged = path26.join(cliDir, "dist", "templates");
1477
1525
  if (existsSync(packaged)) return packaged;
1478
1526
  throw new Error(`${cliDir} has no templates (dist/templates is missing).`);
1479
1527
  }
@@ -1554,16 +1602,16 @@ function initNative(options) {
1554
1602
  if (!BUNDLE.test(bundleId)) throw new Error(`"${bundleId}" isn't a bundle id like com.example.app.`);
1555
1603
  if (!SCHEME.test(scheme)) throw new Error(`"${scheme}" isn't a URL scheme.`);
1556
1604
  if (/["\\\n]/.test(display)) throw new Error("The display name can't contain quotes, backslashes or new lines.");
1557
- const target = path23.resolve(options.target);
1605
+ const target = path26.resolve(options.target);
1558
1606
  if (existsSync(target) && readdirSync(target).length) throw new Error(`${target} isn't empty; init writes into a new folder and never overwrites.`);
1559
1607
  const source = starterDir();
1560
- const read = (rel) => readFileSync(path23.join(source, rel), "utf8");
1561
- const was = starterIdentity(read("starter.config.ts"));
1608
+ const read2 = (rel) => readFileSync(path26.join(source, rel), "utf8");
1609
+ const was = starterIdentity(read2("starter.config.ts"));
1562
1610
  const substitutions = { [was.bundleId]: bundleId, [was.slug]: slug, [was.scheme]: scheme, [was.name]: display };
1563
1611
  const files = /* @__PURE__ */ new Map();
1564
1612
  for (const rel of walk(source, STARTER_EXCLUDE)) {
1565
1613
  const to = rel.replace(new RegExp(`(^|/)${PACKED_GITIGNORE}$`), "$1.gitignore");
1566
- files.set(to, /^supabase\/(migrations|tests)\//.test(rel) ? read(rel) : substitute(read(rel), substitutions));
1614
+ files.set(to, /^supabase\/(migrations|tests)\//.test(rel) ? read2(rel) : substitute(read2(rel), substitutions));
1567
1615
  }
1568
1616
  const versionFor = options.versionFor ?? ((name) => pinnedVersion(target, name)?.version ?? null);
1569
1617
  const pkg = JSON.parse(files.get("package.json"));
@@ -1588,14 +1636,14 @@ function initNative(options) {
1588
1636
  files.set("package.json", `${JSON.stringify(pkg, null, 2)}
1589
1637
  `);
1590
1638
  files.set("metro.config.js", METRO);
1591
- const pnpmSettings = [path23.join(source, "pnpm-workspace.yaml"), path23.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
1639
+ const pnpmSettings = [path26.join(source, "pnpm-workspace.yaml"), path26.join(source, "..", "..", "pnpm-workspace.yaml")].find((f) => existsSync(f));
1592
1640
  if (pnpmSettings) files.set("pnpm-workspace.yaml", appPnpmSettings(readFileSync(pnpmSettings, "utf8")));
1593
1641
  files.set("README.md", readme(display, slug));
1594
1642
  const lock = { ...emptyLock(), substitutions };
1595
1643
  const cliVersion2 = pinnedVersion(target, CLI_PACKAGE)?.version;
1596
1644
  const templates = templatesDir();
1597
1645
  for (const rel of walk(templates)) {
1598
- const text = substitute(readFileSync(path23.join(templates, rel), "utf8"), substitutions);
1646
+ const text = substitute(readFileSync(path26.join(templates, rel), "utf8"), substitutions);
1599
1647
  const to = templateTarget(rel, text);
1600
1648
  files.set(to, text);
1601
1649
  lock.files[to] = { source: `${CLI_PACKAGE}:templates/${rel}`, sha256: sha256(text), ...cliVersion2 ? { version: cliVersion2 } : {} };
@@ -1606,13 +1654,13 @@ function initNative(options) {
1606
1654
  const blocks = [];
1607
1655
  for (const block of options.blocks) {
1608
1656
  const stems = block.migrations.map((m) => stemOf(m.file));
1609
- const copies = stems.map((s) => migrations.find((f) => path23.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
1657
+ const copies = stems.map((s) => migrations.find((f) => path26.posix.basename(f).replace(/^\d+_/, "") === `${s}.sql`));
1610
1658
  if (!stems.length || copies.some((c) => !c)) continue;
1611
1659
  blocks.push(block.id);
1612
1660
  lock.blocks[block.id] = { package: block.package, ...block.version ? { version: block.version } : {} };
1613
1661
  block.migrations.forEach((m) => {
1614
1662
  if (m.test) {
1615
- const test2 = `${TESTS_DIR}/${path23.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
1663
+ const test2 = `${TESTS_DIR}/${path26.posix.basename(m.test).replace(/^\d{4}_/, "")}`;
1616
1664
  if (files.has(test2)) lock.files[test2] = { source: `${m.package}:${m.test}`, sha256: sha256(files.get(test2)) };
1617
1665
  }
1618
1666
  });
@@ -1625,8 +1673,8 @@ function initNative(options) {
1625
1673
  }
1626
1674
  mkdirSync(target, { recursive: true });
1627
1675
  for (const [rel, content] of [...files].sort(([a], [b]) => a.localeCompare(b))) {
1628
- const file = path23.join(target, ...rel.split("/"));
1629
- mkdirSync(path23.dirname(file), { recursive: true });
1676
+ const file = path26.join(target, ...rel.split("/"));
1677
+ mkdirSync(path26.dirname(file), { recursive: true });
1630
1678
  writeFileSync(file, content, { encoding: "utf8", flag: "wx" });
1631
1679
  }
1632
1680
  writeLock(target, lock);
@@ -1664,8 +1712,179 @@ module.exports = withNativeWind(getDefaultConfig(__dirname), { input: "./global.
1664
1712
  }
1665
1713
  });
1666
1714
 
1715
+ // src/introspect/catalog-text.ts
1716
+ function tokenize(tree) {
1717
+ const tokens = [];
1718
+ let i = 0;
1719
+ while (i < tree.length) {
1720
+ const ch = tree[i];
1721
+ if (ch === " " || ch === "\n" || ch === " ") {
1722
+ i++;
1723
+ } else if (ch === "{" || ch === "(") {
1724
+ tokens.push({ kind: "open", char: ch });
1725
+ i++;
1726
+ } else if (ch === "}" || ch === ")") {
1727
+ tokens.push({ kind: "close", char: ch });
1728
+ i++;
1729
+ } else {
1730
+ let text = "";
1731
+ while (i < tree.length) {
1732
+ const c = tree[i];
1733
+ if (c === "\\" && i + 1 < tree.length) {
1734
+ text += tree[i + 1];
1735
+ i += 2;
1736
+ continue;
1737
+ }
1738
+ if (c === " " || c === "\n" || c === " " || c === "{" || c === "}" || c === "(" || c === ")") break;
1739
+ text += c;
1740
+ i++;
1741
+ }
1742
+ tokens.push({ kind: "atom", text });
1743
+ }
1744
+ }
1745
+ return tokens;
1746
+ }
1747
+ function viewColumnOrigins(evAction) {
1748
+ const tokens = tokenize(evAction);
1749
+ let depth = 0;
1750
+ let start = -1;
1751
+ for (let i = 0; i < tokens.length; i++) {
1752
+ const t = tokens[i];
1753
+ if (t.kind === "open") depth++;
1754
+ else if (t.kind === "close") depth--;
1755
+ else if (depth === 2 && t.text === ":targetList") {
1756
+ start = i + 1;
1757
+ break;
1758
+ }
1759
+ }
1760
+ if (start < 0) return [];
1761
+ const origins = [];
1762
+ depth = 2;
1763
+ let entry = null;
1764
+ let lastKey = null;
1765
+ for (let i = start; i < tokens.length; i++) {
1766
+ const t = tokens[i];
1767
+ if (t.kind === "open") {
1768
+ depth++;
1769
+ if (depth === 4 && t.char === "{") {
1770
+ entry = /* @__PURE__ */ new Map();
1771
+ lastKey = null;
1772
+ }
1773
+ continue;
1774
+ }
1775
+ if (t.kind === "close") {
1776
+ if (depth === 4 && entry) {
1777
+ const relation = Number(entry.get(":resorigtbl"));
1778
+ const column = Number(entry.get(":resorigcol"));
1779
+ const position = Number(entry.get(":resno"));
1780
+ const name = entry.get(":resname") ?? "";
1781
+ if (entry.get(":resjunk") !== "true" && position > 0 && relation > 0 && column > 0) {
1782
+ origins.push({ position, name, relation, column });
1783
+ }
1784
+ entry = null;
1785
+ }
1786
+ depth--;
1787
+ if (depth <= 2) break;
1788
+ continue;
1789
+ }
1790
+ if (depth !== 4 || !entry) continue;
1791
+ if (t.text === "TARGETENTRY") continue;
1792
+ if (t.text.startsWith(":")) lastKey = t.text;
1793
+ else if (lastKey) {
1794
+ entry.set(lastKey, t.text);
1795
+ lastKey = null;
1796
+ }
1797
+ }
1798
+ return origins;
1799
+ }
1800
+ function unwrap(expr) {
1801
+ let s = expr.trim();
1802
+ for (; ; ) {
1803
+ if (!s.startsWith("(") || !s.endsWith(")")) return s;
1804
+ let depth = 0;
1805
+ let inQuote = false;
1806
+ let wrapsAll = true;
1807
+ for (let i = 0; i < s.length; i++) {
1808
+ const c = s[i];
1809
+ if (c === "'") inQuote = !inQuote;
1810
+ if (inQuote) continue;
1811
+ if (c === "(") depth++;
1812
+ else if (c === ")") {
1813
+ depth--;
1814
+ if (depth === 0 && i < s.length - 1) {
1815
+ wrapsAll = false;
1816
+ break;
1817
+ }
1818
+ }
1819
+ }
1820
+ if (!wrapsAll) return s;
1821
+ s = s.slice(1, -1).trim();
1822
+ }
1823
+ }
1824
+ function splitTopLevel(expr, separator) {
1825
+ const parts = [];
1826
+ let depth = 0;
1827
+ let inQuote = false;
1828
+ let from = 0;
1829
+ for (let i = 0; i < expr.length; i++) {
1830
+ const c = expr[i];
1831
+ if (c === "'") inQuote = !inQuote;
1832
+ if (inQuote) continue;
1833
+ if (c === "(") depth++;
1834
+ else if (c === ")") depth--;
1835
+ else if (depth === 0 && expr.startsWith(separator, i)) {
1836
+ parts.push(expr.slice(from, i));
1837
+ from = i + separator.length;
1838
+ i += separator.length - 1;
1839
+ }
1840
+ }
1841
+ parts.push(expr.slice(from));
1842
+ return parts;
1843
+ }
1844
+ function escapeRegExp(s) {
1845
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1846
+ }
1847
+ function checkEnumValues(definition, column) {
1848
+ const outer = /^CHECK \((.*)\)(?: NOT VALID)?$/s.exec(definition.trim());
1849
+ if (!outer) return void 0;
1850
+ const ident = `(?:${escapeRegExp(column)}|${escapeRegExp(`"${column.replace(/"/g, '""')}"`)})`;
1851
+ const ref = String.raw`(?:${ident}|\(${ident}\)${CAST})`;
1852
+ let body = unwrap(outer[1]);
1853
+ const parts = splitTopLevel(body, " OR ");
1854
+ if (parts.length === 2) {
1855
+ const isNull = new RegExp(`^${ref} IS NULL$`);
1856
+ const nullAt = parts.findIndex((p) => isNull.test(unwrap(p)));
1857
+ if (nullAt < 0) return void 0;
1858
+ body = unwrap(parts[1 - nullAt]);
1859
+ } else if (parts.length !== 1) {
1860
+ return void 0;
1861
+ }
1862
+ const single = new RegExp(`^${ref} = ${LITERAL}$`).exec(body);
1863
+ if (single) return [single[1].replace(/''/g, "'")];
1864
+ const any = new RegExp(String.raw`^${ref} = ANY \((.*)\)$`).exec(body);
1865
+ if (!any) return void 0;
1866
+ const list = /^\(?ARRAY\[(.*?)\](?:\)(?:::[a-z][a-z ]*(?:\(\d+\))?\[\]))?$/s.exec(unwrap(any[1]));
1867
+ if (!list) return void 0;
1868
+ const items = splitTopLevel(list[1], ", ");
1869
+ const values = [];
1870
+ const literal2 = new RegExp(`^${LITERAL}$`);
1871
+ for (const item of items) {
1872
+ const m = literal2.exec(item.trim());
1873
+ if (!m) return void 0;
1874
+ values.push(m[1].replace(/''/g, "'"));
1875
+ }
1876
+ return values.length ? values : void 0;
1877
+ }
1878
+ var CAST, LITERAL;
1879
+ var init_catalog_text = __esm({
1880
+ "src/introspect/catalog-text.ts"() {
1881
+ CAST = String.raw`::[a-z][a-z ]*(?:\(\d+(?:,\d+)?\))?`;
1882
+ LITERAL = String.raw`'((?:[^']|'')*)'${CAST}`;
1883
+ }
1884
+ });
1885
+
1667
1886
  // src/introspect/comments.ts
1668
- function parse(comment, keys, where) {
1887
+ function parse(comment, keys, where2) {
1669
1888
  if (!comment) return {};
1670
1889
  const at = comment.indexOf(MARKER);
1671
1890
  if (at < 0) return { description: comment.trim() || void 0 };
@@ -1675,18 +1894,18 @@ function parse(comment, keys, where) {
1675
1894
  try {
1676
1895
  value = JSON.parse(raw);
1677
1896
  } catch {
1678
- throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
1897
+ throw new CommentSettingsError(`${where2}: the text after ${MARKER} must be one JSON object.`);
1679
1898
  }
1680
1899
  if (!value || typeof value !== "object" || Array.isArray(value)) {
1681
- throw new CommentSettingsError(`${where}: the text after ${MARKER} must be one JSON object.`);
1900
+ throw new CommentSettingsError(`${where2}: the text after ${MARKER} must be one JSON object.`);
1682
1901
  }
1683
1902
  const settings2 = {};
1684
1903
  for (const [key2, v] of Object.entries(value)) {
1685
1904
  const kind = keys[key2];
1686
1905
  if (!kind) {
1687
- throw new CommentSettingsError(`${where}: unknown ${MARKER} setting "${key2}". Allowed: ${Object.keys(keys).join(", ")}.`);
1906
+ throw new CommentSettingsError(`${where2}: unknown ${MARKER} setting "${key2}". Allowed: ${Object.keys(keys).join(", ")}.`);
1688
1907
  }
1689
- if (typeof v !== kind) throw new CommentSettingsError(`${where}: ${MARKER} "${key2}" must be a ${kind}.`);
1908
+ if (typeof v !== kind) throw new CommentSettingsError(`${where2}: ${MARKER} "${key2}" must be a ${kind}.`);
1690
1909
  settings2[key2] = v;
1691
1910
  }
1692
1911
  return {
@@ -1722,16 +1941,24 @@ function storageTypeOf(dbType) {
1722
1941
  if (t === "json" || t === "jsonb") return "json";
1723
1942
  return "string";
1724
1943
  }
1944
+ function qualifiedName(schema, table) {
1945
+ const part = (p) => /[."]/.test(p) ? `"${p.replace(/"/g, '""')}"` : p;
1946
+ return `${part(schema)}.${part(table)}`;
1947
+ }
1725
1948
  var init_model = __esm({
1726
1949
  "src/introspect/model.ts"() {
1727
1950
  }
1728
1951
  });
1729
1952
 
1730
1953
  // src/introspect/postgres.ts
1731
- async function introspectPostgres(sql, schemas) {
1954
+ function where(sql, scope) {
1955
+ return "schemas" in scope ? sql`n.nspname = any(${scope.schemas})` : sql`c.oid = any(${scope.oids}::oid[])`;
1956
+ }
1957
+ async function readRelations(sql, scope, into) {
1732
1958
  const columns = await sql`
1733
- select n.nspname as schema, c.relname as table,
1959
+ select c.oid::text as oid, c.relkind::text as relkind, n.nspname as schema, c.relname as table,
1734
1960
  obj_description(c.oid, 'pg_class') as table_comment,
1961
+ a.attnum::int as attnum,
1735
1962
  a.attname as column,
1736
1963
  format_type(a.atttypid, a.atttypmod) as db_type,
1737
1964
  t.typcategory = 'A' as is_array,
@@ -1747,71 +1974,201 @@ async function introspectPostgres(sql, schemas) {
1747
1974
  join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
1748
1975
  join pg_type t on t.oid = a.atttypid
1749
1976
  where c.relkind in ('r', 'p', 'v', 'm', 'f')
1750
- and n.nspname = any(${schemas})
1977
+ and ${where(sql, scope)}
1751
1978
  order by n.nspname, c.relname, a.attnum`;
1752
1979
  const keys = await sql`
1753
- select n.nspname as schema, c.relname as table,
1754
- array_agg(a.attname::text order by k.ord) as columns
1980
+ select c.oid::text as oid, array_agg(k.attnum::int order by k.ord) as columns
1755
1981
  from pg_constraint con
1756
1982
  join pg_class c on c.oid = con.conrelid
1757
1983
  join pg_namespace n on n.oid = c.relnamespace
1758
1984
  cross join lateral unnest(con.conkey) with ordinality as k(attnum, ord)
1759
- join pg_attribute a on a.attrelid = c.oid and a.attnum = k.attnum
1760
- where con.contype = 'p' and n.nspname = any(${schemas})
1761
- group by n.nspname, c.relname`;
1985
+ where con.contype = 'p' and ${where(sql, scope)}
1986
+ group by c.oid`;
1762
1987
  const links = await sql`
1763
- select n.nspname as schema, c.relname as table, a.attname as column,
1988
+ select c.oid::text as oid, con.conkey[1]::int as attnum,
1764
1989
  rn.nspname as ref_schema, rc.relname as ref_table, ra.attname as ref_column
1765
1990
  from pg_constraint con
1766
1991
  join pg_class c on c.oid = con.conrelid
1767
1992
  join pg_namespace n on n.oid = c.relnamespace
1768
- join pg_attribute a on a.attrelid = c.oid and a.attnum = con.conkey[1]
1769
1993
  join pg_class rc on rc.oid = con.confrelid
1770
1994
  join pg_namespace rn on rn.oid = rc.relnamespace
1771
1995
  join pg_attribute ra on ra.attrelid = rc.oid and ra.attnum = con.confkey[1]
1772
1996
  where con.contype = 'f' and array_length(con.conkey, 1) = 1
1773
- and n.nspname = any(${schemas})`;
1774
- const keyOf = new Map(keys.map((k) => [`${k.schema}.${k.table}`, k.columns]));
1775
- const linkOf = new Map(links.map((l) => [`${l.schema}.${l.table}.${l.column}`, l]));
1776
- const tables = /* @__PURE__ */ new Map();
1997
+ and ${where(sql, scope)}`;
1998
+ const checks = await sql`
1999
+ select c.oid::text as oid, con.conkey[1]::int as attnum, a.attname as column,
2000
+ pg_get_constraintdef(con.oid) as definition
2001
+ from pg_constraint con
2002
+ join pg_class c on c.oid = con.conrelid
2003
+ join pg_namespace n on n.oid = c.relnamespace
2004
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = con.conkey[1]
2005
+ where con.contype = 'c' and array_length(con.conkey, 1) = 1
2006
+ and ${where(sql, scope)}
2007
+ order by con.conname`;
2008
+ const views = await sql`
2009
+ select c.oid::text as oid, r.ev_action::text as ev_action
2010
+ from pg_class c
2011
+ join pg_namespace n on n.oid = c.relnamespace
2012
+ join pg_rewrite r on r.ev_class = c.oid and r.rulename = '_RETURN'
2013
+ where c.relkind = 'v'
2014
+ and (pg_relation_is_updatable(c.oid, false) & 20) = 20
2015
+ and not exists (select 1 from pg_rewrite o where o.ev_class = c.oid and o.rulename <> '_RETURN')
2016
+ and ${where(sql, scope)}`;
2017
+ const added = [];
1777
2018
  for (const row of columns) {
1778
- const name = `${row.schema}.${row.table}`;
1779
- let table = tables.get(name);
1780
- if (!table) {
2019
+ let relation = into.get(row.oid);
2020
+ if (!relation) {
2021
+ const name = qualifiedName(row.schema, row.table);
1781
2022
  const comment2 = parseTableComment(row.table_comment, name);
1782
- table = {
1783
- name,
1784
- schema: row.schema,
1785
- table: row.table,
1786
- key: keyOf.get(name) ?? [],
1787
- columns: [],
1788
- ...comment2.description ? { description: comment2.description } : {},
1789
- ...comment2.settings ? { settings: comment2.settings } : {}
2023
+ relation = {
2024
+ oid: row.oid,
2025
+ table: {
2026
+ name,
2027
+ schema: row.schema,
2028
+ table: row.table,
2029
+ key: [],
2030
+ columns: [],
2031
+ ...comment2.description ? { description: comment2.description } : {},
2032
+ ...comment2.settings ? { settings: comment2.settings } : {}
2033
+ },
2034
+ columns: /* @__PURE__ */ new Map(),
2035
+ key: []
1790
2036
  };
1791
- tables.set(name, table);
2037
+ into.set(row.oid, relation);
2038
+ added.push(row.oid);
1792
2039
  }
1793
- const comment = parseColumnComment(row.column_comment, `${name}.${row.column}`);
1794
- const link = linkOf.get(`${name}.${row.column}`);
1795
- table.columns.push({
2040
+ const comment = parseColumnComment(row.column_comment, `${relation.table.name}.${row.column}`);
2041
+ const column = {
1796
2042
  name: row.column,
1797
2043
  dbType: row.db_type,
1798
2044
  type: storageTypeOf(row.db_type),
1799
2045
  array: row.is_array,
1800
2046
  nullable: !row.not_null,
2047
+ // A view's columns always read as nullable: unknown until traced to a table.
2048
+ ...row.relkind === "v" || row.relkind === "m" ? { nullableUnknown: true } : {},
1801
2049
  hasDefault: row.has_default,
1802
2050
  generated: row.generated,
1803
2051
  ...row.enum_values ? { enumValues: row.enum_values } : {},
1804
- ...link ? { references: { resource: `${link.ref_schema}.${link.ref_table}`, field: link.ref_column } } : {},
1805
2052
  ...comment.description ? { description: comment.description } : {},
1806
2053
  ...comment.settings ? { settings: comment.settings } : {}
1807
- });
2054
+ };
2055
+ relation.table.columns.push(column);
2056
+ relation.columns.set(row.attnum, column);
1808
2057
  }
1809
- return [...tables.values()];
2058
+ for (const k of keys) {
2059
+ const relation = into.get(k.oid);
2060
+ if (relation) relation.key = k.columns;
2061
+ }
2062
+ for (const l of links) {
2063
+ const column = into.get(l.oid)?.columns.get(l.attnum);
2064
+ if (column) column.references = { resource: qualifiedName(l.ref_schema, l.ref_table), field: l.ref_column };
2065
+ }
2066
+ const listed = /* @__PURE__ */ new Map();
2067
+ for (const check of checks) {
2068
+ const column = into.get(check.oid)?.columns.get(check.attnum);
2069
+ if (!column || column.array) continue;
2070
+ const values = checkEnumValues(check.definition, check.column);
2071
+ if (!values) continue;
2072
+ const before = listed.get(column);
2073
+ listed.set(column, before ? before.filter((v) => values.includes(v)) : values);
2074
+ }
2075
+ for (const [column, values] of listed) {
2076
+ const allowed = column.enumValues ? column.enumValues.filter((v) => values.includes(v)) : values;
2077
+ if (allowed.length > 0) column.enumValues = allowed;
2078
+ }
2079
+ for (const view of views) {
2080
+ const relation = into.get(view.oid);
2081
+ if (!relation) continue;
2082
+ relation.origins = /* @__PURE__ */ new Map();
2083
+ for (const origin of viewColumnOrigins(view.ev_action)) {
2084
+ if (relation.columns.has(origin.position)) {
2085
+ relation.origins.set(origin.position, { relation: String(origin.relation), column: origin.column });
2086
+ }
2087
+ }
2088
+ }
2089
+ return added;
2090
+ }
2091
+ function inherit(own, source) {
2092
+ const settings2 = source.settings || own.settings ? { ...source.settings, ...own.settings } : void 0;
2093
+ const description = own.description ?? source.description;
2094
+ const both = own.enumValues && source.enumValues ? own.enumValues.filter((v) => source.enumValues.includes(v)) : void 0;
2095
+ const enumValues = both?.length ? both : own.enumValues ?? source.enumValues;
2096
+ return {
2097
+ name: own.name,
2098
+ dbType: own.dbType,
2099
+ type: own.type,
2100
+ array: own.array,
2101
+ nullable: source.nullable,
2102
+ ...source.nullableUnknown ? { nullableUnknown: true } : {},
2103
+ hasDefault: own.hasDefault || source.hasDefault,
2104
+ generated: source.generated,
2105
+ ...enumValues ? { enumValues } : {},
2106
+ ...source.references ? { references: source.references } : {},
2107
+ ...description ? { description } : {},
2108
+ ...settings2 ? { settings: settings2 } : {}
2109
+ };
1810
2110
  }
2111
+ function resolveViews(relations) {
2112
+ const done = /* @__PURE__ */ new Set();
2113
+ const resolve21 = (relation, depth) => {
2114
+ if (done.has(relation.oid) || !relation.origins || depth > MAX_VIEW_DEPTH) return;
2115
+ done.add(relation.oid);
2116
+ const sources = new Set([...relation.origins.values()].map((o) => o.relation));
2117
+ if (sources.size !== 1) return;
2118
+ const source = relations.get([...sources][0]);
2119
+ if (!source) return;
2120
+ resolve21(source, depth + 1);
2121
+ const viewAttnumOf = /* @__PURE__ */ new Map();
2122
+ for (const [attnum, origin] of relation.origins) {
2123
+ const own = relation.columns.get(attnum);
2124
+ const from = source.columns.get(origin.column);
2125
+ if (!own || !from) continue;
2126
+ const merged = inherit(own, from);
2127
+ relation.columns.set(attnum, merged);
2128
+ relation.table.columns[relation.table.columns.indexOf(own)] = merged;
2129
+ if (!viewAttnumOf.has(origin.column)) viewAttnumOf.set(origin.column, attnum);
2130
+ }
2131
+ if (relation.key.length === 0 && source.key.length > 0 && source.key.every((k) => viewAttnumOf.has(k))) {
2132
+ relation.key = source.key.map((k) => viewAttnumOf.get(k));
2133
+ }
2134
+ const theirs = source.table.settings;
2135
+ const viewColumns = new Set(relation.table.columns.map((c) => c.name));
2136
+ const inherited = {
2137
+ ...theirs?.noun ? { noun: theirs.noun } : {},
2138
+ ...theirs?.nounPlural ? { nounPlural: theirs.nounPlural } : {},
2139
+ ...theirs?.labelField && viewColumns.has(theirs.labelField) ? { labelField: theirs.labelField } : {}
2140
+ };
2141
+ if (Object.keys(inherited).length) relation.table.settings = { ...inherited, ...relation.table.settings };
2142
+ };
2143
+ for (const relation of relations.values()) resolve21(relation, 0);
2144
+ }
2145
+ async function introspectPostgres(sql, schemas) {
2146
+ const relations = /* @__PURE__ */ new Map();
2147
+ const wanted = await readRelations(sql, { schemas: [...schemas] }, relations);
2148
+ for (let depth = 0; depth < MAX_VIEW_DEPTH; depth++) {
2149
+ const missing = /* @__PURE__ */ new Set();
2150
+ for (const relation of relations.values()) {
2151
+ for (const origin of relation.origins?.values() ?? []) {
2152
+ if (!relations.has(origin.relation)) missing.add(origin.relation);
2153
+ }
2154
+ }
2155
+ if (missing.size === 0) break;
2156
+ const added = await readRelations(sql, { oids: [...missing].sort() }, relations);
2157
+ if (added.length === 0) break;
2158
+ }
2159
+ resolveViews(relations);
2160
+ return wanted.map((oid) => {
2161
+ const relation = relations.get(oid);
2162
+ return { ...relation.table, key: relation.key.map((attnum) => relation.columns.get(attnum).name) };
2163
+ });
2164
+ }
2165
+ var MAX_VIEW_DEPTH;
1811
2166
  var init_postgres = __esm({
1812
2167
  "src/introspect/postgres.ts"() {
2168
+ init_catalog_text();
1813
2169
  init_comments();
1814
2170
  init_model();
2171
+ MAX_VIEW_DEPTH = 8;
1815
2172
  }
1816
2173
  });
1817
2174
 
@@ -1825,7 +2182,7 @@ function introspectOpenApi(doc, schema = "public") {
1825
2182
  if (!definitions) throw new Error("This OpenAPI document has no definitions. Is it a PostgREST (Supabase /rest/v1/) spec?");
1826
2183
  return Object.keys(definitions).sort().map((tableName) => {
1827
2184
  const def = definitions[tableName];
1828
- const name = `${schema}.${tableName}`;
2185
+ const name = qualifiedName(schema, tableName);
1829
2186
  const required = new Set(def.required ?? []);
1830
2187
  const key2 = [];
1831
2188
  const columns = Object.entries(def.properties ?? {}).map(([column, prop]) => {
@@ -1840,13 +2197,13 @@ function introspectOpenApi(doc, schema = "public") {
1840
2197
  dbType,
1841
2198
  type: storageTypeOf(format),
1842
2199
  array: isArray,
1843
- // PostgREST lists NOT NULL columns without a default as required;
1844
- // the rest may be null or are filled by the database.
2200
+ // PostgREST (v9 on) lists every NOT NULL column as required, with or
2201
+ // without a default (`filter (not . colNullable)` in its OpenAPI.hs).
1845
2202
  nullable: !required.has(column),
1846
2203
  hasDefault: prop.default !== void 0,
1847
2204
  generated: false,
1848
2205
  ...prop.enum ? { enumValues: prop.enum.map(String) } : {},
1849
- ...fk ? { references: { resource: `${schema}.${fk[1]}`, field: fk[2] } } : {},
2206
+ ...fk ? { references: { resource: qualifiedName(schema, fk[1]), field: fk[2] } } : {},
1850
2207
  ...comment2.description ? { description: comment2.description } : {},
1851
2208
  ...comment2.settings ? { settings: comment2.settings } : {}
1852
2209
  };
@@ -1897,7 +2254,7 @@ function tsType(column) {
1897
2254
  function field(column, indent) {
1898
2255
  const parts = [`name: ${quote(column.name)}`, `type: ${quote(column.type)}`, `dbType: ${quote(column.dbType)}`];
1899
2256
  if (column.array) parts.push("array: true");
1900
- if (column.nullable) parts.push("nullable: true");
2257
+ if (!column.nullableUnknown) parts.push(column.nullable ? "nullable: true" : "nullable: false");
1901
2258
  if (column.nullable || column.hasDefault || column.generated) parts.push("optional: true");
1902
2259
  if (column.hasDefault) parts.push("hasDefault: true");
1903
2260
  if (column.generated) parts.push("generated: true");
@@ -1990,6 +2347,7 @@ var init_emit = __esm({
1990
2347
  json: "unknown"
1991
2348
  };
1992
2349
  EmitError = class extends Error {
2350
+ name = "EmitError";
1993
2351
  };
1994
2352
  }
1995
2353
  });
@@ -2003,7 +2361,8 @@ __export(introspect_exports, {
2003
2361
  introspectOpenApi: () => introspectOpenApi,
2004
2362
  introspectPostgres: () => introspectPostgres,
2005
2363
  parseColumnComment: () => parseColumnComment,
2006
- parseTableComment: () => parseTableComment
2364
+ parseTableComment: () => parseTableComment,
2365
+ qualifiedName: () => qualifiedName
2007
2366
  });
2008
2367
  var init_introspect = __esm({
2009
2368
  "src/introspect/index.ts"() {
@@ -2011,23 +2370,107 @@ var init_introspect = __esm({
2011
2370
  init_openapi();
2012
2371
  init_emit();
2013
2372
  init_comments();
2373
+ init_model();
2374
+ }
2375
+ });
2376
+
2377
+ // src/doctor/contracts.ts
2378
+ var contracts_exports = {};
2379
+ __export(contracts_exports, {
2380
+ DEFAULT_CONTRACT_OUT: () => DEFAULT_CONTRACT_OUT,
2381
+ DEFAULT_DATABASE_ENV: () => DEFAULT_DATABASE_ENV,
2382
+ checkContracts: () => checkContracts,
2383
+ contractSource: () => contractSource,
2384
+ postgresContract: () => postgresContract,
2385
+ postgresSource: () => postgresSource,
2386
+ sourceSchemas: () => sourceSchemas
2387
+ });
2388
+ async function postgresContract(url, schemas) {
2389
+ const { introspectPostgres: introspectPostgres2, emitContracts: emitContracts2 } = await Promise.resolve().then(() => (init_introspect(), introspect_exports));
2390
+ const { default: postgres } = await import('postgres');
2391
+ const sql = postgres(url, { max: 1, prepare: false, onnotice: () => {
2392
+ } });
2393
+ try {
2394
+ const tables = await introspectPostgres2(sql, schemas);
2395
+ return { content: emitContracts2(tables, { source: postgresSource(schemas) }), tables: tables.length };
2396
+ } finally {
2397
+ await sql.end();
2398
+ }
2399
+ }
2400
+ function contractSource(content) {
2401
+ return /^\/\/ Source: (.*)$/m.exec(content.slice(0, 2e3))?.[1]?.trim() ?? null;
2402
+ }
2403
+ function sourceSchemas(source) {
2404
+ const m = source === null ? null : /^Postgres \((.*)\)$/.exec(source);
2405
+ const schemas = m?.[1].split(",").map((s) => s.trim()).filter(Boolean);
2406
+ return schemas?.length ? schemas : null;
2407
+ }
2408
+ async function checkContracts(ctx, read2 = postgresContract) {
2409
+ const settings2 = ctx.config.contracts;
2410
+ if (!settings2) return;
2411
+ const out = settings2.out ?? DEFAULT_CONTRACT_OUT;
2412
+ const env = settings2.databaseEnv ?? DEFAULT_DATABASE_ENV;
2413
+ let current = null;
2414
+ try {
2415
+ current = lf(readFileSync(path26.join(ctx.root, out), "utf8"));
2416
+ } catch {
2417
+ current = null;
2418
+ }
2419
+ const source = current === null ? null : contractSource(current);
2420
+ if (source !== null && !source.startsWith("Postgres (")) {
2421
+ ctx.report({ rule: "contracts-stale", level: "info", file: out, message: `not checked: it was generated from ${source.split(" ")[0]}, and the doctor compares only contracts read from Postgres; check it with genesis introspect --check and the same source` });
2422
+ return;
2423
+ }
2424
+ const schemas = settings2.schemas?.length ? settings2.schemas : sourceSchemas(source) ?? ["public"];
2425
+ const url = process.env[env];
2426
+ if (!url) {
2427
+ ctx.report({ rule: "contracts-stale", level: "info", file: out, message: `not checked: set ${env} to the database URL to compare it with the database (as genesis introspect --check)` });
2428
+ return;
2429
+ }
2430
+ let expected;
2431
+ try {
2432
+ expected = lf((await read2(url, schemas)).content);
2433
+ } catch (err) {
2434
+ const generation = err.name === "EmitError";
2435
+ const message = err.message.split("\n")[0];
2436
+ ctx.report({ rule: "contracts-stale", level: generation ? "error" : "warn", file: out, message: generation ? `couldn't be generated: ${message}` : `couldn't read the database through ${env}: ${message}` });
2437
+ return;
2438
+ }
2439
+ const target = path26.relative(process.cwd(), path26.join(ctx.root, out)) || out;
2440
+ const command = `genesis introspect -o ${shellArg(target)} -s ${shellArg(schemas.join(","))}${env === DEFAULT_DATABASE_ENV ? "" : ` --database-env ${shellArg(env)}`}`;
2441
+ if (current !== expected) {
2442
+ ctx.report({
2443
+ rule: "contracts-stale",
2444
+ file: out,
2445
+ message: current === null ? `doesn't exist; run ${command} and commit it` : `is out of date with the database; run ${command} and commit the result`
2446
+ });
2447
+ }
2448
+ }
2449
+ var DEFAULT_CONTRACT_OUT, DEFAULT_DATABASE_ENV, shellArg, postgresSource, lf;
2450
+ var init_contracts = __esm({
2451
+ "src/doctor/contracts.ts"() {
2452
+ DEFAULT_CONTRACT_OUT = "resources.genesis.ts";
2453
+ DEFAULT_DATABASE_ENV = "DATABASE_URL";
2454
+ shellArg = (s) => /^[\w./,@:+=-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
2455
+ postgresSource = (schemas) => `Postgres (${schemas.join(", ")})`;
2456
+ lf = (text) => text.replace(/\r\n/g, "\n");
2014
2457
  }
2015
2458
  });
2016
2459
  function buildCommands(root, config) {
2017
2460
  if (config.build) return config.build;
2018
- const pkgFile = path23.join(root, "package.json");
2461
+ const pkgFile = path26.join(root, "package.json");
2019
2462
  const scripts = existsSync(pkgFile) ? JSON.parse(readFileSync(pkgFile, "utf8")).scripts ?? {} : {};
2020
2463
  const pm = packageManager(root);
2021
2464
  return ["typecheck", "build"].filter((s) => scripts[s]).map((s) => `${pm} run ${s}`);
2022
2465
  }
2023
2466
  function packageManager(root) {
2024
- let dir = path23.resolve(root);
2467
+ let dir = path26.resolve(root);
2025
2468
  for (; ; ) {
2026
- if (existsSync(path23.join(dir, "pnpm-lock.yaml"))) return "pnpm";
2027
- if (existsSync(path23.join(dir, "bun.lock")) || existsSync(path23.join(dir, "bun.lockb"))) return "bun";
2028
- if (existsSync(path23.join(dir, "yarn.lock"))) return "yarn";
2029
- if (existsSync(path23.join(dir, "package-lock.json"))) return "npm";
2030
- const parent = path23.dirname(dir);
2469
+ if (existsSync(path26.join(dir, "pnpm-lock.yaml"))) return "pnpm";
2470
+ if (existsSync(path26.join(dir, "bun.lock")) || existsSync(path26.join(dir, "bun.lockb"))) return "bun";
2471
+ if (existsSync(path26.join(dir, "yarn.lock"))) return "yarn";
2472
+ if (existsSync(path26.join(dir, "package-lock.json"))) return "npm";
2473
+ const parent = path26.dirname(dir);
2031
2474
  if (parent === dir) return "npm";
2032
2475
  dir = parent;
2033
2476
  }
@@ -2084,7 +2527,7 @@ function globToRegExp(glob) {
2084
2527
  }
2085
2528
  function globMatcher(globs) {
2086
2529
  const res = (globs ?? []).filter((g) => g.trim()).map(globToRegExp);
2087
- return (path37) => res.some((re) => re.test(path37));
2530
+ return (path41) => res.some((re) => re.test(path41));
2088
2531
  }
2089
2532
  var init_glob = __esm({
2090
2533
  "src/doctor/glob.ts"() {
@@ -2261,9 +2704,9 @@ function scanFiles(root, config) {
2261
2704
  const files = [];
2262
2705
  const seen = /* @__PURE__ */ new Set();
2263
2706
  const visit = (abs) => {
2264
- const rel = toPosix(path23.relative(root, abs));
2707
+ const rel = toPosix(path26.relative(root, abs));
2265
2708
  if (seen.has(rel) || ignored(rel)) return;
2266
- const ext = path23.extname(abs);
2709
+ const ext = path26.extname(abs);
2267
2710
  if (!extensions.has(ext)) return;
2268
2711
  if (statSync(abs).size > MAX_FILE_BYTES) return;
2269
2712
  seen.add(rel);
@@ -2273,14 +2716,14 @@ function scanFiles(root, config) {
2273
2716
  const walk2 = (dir) => {
2274
2717
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
2275
2718
  if (entry.isDirectory()) {
2276
- if (!SKIP_DIRS.has(entry.name)) walk2(path23.join(dir, entry.name));
2719
+ if (!SKIP_DIRS.has(entry.name)) walk2(path26.join(dir, entry.name));
2277
2720
  } else if (entry.isFile()) {
2278
- visit(path23.join(dir, entry.name));
2721
+ visit(path26.join(dir, entry.name));
2279
2722
  }
2280
2723
  }
2281
2724
  };
2282
2725
  for (const src of config.src ?? (config.packs?.includes("native") ? DEFAULT_NATIVE_SRC : DEFAULT_SRC)) {
2283
- const abs = path23.resolve(root, src);
2726
+ const abs = path26.resolve(root, src);
2284
2727
  if (!existsSync(abs)) continue;
2285
2728
  if (statSync(abs).isDirectory()) walk2(abs);
2286
2729
  else visit(abs);
@@ -2319,7 +2762,7 @@ var init_scan = __esm({
2319
2762
  ];
2320
2763
  SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", "coverage"]);
2321
2764
  MAX_FILE_BYTES = 2 * 1024 * 1024;
2322
- toPosix = (p) => p.split(path23.sep).join("/");
2765
+ toPosix = (p) => p.split(path26.sep).join("/");
2323
2766
  }
2324
2767
  });
2325
2768
  function parseRulesMarkdown(markdown) {
@@ -2336,12 +2779,13 @@ function parseRulesMarkdown(markdown) {
2336
2779
  current = null;
2337
2780
  continue;
2338
2781
  }
2339
- const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message):\s*(.*)$/);
2782
+ const kv = current && line.match(/^-\s+(level|files|exclude|forbid|require|path|message|newOnly):\s*(.*)$/);
2340
2783
  if (!current || !kv) continue;
2341
2784
  const [, key2, raw] = kv;
2342
2785
  const value = raw.trim();
2343
2786
  if (key2 === "files" || key2 === "exclude") current[key2] = value.split(",").map((s) => s.trim()).filter(Boolean);
2344
2787
  else if (key2 === "level") current.level = value;
2788
+ else if (key2 === "newOnly") current.newOnly = value === "true" ? true : value === "false" ? false : value;
2345
2789
  else current[key2] = value;
2346
2790
  }
2347
2791
  return rules;
@@ -2360,6 +2804,9 @@ function compilePatternRules(rules, source) {
2360
2804
  if (!["error", "warn", "info", "guide"].includes(level)) {
2361
2805
  throw new DoctorConfigError(`${source}: rule "${rule.id}" has level "${level}" (use error, warn, info or guide)`);
2362
2806
  }
2807
+ if (rule.newOnly !== void 0 && typeof rule.newOnly !== "boolean") {
2808
+ throw new DoctorConfigError(`${source}: rule "${rule.id}" has newOnly "${String(rule.newOnly)}" (use true or false)`);
2809
+ }
2363
2810
  if (level === "guide") continue;
2364
2811
  if (!rule.files?.length) throw new DoctorConfigError(`${source}: rule "${rule.id}" needs "files" (or level: guide)`);
2365
2812
  if (!rule.forbid && !rule.require && !rule.path) {
@@ -2385,7 +2832,7 @@ function loadPatternRules(root, patterns, rulesDoc) {
2385
2832
  const compiled = compilePatternRules(patterns ?? [], "doctor.patterns");
2386
2833
  let all = compiled;
2387
2834
  if (rulesDoc) {
2388
- const file = path23.resolve(root, rulesDoc);
2835
+ const file = path26.resolve(root, rulesDoc);
2389
2836
  if (!existsSync(file)) throw new DoctorConfigError(`doctor.rulesDoc: ${rulesDoc} not found`);
2390
2837
  const fromDoc = compilePatternRules(parseRulesMarkdown(readFileSync(file, "utf8")), rulesDoc);
2391
2838
  const clash = fromDoc.find((d) => compiled.some((c) => c.rule.id === d.rule.id));
@@ -2395,6 +2842,8 @@ function loadPatternRules(root, patterns, rulesDoc) {
2395
2842
  if (all.length === 0) return null;
2396
2843
  return {
2397
2844
  count: all.length,
2845
+ ids: all.map((r) => r.rule.id),
2846
+ newOnly: all.filter((r) => r.rule.newOnly).map((r) => r.rule.id),
2398
2847
  plugin: {
2399
2848
  name: "patterns",
2400
2849
  check(ctx) {
@@ -2451,14 +2900,14 @@ async function loadPlugins(specs, configDir) {
2451
2900
  }
2452
2901
  function resolvePlugin(id, configDir) {
2453
2902
  try {
2454
- if (id.startsWith(".") || path23.isAbsolute(id)) return resolveFrom(path23.resolve(configDir, id), configDir);
2903
+ if (id.startsWith(".") || path26.isAbsolute(id)) return resolveFrom(path26.resolve(configDir, id), configDir);
2455
2904
  return resolveFrom(id, configDir);
2456
2905
  } catch {
2457
2906
  throw new DoctorConfigError(`doctor.plugins: cannot find ${id} (relative paths resolve from ${configDir})`);
2458
2907
  }
2459
2908
  }
2460
2909
  function resolveFrom(id, from) {
2461
- return createRequire(path23.join(from, "noop.js")).resolve(id);
2910
+ return createRequire(path26.join(from, "noop.js")).resolve(id);
2462
2911
  }
2463
2912
  var init_plugins = __esm({
2464
2913
  "src/doctor/plugins.ts"() {
@@ -2476,7 +2925,7 @@ function importSpecifiers(file) {
2476
2925
  }
2477
2926
  function checkProjectLayout(ctx) {
2478
2927
  for (const dir of ctx.config.localPrimitiveDirs ?? DEFAULT_LOCAL_PRIMITIVE_DIRS) {
2479
- if (existsSync(path23.join(ctx.root, dir))) {
2928
+ if (existsSync(path26.join(ctx.root, dir))) {
2480
2929
  ctx.report({
2481
2930
  rule: "local-primitives",
2482
2931
  file: dir,
@@ -2486,7 +2935,7 @@ function checkProjectLayout(ctx) {
2486
2935
  }
2487
2936
  }
2488
2937
  for (const file of STARTER_LEFTOVERS) {
2489
- if (existsSync(path23.join(ctx.root, file))) {
2938
+ if (existsSync(path26.join(ctx.root, file))) {
2490
2939
  ctx.report({
2491
2940
  rule: "starter-leftover",
2492
2941
  level: "warn",
@@ -2573,7 +3022,7 @@ function checkTokens(ctx) {
2573
3022
  }
2574
3023
  for (const pattern of ctx.config.tokenFiles ?? []) {
2575
3024
  if (/[*?]/.test(pattern)) continue;
2576
- const abs = path23.join(ctx.root, pattern);
3025
+ const abs = path26.join(ctx.root, pattern);
2577
3026
  if (!ctx.files.some((f) => f.absolutePath === abs) && existsSync(abs)) {
2578
3027
  for (const t of declaredTokens(readFileSync(abs, "utf8"))) defined.add(t);
2579
3028
  }
@@ -2669,7 +3118,19 @@ var init_rules = __esm({
2669
3118
  "package-unversioned-change",
2670
3119
  "package-export-missing",
2671
3120
  "package-block-invalid",
2672
- "package-untagged-tests"
3121
+ "package-untagged-tests",
3122
+ "package-doctor-declaration",
3123
+ // package rules (package-rules.ts): the rules themselves are namespaced, e.g. ui/lists-use-resource-view
3124
+ "package-rules-invalid",
3125
+ "package-rule-override",
3126
+ // ratchet (ratchet.ts)
3127
+ "ratchet-skipped",
3128
+ "allow-grew",
3129
+ "rules-weakened",
3130
+ // agent guide (primitives.ts)
3131
+ "agent-guide-stale",
3132
+ // supabase pack: contracts (contracts.ts)
3133
+ "contracts-stale"
2673
3134
  ];
2674
3135
  DEFAULT_LOCAL_PRIMITIVE_DIRS = ["src/components/ui"];
2675
3136
  STARTER_LEFTOVERS = ["components.json", "src/lib/utils.ts"];
@@ -2753,19 +3214,34 @@ var init_expo = __esm({
2753
3214
  });
2754
3215
  }
2755
3216
  });
3217
+ function resolveLocal(root, fromFile, spec) {
3218
+ const bases = spec.startsWith(".") ? [path26.resolve(path26.dirname(fromFile), spec)] : [path26.join(root, spec.slice(2)), path26.join(root, "src", spec.slice(2))];
3219
+ for (const base of bases) {
3220
+ const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path26.join(base, `index${e}`))].find(
3221
+ (p) => SCRIPT_EXTS2.has(path26.extname(p)) && existsSync(p)
3222
+ );
3223
+ if (hit) return hit;
3224
+ }
3225
+ return null;
3226
+ }
2756
3227
  function localImports(root, file) {
2757
3228
  const out = [];
2758
3229
  for (const m of file.code.matchAll(/\bfrom\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g)) {
2759
- const spec = m[1];
2760
- const bases = spec.startsWith(".") ? [path23.resolve(path23.dirname(file.absolutePath), spec)] : [path23.join(root, spec.slice(2)), path23.join(root, "src", spec.slice(2))];
2761
- for (const base of bases) {
2762
- const hit = [base, ...RESOLVE_EXTS.map((e) => base + e), ...RESOLVE_EXTS.map((e) => path23.join(base, `index${e}`))].find(
2763
- (p) => SCRIPT_EXTS2.has(path23.extname(p)) && existsSync(p)
2764
- );
2765
- if (hit) {
2766
- out.push(hit);
2767
- break;
2768
- }
3230
+ const hit = resolveLocal(root, file.absolutePath, m[1]);
3231
+ if (hit) out.push(hit);
3232
+ }
3233
+ return out;
3234
+ }
3235
+ function localImportedNames(root, file) {
3236
+ const out = /* @__PURE__ */ new Map();
3237
+ const re = /\bimport\s+(?:type\s+)?([\w$]+)?\s*,?\s*(?:\{([^}]*)\})?\s*from\s*["']((?:\.{1,2}|[@~])\/[^"']+)["']/g;
3238
+ for (const m of file.code.matchAll(re)) {
3239
+ const target = resolveLocal(root, file.absolutePath, m[3]);
3240
+ if (!target) continue;
3241
+ if (m[1]) out.set(m[1], { file: target, name: "default" });
3242
+ for (const part of (m[2] ?? "").split(",")) {
3243
+ const [imported, local] = part.trim().replace(/^type\s+/, "").split(/\s+as\s+/);
3244
+ if (imported) out.set(local ?? imported, { file: target, name: imported });
2769
3245
  }
2770
3246
  }
2771
3247
  return out;
@@ -2923,7 +3399,7 @@ function checkCustomHeaders(ctx, pkg) {
2923
3399
  if (!JSX_EXTS3.has(file.ext)) continue;
2924
3400
  const code = file.code;
2925
3401
  const hidden = HIDES_HEADER.exec(code);
2926
- if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path23.posix.dirname(file.path), file.path);
3402
+ if (hidden && /(?:^|\/)_layout\.[jt]sx$/.test(file.path)) hidingLayouts.set(path26.posix.dirname(file.path), file.path);
2927
3403
  const own = hidden ? ownHeader(code, pkg) : null;
2928
3404
  if (hidden && own) {
2929
3405
  reported.add(file.path);
@@ -2951,7 +3427,7 @@ function checkCustomHeaders(ctx, pkg) {
2951
3427
  }
2952
3428
  for (const file of ctx.files) {
2953
3429
  if (!JSX_EXTS3.has(file.ext) || reported.has(file.path) || !file.path.startsWith(`${rootDir}/`) || NON_SCREEN_ROUTE.test(file.path)) continue;
2954
- const layout = hidingLayouts.get(path23.posix.dirname(file.path));
3430
+ const layout = hidingLayouts.get(path26.posix.dirname(file.path));
2955
3431
  const own = layout ? ownHeader(file.code, pkg) : null;
2956
3432
  if (!layout || !own) continue;
2957
3433
  ctx.report({
@@ -2972,13 +3448,13 @@ function isLoadingOnlyRoute(code) {
2972
3448
  }
2973
3449
  function routerRoot(ctx) {
2974
3450
  if (ctx.config.native?.routerRoot) return ctx.config.native.routerRoot.replace(/\/+$/, "");
2975
- return existsSync(path23.join(ctx.root, "src", "app")) ? "src/app" : "app";
3451
+ return existsSync(path26.join(ctx.root, "src", "app")) ? "src/app" : "app";
2976
3452
  }
2977
3453
  function checkScreenLayouts(ctx, pkg) {
2978
3454
  const layouts = nativeLayouts(pkg);
2979
3455
  if (layouts.length === 0) return;
2980
3456
  const rootDir = routerRoot(ctx);
2981
- if (!existsSync(path23.join(ctx.root, rootDir))) {
3457
+ if (!existsSync(path26.join(ctx.root, rootDir))) {
2982
3458
  ctx.report({ rule: "native-screen-layout", level: "warn", file: rootDir, message: `no Expo Router root at ${rootDir}; set doctor.native.routerRoot` });
2983
3459
  return;
2984
3460
  }
@@ -3015,7 +3491,7 @@ function checkScreenLayouts(ctx, pkg) {
3015
3491
  function readExpoConfigs(root) {
3016
3492
  const out = [];
3017
3493
  for (const name of EXPO_CONFIGS) {
3018
- const abs = path23.join(root, name);
3494
+ const abs = path26.join(root, name);
3019
3495
  if (!existsSync(abs)) continue;
3020
3496
  const text = readFileSync(abs, "utf8");
3021
3497
  let json = null;
@@ -3049,13 +3525,13 @@ function pluginOptions(json, module) {
3049
3525
  return null;
3050
3526
  }
3051
3527
  function dependencies(root) {
3052
- const file = path23.join(root, "package.json");
3528
+ const file = path26.join(root, "package.json");
3053
3529
  if (!existsSync(file)) return /* @__PURE__ */ new Set();
3054
3530
  const pkg = JSON.parse(readFileSync(file, "utf8"));
3055
3531
  return /* @__PURE__ */ new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
3056
3532
  }
3057
3533
  function runtimeDependencies(root) {
3058
- const file = path23.join(root, "package.json");
3534
+ const file = path26.join(root, "package.json");
3059
3535
  if (!existsSync(file)) return {};
3060
3536
  return JSON.parse(readFileSync(file, "utf8")).dependencies ?? {};
3061
3537
  }
@@ -3467,14 +3943,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3467
3943
  seen.add(file);
3468
3944
  const json = readJsonc(file);
3469
3945
  if (!json) return {};
3470
- const dir = path23.dirname(file);
3946
+ const dir = path26.dirname(file);
3471
3947
  let merged = {};
3472
3948
  const parents = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
3473
3949
  for (const ext of parents) {
3474
3950
  if (typeof ext !== "string") continue;
3475
3951
  let target = null;
3476
- if (ext.startsWith(".") || path23.isAbsolute(ext)) {
3477
- const abs = path23.resolve(dir, ext);
3952
+ if (ext.startsWith(".") || path26.isAbsolute(ext)) {
3953
+ const abs = path26.resolve(dir, ext);
3478
3954
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3479
3955
  } else {
3480
3956
  const parts = ext.split("/");
@@ -3482,14 +3958,14 @@ function readTsconfig(root, file, seen = /* @__PURE__ */ new Set()) {
3482
3958
  const pkgDir = findPackageDir(root, parts.slice(0, nameLength).join("/"));
3483
3959
  if (pkgDir) {
3484
3960
  const sub = parts.slice(nameLength).join("/");
3485
- const abs = path23.join(pkgDir, sub || "tsconfig.json");
3961
+ const abs = path26.join(pkgDir, sub || "tsconfig.json");
3486
3962
  target = existsSync(abs) && statSync(abs).isFile() ? abs : existsSync(`${abs}.json`) ? `${abs}.json` : null;
3487
3963
  }
3488
3964
  }
3489
3965
  if (target) merged = { ...merged, ...readTsconfig(root, target, seen) };
3490
3966
  }
3491
3967
  const opts = json.compilerOptions ?? {};
3492
- if (typeof opts.baseUrl === "string") merged.baseUrl = path23.resolve(dir, opts.baseUrl);
3968
+ if (typeof opts.baseUrl === "string") merged.baseUrl = path26.resolve(dir, opts.baseUrl);
3493
3969
  if (opts.paths && typeof opts.paths === "object") {
3494
3970
  merged.paths = opts.paths;
3495
3971
  merged.pathsDir = dir;
@@ -3500,7 +3976,7 @@ function aliases(root) {
3500
3976
  const table = [];
3501
3977
  let baseUrl = null;
3502
3978
  for (const name of ["tsconfig.json", "tsconfig.app.json", "jsconfig.json"]) {
3503
- const file = path23.join(root, name);
3979
+ const file = path26.join(root, name);
3504
3980
  if (!existsSync(file)) continue;
3505
3981
  const config = readTsconfig(root, file);
3506
3982
  baseUrl ??= config.baseUrl ?? null;
@@ -3508,22 +3984,22 @@ function aliases(root) {
3508
3984
  for (const [pattern, targets] of Object.entries(config.paths ?? {})) {
3509
3985
  if (!Array.isArray(targets)) continue;
3510
3986
  const exact = !pattern.endsWith("*");
3511
- table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path23.join(base, String(t).replace(/\*$/, ""))) });
3987
+ table.push({ prefix: pattern.replace(/\*$/, ""), exact, targets: targets.map((t) => path26.join(base, String(t).replace(/\*$/, ""))) });
3512
3988
  }
3513
3989
  }
3514
- const pkg = readJsonc(path23.join(root, "package.json"));
3990
+ const pkg = readJsonc(path26.join(root, "package.json"));
3515
3991
  for (const [pattern, target] of Object.entries(pkg?.imports ?? {})) {
3516
3992
  if (typeof target !== "string") continue;
3517
- table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path23.join(root, target.replace(/\*.*$/, ""))] });
3993
+ table.push({ prefix: pattern.replace(/\*.*$/, ""), exact: !pattern.includes("*"), targets: [path26.join(root, target.replace(/\*.*$/, ""))] });
3518
3994
  }
3519
- for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path23.join(root, "src") + path23.sep, root + path23.sep] });
3995
+ for (const prefix of ["@/", "~/", "#/"]) table.push({ prefix, exact: false, targets: [path26.join(root, "src") + path26.sep, root + path26.sep] });
3520
3996
  return { table, baseUrl };
3521
3997
  }
3522
3998
  function resolveFile(base) {
3523
- const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path23.join(base, `index${e}`))];
3999
+ const tries = [base, ...RESOLVE_EXTS2.map((e) => base + e), ...RESOLVE_EXTS2.map((e) => path26.join(base, `index${e}`))];
3524
4000
  if (/\.[mc]?js$/.test(base)) tries.push(...[".ts", ".tsx"].map((e) => base.replace(/\.[mc]?js$/, e)));
3525
4001
  for (const p of tries) {
3526
- if (SCRIPT_EXTS2.has(path23.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
4002
+ if (SCRIPT_EXTS2.has(path26.extname(p)) && existsSync(p) && statSync(p).isFile()) return p;
3527
4003
  }
3528
4004
  return null;
3529
4005
  }
@@ -3536,13 +4012,13 @@ function createTrail(ctx) {
3536
4012
  const { table, baseUrl } = aliases(ctx.root);
3537
4013
  let declared = null;
3538
4014
  try {
3539
- const pkg = JSON.parse(readFileSync(path23.join(ctx.root, "package.json"), "utf8"));
4015
+ const pkg = JSON.parse(readFileSync(path26.join(ctx.root, "package.json"), "utf8"));
3540
4016
  declared = new Set(["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => Object.keys(pkg[k] ?? {})));
3541
4017
  } catch {
3542
4018
  declared = null;
3543
4019
  }
3544
4020
  const byPath = new Map(ctx.files.map((f) => [f.absolutePath, f]));
3545
- const read = (abs) => byPath.get(abs) ?? readSource(abs);
4021
+ const read2 = (abs) => byPath.get(abs) ?? readSource(abs);
3546
4022
  const importsCache = /* @__PURE__ */ new Map();
3547
4023
  const importsOf = (file) => {
3548
4024
  const hit = importsCache.get(file.absolutePath);
@@ -3567,17 +4043,17 @@ function createTrail(ctx) {
3567
4043
  if (/^(?:node:|https?:|data:|virtual:)/.test(spec) || /\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|json|md|mdx)(?:\?.*)?$/.test(spec)) continue;
3568
4044
  let resolved = null;
3569
4045
  if (spec.startsWith(".")) {
3570
- resolved = resolveFile(path23.resolve(path23.dirname(file.absolutePath), spec));
4046
+ resolved = resolveFile(path26.resolve(path26.dirname(file.absolutePath), spec));
3571
4047
  if (!resolved) lost = true;
3572
4048
  } else {
3573
4049
  const alias = table.find((a) => a.exact ? spec === a.prefix : spec.startsWith(a.prefix));
3574
4050
  if (alias) {
3575
4051
  for (const t of alias.targets) {
3576
- resolved = resolveFile(alias.exact ? t : path23.join(t, spec.slice(alias.prefix.length)));
4052
+ resolved = resolveFile(alias.exact ? t : path26.join(t, spec.slice(alias.prefix.length)));
3577
4053
  if (resolved) break;
3578
4054
  }
3579
4055
  }
3580
- if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path23.join(baseUrl, spec));
4056
+ if (!resolved && baseUrl && !spec.startsWith("#")) resolved = resolveFile(path26.join(baseUrl, spec));
3581
4057
  if (!resolved) {
3582
4058
  const pkg = spec.split("/").slice(0, spec.startsWith("@") ? 2 : 1).join("/");
3583
4059
  if (spec.startsWith("#") || declared && !declared.has(pkg) && !findPackageDir(ctx.root, pkg)) lost = true;
@@ -3619,7 +4095,7 @@ function createTrail(ctx) {
3619
4095
  cut.add(abs);
3620
4096
  continue;
3621
4097
  }
3622
- const target = read(abs);
4098
+ const target = read2(abs);
3623
4099
  if (!target) {
3624
4100
  unknown = true;
3625
4101
  continue;
@@ -3632,41 +4108,546 @@ function createTrail(ctx) {
3632
4108
  }
3633
4109
  if (r === "unknown") unknown = true;
3634
4110
  }
3635
- seen.delete(file.absolutePath);
3636
- cut.delete(file.absolutePath);
4111
+ seen.delete(file.absolutePath);
4112
+ cut.delete(file.absolutePath);
4113
+ }
4114
+ if (result === "no" && unknown) result = "unknown";
4115
+ }
4116
+ if (result === "yes" || cut.size === 0) {
4117
+ cache2.free.set(k, result);
4118
+ return [result, /* @__PURE__ */ new Set()];
4119
+ }
4120
+ const entries = cache2.cut.get(k) ?? [];
4121
+ entries.push({ cut: [...cut], result });
4122
+ cache2.cut.set(k, entries);
4123
+ return [result, cut];
4124
+ };
4125
+ return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
4126
+ }
4127
+ var TRAIL_DEPTH, RESOLVE_EXTS2, IMPORT_FROM, EXPORT_FROM, DYNAMIC, trails;
4128
+ var init_trail = __esm({
4129
+ "src/doctor/trail.ts"() {
4130
+ init_genesis();
4131
+ init_source();
4132
+ TRAIL_DEPTH = 6;
4133
+ RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
4134
+ IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
4135
+ EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
4136
+ DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
4137
+ trails = /* @__PURE__ */ new WeakMap();
4138
+ }
4139
+ });
4140
+ function routesDir(ctx) {
4141
+ if (ctx.config.routesDir) return ctx.config.routesDir;
4142
+ return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path26.join(ctx.root, d))) ?? null;
4143
+ }
4144
+ function flavorOf(dir, rels) {
4145
+ const stems = rels.map((r) => r.split("/").pop());
4146
+ if (stems.includes("__root")) return "tanstack";
4147
+ if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
4148
+ if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
4149
+ return "tanstack";
4150
+ }
4151
+ function renders(code) {
4152
+ const elements = renderedElements(code);
4153
+ if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
4154
+ const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
4155
+ const named = COMPONENT_OPTION.exec(code)?.[1];
4156
+ if (named && !definedHere(named)) return true;
4157
+ if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
4158
+ const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
4159
+ return exported !== void 0 && !definedHere(exported);
4160
+ }
4161
+ function webRoutes(ctx) {
4162
+ const dir = routesDir(ctx);
4163
+ if (!dir) return [];
4164
+ const candidates = ctx.files.filter((f) => JSX_EXTS2.has(f.ext) && f.path.startsWith(`${dir}/`)).map((file) => ({ file, rel: file.path.slice(dir.length + 1).replace(/\.[^.]+$/, "") }));
4165
+ const flavor = flavorOf(dir, candidates.map((c) => c.rel));
4166
+ const stems = STEMS[flavor];
4167
+ const groups = /* @__PURE__ */ new Map();
4168
+ for (const { file, rel } of candidates) {
4169
+ const parts = rel.split("/");
4170
+ if (parts.some((p) => p.startsWith("-"))) continue;
4171
+ if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
4172
+ if (flavor === "next-pages" && parts[0] === "api") continue;
4173
+ if (stems.skip.test(parts.at(-1))) continue;
4174
+ if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
4175
+ const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
4176
+ groups.set(id, [...groups.get(id) ?? [], file]);
4177
+ }
4178
+ const trail = trailFor(ctx);
4179
+ const routes = [];
4180
+ for (const [id, files] of groups) {
4181
+ const parts = id.split("/");
4182
+ const stem = parts.pop();
4183
+ const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
4184
+ const named = stems.layout.has(stem) || stems.index.has(stem);
4185
+ const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
4186
+ const segments = [...folders, ...own];
4187
+ const tree = [...parts, ...own];
4188
+ let index = stems.index.has(stem);
4189
+ if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
4190
+ segments.pop();
4191
+ tree.pop();
4192
+ index = true;
4193
+ }
4194
+ const code = files.map((f) => f.code).join("\n");
4195
+ const elements = renderedElements(code);
4196
+ const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
4197
+ const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
4198
+ const layout = stems.layout.has(stem) || pathless || outlet;
4199
+ const rendering = renders(code);
4200
+ const ownContent = new RegExp(OWN_CONTENT).test(code);
4201
+ const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
4202
+ const page = !pure && !pathless && (!layout || ownContent);
4203
+ routes.push({
4204
+ file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
4205
+ files,
4206
+ segments,
4207
+ tree,
4208
+ index,
4209
+ layout,
4210
+ page,
4211
+ detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
4212
+ redirectOnly: !rendering,
4213
+ parents: []
4214
+ });
4215
+ }
4216
+ for (const r of routes) {
4217
+ const own = r.tree;
4218
+ for (const p of routes) {
4219
+ if (p === r || !p.layout) continue;
4220
+ const n = p.tree.length;
4221
+ if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
4222
+ if (key(own.slice(0, n)) !== key(p.tree)) continue;
4223
+ if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
4224
+ r.parents.push(p);
4225
+ }
4226
+ r.parents.sort((a, b) => b.tree.length - a.tree.length);
4227
+ }
4228
+ return routes;
4229
+ }
4230
+ var ROUTES_DIR_CANDIDATES, STEMS, NON_PAGE_ELEMENTS, HTML_ELEMENT, COMPONENT_OPTION, RENDERS_OUTLET, OWN_CONTENT, key;
4231
+ var init_routes = __esm({
4232
+ "src/doctor/routes.ts"() {
4233
+ init_source();
4234
+ init_trail();
4235
+ ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
4236
+ STEMS = {
4237
+ tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
4238
+ "next-app": {
4239
+ layout: /* @__PURE__ */ new Set(["layout"]),
4240
+ index: /* @__PURE__ */ new Set(["page"]),
4241
+ skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
4242
+ },
4243
+ "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
4244
+ };
4245
+ NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
4246
+ HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
4247
+ COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
4248
+ RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
4249
+ OWN_CONTENT = /(?<![=-])>\s*[A-Za-z][^<>{}]*</.source + "|" + /(?<![\w$.])<(?:h[1-6]|ul|ol|table|dl|H[1-6]|[A-Z]\w*(?:Heading|Title|Table|List|Grid))(?=[\s>/])/.source;
4250
+ key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
4251
+ }
4252
+ });
4253
+ function ruleNamespace(packageName3) {
4254
+ const m = GENESIS.exec(packageName3);
4255
+ if (m) return m[1] ?? "genesis";
4256
+ return packageName3;
4257
+ }
4258
+ function toRegExp2(source, flags = "") {
4259
+ if (source.startsWith("(?i)")) return new RegExp(source.slice(4), flags + "i");
4260
+ return new RegExp(source, flags);
4261
+ }
4262
+ function validateDeclaration(raw, packageName3, packageDir2, ignored) {
4263
+ const fail = (msg) => {
4264
+ throw new PackageDeclarationError(`${packageName3}: genesis.doctor ${msg}`);
4265
+ };
4266
+ const unknownKey = (where2, key2, known) => {
4267
+ const msg = `${where2 ? `${where2} ` : ""}has an unknown key "${key2}"${known ? ` (known: ${[...known].filter((k) => k !== "$comment").join(", ")})` : ""}`;
4268
+ if (!ignored) return fail(msg);
4269
+ ignored.push(`${packageName3}: genesis.doctor ${msg}; ignored`);
4270
+ };
4271
+ const each = (list, check) => list.flatMap((item, i) => {
4272
+ if (!ignored) return [check(item, i)];
4273
+ try {
4274
+ return [check(item, i)];
4275
+ } catch (err) {
4276
+ if (!(err instanceof PackageDeclarationError)) throw err;
4277
+ ignored.push(`${err.message}; that entry is skipped`);
4278
+ return [];
4279
+ }
4280
+ });
4281
+ if (typeof raw === "string") {
4282
+ if (!packageDir2) fail(`points at ${raw}, but the package folder is unknown`);
4283
+ const file = path26.resolve(packageDir2, raw);
4284
+ if (!inside(packageDir2, file)) fail(`points outside the package (${raw})`);
4285
+ if (!existsSync(file)) fail(`points at ${raw}, which doesn't exist (is it in package.json "files"?)`);
4286
+ let parsed;
4287
+ try {
4288
+ parsed = JSON.parse(readFileSync(file, "utf8"));
4289
+ } catch (err) {
4290
+ return fail(`file ${raw} is not valid JSON: ${err.message}`);
4291
+ }
4292
+ return validateDeclaration(parsed, packageName3, packageDir2, ignored);
4293
+ }
4294
+ if (raw === false) fail(`is false; say why with { "enforce": false, "reason": "\u2026" }`);
4295
+ if (!isObject3(raw)) fail(`must be an object (or a path to a JSON file in the package)`);
4296
+ const c = raw;
4297
+ for (const key2 of Object.keys(c)) if (!DECLARATION_KEYS.has(key2)) unknownKey("", key2, DECLARATION_KEYS);
4298
+ const enforce = c.enforce === void 0 ? true : c.enforce;
4299
+ if (typeof enforce !== "boolean") fail(`enforce must be true or false`);
4300
+ if (c.reason !== void 0 && (typeof c.reason !== "string" || !c.reason.trim())) fail(`reason must be a sentence`);
4301
+ const prefer = c.prefer === void 0 ? [] : c.prefer;
4302
+ if (!Array.isArray(prefer)) fail(`prefer must be a list`);
4303
+ const primitives = c.primitives === void 0 ? [] : c.primitives;
4304
+ if (!Array.isArray(primitives)) fail(`primitives must be a list`);
4305
+ if (c.plugin !== void 0 && (typeof c.plugin !== "string" || !c.plugin.trim())) fail(`plugin must be a module path inside the package`);
4306
+ if (!enforce) {
4307
+ if (typeof c.reason !== "string") fail(`turns enforcement off without a reason; add "reason"`);
4308
+ if (prefer.length || c.plugin) fail(`turns enforcement off but declares rules; drop "enforce": false or the rules`);
4309
+ } else if (!prefer.length && !c.plugin) {
4310
+ fail(`declares no rules; add "prefer" rules or a "plugin", or say { "enforce": false, "reason": "\u2026" }`);
4311
+ }
4312
+ const ids = /* @__PURE__ */ new Set();
4313
+ const rules = each(prefer, (r, i) => validatePrefer(r, `prefer[${i}]`, fail, unknownKey));
4314
+ for (const r of rules) {
4315
+ if (ids.has(r.id)) fail(`defines the rule "${r.id}" twice`);
4316
+ ids.add(r.id);
4317
+ }
4318
+ const entries = each(primitives, (p, i) => {
4319
+ const where2 = `primitives[${i}]`;
4320
+ if (!isObject3(p)) return fail(`${where2} must be an object`);
4321
+ for (const key2 of Object.keys(p)) if (!PRIMITIVE_KEYS.has(key2)) unknownKey(where2, key2);
4322
+ for (const key2 of ["need", "use"]) if (typeof p[key2] !== "string" || !p[key2].trim()) fail(`${where2} needs "${key2}"`);
4323
+ for (const key2 of ["import", "docs"]) if (p[key2] !== void 0 && typeof p[key2] !== "string") fail(`${where2}.${key2} must be a string`);
4324
+ return p;
4325
+ });
4326
+ let plugin;
4327
+ if (typeof c.plugin === "string") {
4328
+ if (!packageDir2) plugin = c.plugin;
4329
+ else {
4330
+ plugin = path26.resolve(packageDir2, c.plugin);
4331
+ if (!inside(packageDir2, plugin)) fail(`plugin points outside the package (${c.plugin})`);
4332
+ }
4333
+ }
4334
+ return {
4335
+ enforce,
4336
+ ...typeof c.reason === "string" ? { reason: c.reason } : {},
4337
+ prefer: rules,
4338
+ primitives: entries,
4339
+ ...plugin ? { plugin } : {}
4340
+ };
4341
+ }
4342
+ function validatePrefer(raw, where2, fail, unknownKey) {
4343
+ if (!isObject3(raw)) return fail(`${where2} must be an object`);
4344
+ const narrowing = (at2, key2, known) => fail(`${at2} has an unknown key "${key2}" (known: ${[...known].join(", ")})`);
4345
+ for (const key2 of Object.keys(raw)) if (!PREFER_KEYS.has(key2)) narrowing(where2, key2, PREFER_KEYS);
4346
+ if (typeof raw.id !== "string" || !ID.test(raw.id)) fail(`${where2} needs an "id" of lower-case words and dashes`);
4347
+ const at = `${where2} (${raw.id})`;
4348
+ for (const key2 of ["use", "why"]) if (typeof raw[key2] !== "string" || !raw[key2].trim()) fail(`${at} needs "${key2}"`);
4349
+ for (const key2 of ["need", "import", "docs"]) if (raw[key2] !== void 0 && typeof raw[key2] !== "string") fail(`${at}.${key2} must be a string`);
4350
+ if (raw.level !== void 0 && !LEVELS2.has(raw.level)) fail(`${at}.level must be "error", "warn" or "info"`);
4351
+ if (raw.platform !== void 0 && raw.platform !== "web" && raw.platform !== "native") fail(`${at}.platform must be "web" or "native"`);
4352
+ if (raw.newOnly !== void 0 && typeof raw.newOnly !== "boolean") fail(`${at}.newOnly must be true or false`);
4353
+ for (const key2 of ["files", "exclude"]) if (raw[key2] !== void 0 && !isStringList2(raw[key2])) fail(`${at}.${key2} must be a list of globs`);
4354
+ if (!isObject3(raw.forbid)) fail(`${at} needs "forbid": { jsx?, imports?, pattern? }`);
4355
+ const forbid = raw.forbid;
4356
+ for (const key2 of Object.keys(forbid)) if (!FORBID_KEYS.has(key2)) unknownKey(`${at}.forbid`, key2);
4357
+ if (!forbid.jsx && !forbid.imports && !forbid.pattern) fail(`${at}.forbid needs jsx, imports or pattern`);
4358
+ if (forbid.jsx !== void 0 && !(isStringList2(forbid.jsx) && forbid.jsx.every((n) => /^[A-Z][\w.]*$/.test(n)))) fail(`${at}.forbid.jsx must be a list of component names`);
4359
+ if (forbid.imports !== void 0 && !isStringList2(forbid.imports)) fail(`${at}.forbid.imports must be a list of import specifiers`);
4360
+ if (forbid.pattern !== void 0) checkPattern(forbid.pattern, `${at}.forbid.pattern`, fail);
4361
+ if (raw.unless !== void 0) {
4362
+ if (!isObject3(raw.unless)) fail(`${at}.unless must be an object`);
4363
+ const unless = raw.unless;
4364
+ for (const key2 of Object.keys(unless)) if (!UNLESS_KEYS.has(key2)) narrowing(`${at}.unless`, key2, UNLESS_KEYS);
4365
+ if (unless.renders !== void 0 && !isStringList2(unless.renders)) fail(`${at}.unless.renders must be a list of component names`);
4366
+ if (unless.pattern !== void 0) checkPattern(unless.pattern, `${at}.unless.pattern`, fail);
4367
+ }
4368
+ return raw;
4369
+ }
4370
+ function checkPattern(v, where2, fail) {
4371
+ if (typeof v !== "string" || !v) fail(`${where2} must be a regular expression`);
4372
+ try {
4373
+ toRegExp2(v, "g");
4374
+ } catch (err) {
4375
+ fail(`${where2} is not a valid regular expression: ${err.message}`);
4376
+ }
4377
+ }
4378
+ function readDeclaringPackage(dir, local) {
4379
+ const file = path26.join(dir, "package.json");
4380
+ let stamp;
4381
+ let real2;
4382
+ try {
4383
+ real2 = realpathSync(dir);
4384
+ stamp = `${real2}
4385
+ ${statSync(file).mtimeMs}
4386
+ ${local}`;
4387
+ } catch {
4388
+ return null;
4389
+ }
4390
+ const hit = discoveryCache.get(stamp);
4391
+ if (hit) return hit;
4392
+ let json;
4393
+ try {
4394
+ json = JSON.parse(readFileSync(file, "utf8"));
4395
+ } catch {
4396
+ return null;
4397
+ }
4398
+ if (typeof json.name !== "string" || !json.name) return null;
4399
+ const pkg = {
4400
+ name: json.name,
4401
+ version: typeof json.version === "string" ? json.version : "0.0.0",
4402
+ dir: path26.resolve(dir),
4403
+ namespace: ruleNamespace(json.name),
4404
+ local,
4405
+ private: json.private === true,
4406
+ declaration: null
4407
+ };
4408
+ const raw = json.genesis?.doctor;
4409
+ if (raw !== void 0) {
4410
+ const ignored = [];
4411
+ try {
4412
+ pkg.declaration = validateDeclaration(raw, json.name, path26.resolve(dir), ignored);
4413
+ if (ignored.length) pkg.ignored = ignored;
4414
+ } catch (err) {
4415
+ pkg.error = err.message;
4416
+ }
4417
+ }
4418
+ discoveryCache.set(stamp, pkg);
4419
+ return pkg;
4420
+ }
4421
+ function discoverPackages(root) {
4422
+ const byName = /* @__PURE__ */ new Map();
4423
+ const installed = [...installedGenesis(root).values()];
4424
+ for (const dir of installed) {
4425
+ const pkg = readDeclaringPackage(dir, false);
4426
+ if (pkg) byName.set(pkg.name, pkg);
4427
+ }
4428
+ for (const dir of installed) {
4429
+ let scope;
4430
+ try {
4431
+ scope = path26.dirname(realpathSync(dir));
4432
+ } catch {
4433
+ continue;
4434
+ }
4435
+ if (path26.basename(scope) !== "@marktiderman" || !existsSync(scope)) continue;
4436
+ for (const entry of readdirSync(scope)) {
4437
+ if (byName.has(`@marktiderman/${entry}`) || !GENESIS.test(`@marktiderman/${entry}`)) continue;
4438
+ const pkg = readDeclaringPackage(path26.join(scope, entry), false);
4439
+ if (pkg) byName.set(pkg.name, pkg);
4440
+ }
4441
+ }
4442
+ let local = [];
4443
+ try {
4444
+ local = localPackages(root);
4445
+ } catch {
4446
+ }
4447
+ for (const l of local) {
4448
+ const pkg = readDeclaringPackage(l.dir, true);
4449
+ if (pkg) byName.set(pkg.name, pkg);
4450
+ }
4451
+ return [...byName.values()].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
4452
+ }
4453
+ function clearPackageRulesCache() {
4454
+ discoveryCache.clear();
4455
+ }
4456
+ function preferRules(packages) {
4457
+ return packages.flatMap(
4458
+ (p) => (p.declaration?.prefer ?? []).map((r) => ({ ...r, ruleId: `${p.namespace}/${r.id}`, package: p.name, packageDir: p.dir }))
4459
+ );
4460
+ }
4461
+ function compile(rule, setting, routes) {
4462
+ const expand = (globs) => globs.flatMap((g) => {
4463
+ if (!g.includes("{routes}")) return [g];
4464
+ return routes ? [g.replaceAll("{routes}", routes)] : [];
4465
+ });
4466
+ const files = expand(setting?.files ?? rule.files ?? SCRIPT_GLOBS);
4467
+ if (files.length === 0) return null;
4468
+ return {
4469
+ rule,
4470
+ level: rule.level ?? "warn",
4471
+ includes: globMatcher(files),
4472
+ excludes: globMatcher(expand(setting?.exclude ?? rule.exclude ?? [])),
4473
+ jsx: new Set(rule.forbid.jsx ?? []),
4474
+ imports: (rule.forbid.imports ?? []).map(specMatcher),
4475
+ ...rule.forbid.pattern ? { pattern: toRegExp2(rule.forbid.pattern, "g") } : {},
4476
+ unlessRenders: new Set(rule.unless?.renders ?? []),
4477
+ ...rule.unless?.pattern ? { unlessPattern: toRegExp2(rule.unless.pattern) } : {}
4478
+ };
4479
+ }
4480
+ function messageFor(rule, found) {
4481
+ const from = rule.import ? ` (${rule.import})` : "";
4482
+ const docs = rule.docs ? ` See ${rule.docs}` : "";
4483
+ return `${found}; use ${rule.use}${from}. ${rule.why}${docs}`;
4484
+ }
4485
+ function wrappersIn(file, elements, c) {
4486
+ const out = /* @__PURE__ */ new Map();
4487
+ const decls = [...file.code.matchAll(TOP_LEVEL)];
4488
+ const listed = /* @__PURE__ */ new Map();
4489
+ for (const m of file.code.matchAll(EXPORT_LIST)) {
4490
+ for (const part of m[1].split(",")) {
4491
+ const [local, exported] = part.trim().split(/\s+as\s+/);
4492
+ if (local) listed.set(local, [...listed.get(local) ?? [], exported ?? local]);
4493
+ }
4494
+ }
4495
+ for (const m of file.code.matchAll(EXPORT_DEFAULT_NAME)) listed.set(m[1], [...listed.get(m[1]) ?? [], "default"]);
4496
+ decls.forEach((d, i) => {
4497
+ const name = d[3];
4498
+ if (!/^[A-Z]/.test(name) || c.jsx.has(name)) return;
4499
+ const end = decls[i + 1]?.index ?? file.code.length;
4500
+ const hit = elements.find((m) => m.index > d.index && m.index < end && c.jsx.has(m[1]));
4501
+ if (!hit) return;
4502
+ const names = [...d[1] ? [d[2] ? "default" : name] : [], ...listed.get(name) ?? []];
4503
+ for (const n of names) out.set(n, hit[1]);
4504
+ });
4505
+ return out;
4506
+ }
4507
+ function runPrefer(ctx, c) {
4508
+ const own = c.rule.packageDir;
4509
+ const checked = ctx.files.filter((file) => SCRIPT.has(file.ext) && c.includes(file.path) && !c.excludes(file.path) && !inside(own, file.absolutePath));
4510
+ const exempt = (file, rendered) => rendered.some((n) => c.unlessRenders.has(n)) || (c.unlessPattern?.test(file.code) ?? false);
4511
+ const wrappers = /* @__PURE__ */ new Map();
4512
+ const renderedBy = /* @__PURE__ */ new Map();
4513
+ for (const file of checked) {
4514
+ if (!JSX.has(file.ext)) continue;
4515
+ const elements = [...file.code.matchAll(ELEMENT)];
4516
+ renderedBy.set(file, elements);
4517
+ if (!c.jsx.size || exempt(file, elements.map((m) => m[1]))) continue;
4518
+ const found = wrappersIn(file, elements, c);
4519
+ if (found.size) wrappers.set(file.absolutePath, found);
4520
+ }
4521
+ for (const file of checked) {
4522
+ const elements = renderedBy.get(file) ?? [];
4523
+ if (exempt(file, elements.map((m) => m[1]))) continue;
4524
+ const report = (line, subject, found) => ctx.report({ rule: c.rule.ruleId, level: c.level, file: file.path, line, subject, message: messageFor(c.rule, found) });
4525
+ const imported = wrappers.size && elements.length ? localImportedNames(ctx.root, file) : null;
4526
+ for (const m of elements) {
4527
+ const name = m[1];
4528
+ if (c.jsx.has(name)) {
4529
+ report(lineAt(file.code, m.index), name, `renders <${name}>`);
4530
+ continue;
4531
+ }
4532
+ const from = imported?.get(name.split(".")[0]);
4533
+ const around = from && !name.includes(".") ? wrappers.get(from.file)?.get(from.name) : void 0;
4534
+ if (around) report(lineAt(file.code, m.index), name, `renders <${name}>, an app wrapper around <${around}>`);
4535
+ }
4536
+ if (c.imports.length) {
4537
+ for (const { specifier, line } of importSpecifiers(file)) {
4538
+ if (c.imports.some((t) => t(specifier))) report(line, specifier, `imports ${specifier}`);
4539
+ }
4540
+ }
4541
+ if (c.pattern) {
4542
+ c.pattern.lastIndex = 0;
4543
+ for (const m of file.code.matchAll(c.pattern)) {
4544
+ const text = m[0].trim().replace(/\s+/g, " ").slice(0, 60);
4545
+ report(lineAt(file.code, m.index), text, `has ${text}`);
4546
+ }
4547
+ }
4548
+ }
4549
+ }
4550
+ async function packageRulesPlugins(packages) {
4551
+ const out = [
4552
+ {
4553
+ name: "package-rules",
4554
+ check(ctx) {
4555
+ for (const p of packages) {
4556
+ const at = { rule: "package-rules-invalid", level: "warn", file: `${p.name}/package.json`, subject: p.name };
4557
+ if (p.error) ctx.report({ ...at, message: `${p.error}; its rules don't run` });
4558
+ for (const note of p.ignored ?? []) ctx.report({ ...at, message: `${note} (a newer @marktiderman/genesis-cli may read it)` });
4559
+ }
4560
+ const routes = routesDir(ctx);
4561
+ const settings2 = ctx.config.packageRules ?? {};
4562
+ for (const rule of preferRules(packages)) {
4563
+ if (rule.platform === "web" && isNative(ctx)) continue;
4564
+ if (rule.platform === "native" && !isNative(ctx)) continue;
4565
+ const compiled = compile(rule, settings2[rule.ruleId], routes);
4566
+ if (compiled) runPrefer(ctx, compiled);
4567
+ }
3637
4568
  }
3638
- if (result === "no" && unknown) result = "unknown";
3639
4569
  }
3640
- if (result === "yes" || cut.size === 0) {
3641
- cache2.free.set(k, result);
3642
- return [result, /* @__PURE__ */ new Set()];
4570
+ ];
4571
+ for (const p of packages) {
4572
+ const file = p.declaration?.plugin;
4573
+ if (!file) continue;
4574
+ let loaded;
4575
+ try {
4576
+ loaded = await loadPlugins([file], p.dir);
4577
+ } catch (err) {
4578
+ const message = err.message;
4579
+ out.push({ name: `${p.name} plugin`, check: (ctx) => ctx.report({ rule: "package-rules-invalid", level: "warn", file: `${p.name}/package.json`, subject: p.name, message }) });
4580
+ continue;
3643
4581
  }
3644
- const entries = cache2.cut.get(k) ?? [];
3645
- entries.push({ cut: [...cut], result });
3646
- cache2.cut.set(k, entries);
3647
- return [result, cut];
3648
- };
3649
- return { reach: (file, test2, depth = TRAIL_DEPTH) => reach(file, test2, depth, /* @__PURE__ */ new Set())[0] };
4582
+ for (const plugin of loaded) {
4583
+ out.push({
4584
+ name: `${p.namespace}/${plugin.name}`,
4585
+ check: (ctx) => plugin.check({
4586
+ ...ctx,
4587
+ report: (f) => ctx.report({ ...f, rule: f.rule.startsWith(`${p.namespace}/`) ? f.rule : `${p.namespace}/${f.rule}` })
4588
+ })
4589
+ });
4590
+ }
4591
+ }
4592
+ return out;
3650
4593
  }
3651
- var TRAIL_DEPTH, RESOLVE_EXTS2, IMPORT_FROM, EXPORT_FROM, DYNAMIC, trails;
3652
- var init_trail = __esm({
3653
- "src/doctor/trail.ts"() {
3654
- init_genesis();
4594
+ function unknownPackageRuleSettings(config, packages, reported) {
4595
+ const known = /* @__PURE__ */ new Set([...packageRuleIds(packages), ...reported.map((f) => f.rule)]);
4596
+ const plugins = packages.filter((p) => p.declaration?.plugin).map((p) => `${p.namespace}/`);
4597
+ return Object.keys(config.packageRules ?? {}).filter((id) => !known.has(id) && !plugins.some((ns) => id.startsWith(ns))).map((id) => ({
4598
+ rule: "stale-exception",
4599
+ level: "warn",
4600
+ file: "genesis config",
4601
+ subject: id,
4602
+ message: `packageRules names ${id}, which no installed package declares; check the id (genesis primitives lists them) or remove it`
4603
+ }));
4604
+ }
4605
+ function packageRuleIds(packages) {
4606
+ return new Set(preferRules(packages).map((r) => r.ruleId));
4607
+ }
4608
+ var PackageDeclarationError, GENESIS, ID, LEVELS2, PREFER_KEYS, FORBID_KEYS, UNLESS_KEYS, PRIMITIVE_KEYS, DECLARATION_KEYS, SCRIPT_GLOBS, isObject3, isStringList2, discoveryCache, specMatcher, JSX, ELEMENT, SCRIPT, TOP_LEVEL, EXPORT_LIST, EXPORT_DEFAULT_NAME, isNative;
4609
+ var init_package_rules = __esm({
4610
+ "src/doctor/package-rules.ts"() {
4611
+ init_discover();
4612
+ init_files();
4613
+ init_local();
4614
+ init_glob();
4615
+ init_plugins();
4616
+ init_routes();
4617
+ init_scan();
3655
4618
  init_source();
3656
- TRAIL_DEPTH = 6;
3657
- RESOLVE_EXTS2 = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs"];
3658
- IMPORT_FROM = /^[ \t]*import\s+(type\s+)?([^;"'`]*?)\s*from\s*["']([^"']+)["']/gm;
3659
- EXPORT_FROM = /^[ \t]*export\s+(type\s+)?[^;"'`]*?\bfrom\s*["']([^"']+)["']/gm;
3660
- DYNAMIC = /\bimport\s*\(\s*["']([^"']+)["']/g;
3661
- trails = /* @__PURE__ */ new WeakMap();
4619
+ init_rules();
4620
+ PackageDeclarationError = class extends Error {
4621
+ name = "PackageDeclarationError";
4622
+ };
4623
+ GENESIS = /^@marktiderman\/genesis(?:-([a-z0-9-]+))?$/;
4624
+ ID = /^[a-z0-9][a-z0-9-]*$/;
4625
+ LEVELS2 = /* @__PURE__ */ new Set(["error", "warn", "info"]);
4626
+ PREFER_KEYS = /* @__PURE__ */ new Set(["id", "need", "level", "platform", "files", "exclude", "forbid", "unless", "use", "import", "docs", "why", "newOnly"]);
4627
+ FORBID_KEYS = /* @__PURE__ */ new Set(["jsx", "imports", "pattern"]);
4628
+ UNLESS_KEYS = /* @__PURE__ */ new Set(["renders", "pattern"]);
4629
+ PRIMITIVE_KEYS = /* @__PURE__ */ new Set(["need", "use", "import", "docs"]);
4630
+ DECLARATION_KEYS = /* @__PURE__ */ new Set(["enforce", "reason", "prefer", "primitives", "plugin", "$comment"]);
4631
+ SCRIPT_GLOBS = ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx", "**/*.mts", "**/*.cts", "**/*.mjs", "**/*.cjs"];
4632
+ isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4633
+ isStringList2 = (v) => Array.isArray(v) && v.every((x) => typeof x === "string" && x.trim() !== "");
4634
+ discoveryCache = /* @__PURE__ */ new Map();
4635
+ specMatcher = (s) => s.endsWith("*") ? (spec) => spec.startsWith(s.slice(0, -1)) : (spec) => spec === s;
4636
+ JSX = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
4637
+ ELEMENT = /(?<![\w$.])<([A-Z][\w.]*)(?=[\s>/<])/g;
4638
+ SCRIPT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"]);
4639
+ TOP_LEVEL = /^(export\s+(default\s+)?)?(?:async\s+)?(?:function\*?|const|let|var|class)\s+([\w$]+)/gm;
4640
+ EXPORT_LIST = /\bexport\s*\{([^}]*)\}(?!\s*from)/g;
4641
+ EXPORT_DEFAULT_NAME = /^export\s+default\s+([A-Z][\w$]*)\s*;?\s*$/gm;
4642
+ isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
3662
4643
  }
3663
4644
  });
3664
4645
  function sourceFiles(dir, rel = "") {
3665
4646
  const out = [];
3666
- for (const entry of readdirSync(path23.join(dir, rel)).sort()) {
4647
+ for (const entry of readdirSync(path26.join(dir, rel)).sort()) {
3667
4648
  if (entry.startsWith(".") || SKIP_DIRS2.has(entry)) continue;
3668
4649
  const child = rel ? `${rel}/${entry}` : entry;
3669
- const stat = lstatSync(path23.join(dir, child));
4650
+ const stat = lstatSync(path26.join(dir, child));
3670
4651
  if (stat.isSymbolicLink()) continue;
3671
4652
  if (stat.isDirectory()) out.push(...sourceFiles(dir, child));
3672
4653
  else if (SOURCE.test(entry) && !entry.endsWith(".d.ts")) out.push(child);
@@ -3689,13 +4670,13 @@ function matchPattern(pattern, spec) {
3689
4670
  return spec.startsWith(head) && spec.endsWith(tail) && spec.length >= head.length + tail.length ? spec.slice(head.length, spec.length - tail.length) : null;
3690
4671
  }
3691
4672
  function tsconfigPaths(dir) {
3692
- const file = path23.join(dir, "tsconfig.json");
4673
+ const file = path26.join(dir, "tsconfig.json");
3693
4674
  if (!existsSync(file)) return [];
3694
4675
  try {
3695
4676
  const text = readFileSync(file, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[\s{,[])\/\/[^\n]*/g, "$1").replace(/,(\s*[}\]])/g, "$1");
3696
4677
  const options = JSON.parse(text).compilerOptions ?? {};
3697
- const base = path23.resolve(dir, options.baseUrl ?? ".");
3698
- return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path23.resolve(base, t)) }));
4678
+ const base = path26.resolve(dir, options.baseUrl ?? ".");
4679
+ return Object.entries(options.paths ?? {}).map(([pattern, targets]) => ({ pattern, targets: targets.map((t) => path26.resolve(base, t)) }));
3699
4680
  } catch {
3700
4681
  return [];
3701
4682
  }
@@ -3709,8 +4690,8 @@ function checkImports2(ctx, pkg, json) {
3709
4690
  const hit = matchPattern(pattern, spec);
3710
4691
  if (hit === null) continue;
3711
4692
  return targets.some((t) => {
3712
- const rel = path23.relative(pkg.dir, t.replace("*", hit));
3713
- return !rel.startsWith("..") && !path23.isAbsolute(rel);
4693
+ const rel = path26.relative(pkg.dir, t.replace("*", hit));
4694
+ return !rel.startsWith("..") && !path26.isAbsolute(rel);
3714
4695
  });
3715
4696
  }
3716
4697
  return null;
@@ -3723,7 +4704,7 @@ function checkImports2(ctx, pkg, json) {
3723
4704
  ...Object.keys(json.optionalDependencies ?? {})
3724
4705
  ]);
3725
4706
  for (const file of sourceFiles(pkg.dir)) {
3726
- const code = stripForImports(readFileSync(path23.join(pkg.dir, file), "utf8"));
4707
+ const code = stripForImports(readFileSync(path26.join(pkg.dir, file), "utf8"));
3727
4708
  if (code === null) continue;
3728
4709
  const at = `${pkg.rel}/${file}`;
3729
4710
  const typeOnly = [...code.matchAll(TYPE_ONLY)].map((m) => [m.index, m.index + m[0].length]);
@@ -3748,9 +4729,9 @@ function checkImports2(ctx, pkg, json) {
3748
4729
  continue;
3749
4730
  }
3750
4731
  if (spec.startsWith(".")) {
3751
- const target = path23.resolve(pkg.dir, path23.dirname(file), spec);
3752
- const rel = path23.relative(pkg.dir, target);
3753
- if (rel.startsWith("..") || path23.isAbsolute(rel)) {
4732
+ const target = path26.resolve(pkg.dir, path26.dirname(file), spec);
4733
+ const rel = path26.relative(pkg.dir, target);
4734
+ if (rel.startsWith("..") || path26.isAbsolute(rel)) {
3754
4735
  ctx.report({ rule: "package-app-import", file: at, line, subject: spec, message: `${pkg.name} reaches outside its folder (${spec}); move what it needs into the package or a dependency` });
3755
4736
  }
3756
4737
  continue;
@@ -3772,12 +4753,12 @@ function checkMigrations(ctx, pkg, json) {
3772
4753
  if (typeof m.file === "string" && typeof m.test === "string") declaredFiles.add(m.file);
3773
4754
  if (typeof m.file === "string" && typeof m.test !== "string") {
3774
4755
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.file, message: `${pkg.name} block ${id}: ${m.file} has no pgTAP test; declare one as "test" beside it` });
3775
- } else if (typeof m.test === "string" && !existsSync(path23.join(pkg.dir, m.test))) {
4756
+ } else if (typeof m.test === "string" && !existsSync(path26.join(pkg.dir, m.test))) {
3776
4757
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/package.json`, subject: m.test, message: `${pkg.name} block ${id}: its test ${m.test} doesn't exist` });
3777
4758
  }
3778
4759
  }
3779
4760
  }
3780
- const dir = path23.join(pkg.dir, "migrations");
4761
+ const dir = path26.join(pkg.dir, "migrations");
3781
4762
  if (!existsSync(dir)) return;
3782
4763
  const seen = /* @__PURE__ */ new Map();
3783
4764
  for (const name of readdirSync(dir).sort()) {
@@ -3786,7 +4767,7 @@ function checkMigrations(ctx, pkg, json) {
3786
4767
  const other = seen.get(m[1]);
3787
4768
  if (other) ctx.report({ rule: "package-migration-number", file: `${pkg.rel}/migrations/${name}`, subject: m[1], message: `${pkg.name}: ${name} and ${other} share the number ${m[1]}; give each migration its own` });
3788
4769
  else seen.set(m[1], name);
3789
- if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path23.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
4770
+ if (!declaredFiles.has(`migrations/${name}`) && !existsSync(path26.join(dir, "tests", name.replace(/\.sql$/, ".test.sql")))) {
3790
4771
  ctx.report({ rule: "package-migration-test", file: `${pkg.rel}/migrations/${name}`, subject: name, message: `${pkg.name}: ${name} has no pgTAP test (migrations/tests/${name.replace(/\.sql$/, ".test.sql")})` });
3791
4772
  }
3792
4773
  }
@@ -3800,7 +4781,7 @@ function checkExports(ctx, pkg, json) {
3800
4781
  walk2(json.exports);
3801
4782
  for (const t of targets) {
3802
4783
  if (!t.startsWith("./") || t.includes("*") || !/\.(?:[cm]?tsx?|json)$/.test(t) || /\.d\.[cm]?ts$/.test(t)) continue;
3803
- if (!existsSync(path23.join(pkg.dir, t))) {
4784
+ if (!existsSync(path26.join(pkg.dir, t))) {
3804
4785
  ctx.report({ rule: "package-export-missing", file: `${pkg.rel}/package.json`, subject: t, message: `${pkg.name} exports ${t}, which doesn't exist` });
3805
4786
  }
3806
4787
  }
@@ -3818,11 +4799,11 @@ function checkBlocks(ctx, pkg, json) {
3818
4799
  function checkTaggedTests(ctx, pkg) {
3819
4800
  const tests = sourceFiles(pkg.dir).filter((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f));
3820
4801
  if (!tests.length) return;
3821
- const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path23.join(pkg.dir, f), "utf8")));
4802
+ const tagged = tests.some((f) => /@feat:[a-z]/.test(readFileSync(path26.join(pkg.dir, f), "utf8")));
3822
4803
  if (!tagged) ctx.report({ rule: "package-untagged-tests", level: "warn", file: pkg.rel, message: `${pkg.name}'s tests name no feature; tag them with // @feat:<feature id>` });
3823
4804
  }
3824
4805
  function checkRegistered(ctx, pkg) {
3825
- const file = path23.join(ctx.root, "features.json");
4806
+ const file = path26.join(ctx.root, "features.json");
3826
4807
  if (!existsSync(file)) return;
3827
4808
  let doc;
3828
4809
  try {
@@ -3832,7 +4813,7 @@ function checkRegistered(ctx, pkg) {
3832
4813
  }
3833
4814
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3834
4815
  const forms = /* @__PURE__ */ new Set([pkg.rel]);
3835
- if (top) forms.add(path23.relative(top, realpathSync(pkg.dir)).split(path23.sep).join("/"));
4816
+ if (top) forms.add(path26.relative(top, realpathSync(pkg.dir)).split(path26.sep).join("/"));
3836
4817
  const covered = (doc.features ?? []).some(
3837
4818
  (f) => (f.links?.code ?? []).some((c) => {
3838
4819
  const norm = c.replace(/^\.\//, "").replace(/\/+$/, "");
@@ -3862,9 +4843,9 @@ function mergeBaseOf(root, base) {
3862
4843
  function checkChanges(ctx, pkg, json, base, mergeBase) {
3863
4844
  const top = git(ctx.root, ["rev-parse", "--show-toplevel"])?.trim();
3864
4845
  if (!top) return;
3865
- const appRelative = (fromTop) => path23.relative(realpathSync(ctx.root), path23.join(top, fromTop)).split(path23.sep).join("/");
3866
- const inRepo = path23.relative(top, realpathSync(pkg.dir)).split(path23.sep).join("/");
3867
- const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell, i) => i === 0 ? cell : appRelative(cell)).join(" ")).join("\n");
4846
+ const appRelative = (fromTop) => path26.relative(realpathSync(ctx.root), path26.join(top, fromTop)).split(path26.sep).join("/");
4847
+ const inRepo = path26.relative(top, realpathSync(pkg.dir)).split(path26.sep).join("/");
4848
+ const diff = (git(top, ["diff", "--name-status", "-M", mergeBase, "--", inRepo]) ?? "").split("\n").filter(Boolean).map((row) => row.split(" ").map((cell2, i) => i === 0 ? cell2 : appRelative(cell2)).join(" ")).join("\n");
3868
4849
  const untracked = (git(top, ["ls-files", "--others", "--exclude-standard", "--", inRepo]) ?? "").split("\n").filter(Boolean).map(appRelative);
3869
4850
  const changed = [...diff.split("\n").filter(Boolean).map((row) => row.split(" ").at(-1)), ...untracked].filter(
3870
4851
  (f) => !/(^|\/)(CHANGELOG\.md|node_modules\/)/.test(f)
@@ -3886,11 +4867,11 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
3886
4867
  const now = typeof json.version === "string" ? parseVersion(json.version) : null;
3887
4868
  const was = typeof versionBefore === "string" ? parseVersion(versionBefore) : null;
3888
4869
  const bumped = before === null || now !== null && was !== null && compareVersions(now, was) > 0;
3889
- const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path23.join(top, f)) : [];
4870
+ const changesets = top ? (git(top, ["diff", "--name-only", "--diff-filter=A", mergeBase, "--", ".changeset"]) ?? "").split("\n").concat((git(top, ["ls-files", "--others", "--exclude-standard", "--", ".changeset"]) ?? "").split("\n")).filter((f) => f.endsWith(".md")).map((f) => path26.join(top, f)) : [];
3890
4871
  const naming = changesets.filter((p) => existsSync(p) && changesetNames(readFileSync(p, "utf8")).has(json.name));
3891
4872
  const named = naming.length > 0;
3892
4873
  if (named && !naming.some((p) => /^Features:\s*\S/m.test(readFileSync(p, "utf8")))) {
3893
- ctx.report({ rule: "package-unversioned-change", level: "warn", file: path23.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
4874
+ ctx.report({ rule: "package-unversioned-change", level: "warn", file: path26.relative(realpathSync(ctx.root), naming[0]), message: `the changeset for ${pkg.name} has no "Features:" line; name the features it changes` });
3894
4875
  }
3895
4876
  let jsonBefore = null;
3896
4877
  try {
@@ -3900,7 +4881,7 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
3900
4881
  }
3901
4882
  const raw = json;
3902
4883
  if (jsonBefore && (JSON.stringify(jsonBefore.genesis) !== JSON.stringify(raw.genesis) || JSON.stringify(jsonBefore.exports) !== JSON.stringify(raw.exports))) {
3903
- const appInRepo = path23.relative(top, realpathSync(ctx.root)).split(path23.sep).join("/");
4884
+ const appInRepo = path26.relative(top, realpathSync(ctx.root)).split(path26.sep).join("/");
3904
4885
  const candidates = [.../* @__PURE__ */ new Set(["features.ts", "src/features.ts", ...appInRepo ? [`${appInRepo}/features.ts`, `${appInRepo}/src/features.ts`] : []])];
3905
4886
  const registry = (git(top, ["diff", "--name-only", mergeBase, "--", ...candidates]) ?? "").trim();
3906
4887
  if (!registry) ctx.report({ rule: "package-unversioned-change", level: "warn", file: `${pkg.rel}/package.json`, message: `${pkg.name}'s blocks or exports changed but features.ts didn't; update the features they belong to` });
@@ -3917,6 +4898,25 @@ function checkChanges(ctx, pkg, json, base, mergeBase) {
3917
4898
  });
3918
4899
  }
3919
4900
  }
4901
+ function checkDoctorDeclaration(ctx, pkg, json) {
4902
+ if (json.private === true || !GENESIS_NAME.test(json.name)) return;
4903
+ const file = `${pkg.rel}/package.json`;
4904
+ const raw = json.genesis?.doctor;
4905
+ if (raw === void 0) {
4906
+ ctx.report({
4907
+ rule: "package-doctor-declaration",
4908
+ file,
4909
+ subject: json.name,
4910
+ message: `${json.name} declares no doctor rules; add genesis.doctor with the primitives it enforces ("prefer" rules), or { "enforce": false, "reason": "\u2026" }`
4911
+ });
4912
+ return;
4913
+ }
4914
+ try {
4915
+ validateDeclaration(raw, json.name, pkg.dir);
4916
+ } catch (err) {
4917
+ ctx.report({ rule: "package-doctor-declaration", file, subject: json.name, message: err.message });
4918
+ }
4919
+ }
3920
4920
  function checkPackagesPack(ctx) {
3921
4921
  let packages;
3922
4922
  try {
@@ -3932,28 +4932,31 @@ function checkPackagesPack(ctx) {
3932
4932
  ctx.report({ rule: "package-unversioned-change", level: base ? "warn" : "info", file: "genesis.config.json", message: `change gate skipped: ${merge.reason}` });
3933
4933
  }
3934
4934
  for (const pkg of packages) {
3935
- const json = JSON.parse(readFileSync(path23.join(pkg.dir, "package.json"), "utf8"));
4935
+ const json = JSON.parse(readFileSync(path26.join(pkg.dir, "package.json"), "utf8"));
3936
4936
  checkImports2(ctx, pkg, json);
3937
4937
  checkExports(ctx, pkg, json);
3938
4938
  checkBlocks(ctx, pkg, json);
3939
4939
  checkMigrations(ctx, pkg, json);
3940
4940
  checkTaggedTests(ctx, pkg);
3941
4941
  checkRegistered(ctx, pkg);
4942
+ checkDoctorDeclaration(ctx, pkg, json);
3942
4943
  if (base && "sha" in merge) checkChanges(ctx, pkg, json, base, merge.sha);
3943
4944
  }
3944
4945
  }
3945
- var SOURCE, SKIP_DIRS2, BUILTINS, IMPORT, TYPE_ONLY;
4946
+ var SOURCE, SKIP_DIRS2, BUILTINS, IMPORT, TYPE_ONLY, GENESIS_NAME;
3946
4947
  var init_packages = __esm({
3947
4948
  "src/doctor/packages.ts"() {
3948
4949
  init_local();
3949
4950
  init_manifest();
3950
4951
  init_semver();
3951
4952
  init_trail();
4953
+ init_package_rules();
3952
4954
  SOURCE = /\.(?:[cm]?[jt]sx?)$/;
3953
4955
  SKIP_DIRS2 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "coverage", ".turbo"]);
3954
4956
  BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
3955
4957
  IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*)["']([^"']+)["']/g;
3956
4958
  TYPE_ONLY = /\b(?:import|export)\s+type\s+(?:\{[^}]*\}|\*\s+as\s+[\w$]+|\*|[\w$]+)\s*from\s*["'][^"']+["']/g;
4959
+ GENESIS_NAME = /^@marktiderman\/genesis(?:-[a-z0-9-]+)?$/;
3957
4960
  }
3958
4961
  });
3959
4962
  function sqlStatements(text) {
@@ -4102,30 +5105,30 @@ function gitView(root, dir, base) {
4102
5105
  const untracked = git2(root, ["ls-files", "--others", "--exclude-standard", "--", dir]);
4103
5106
  if (diff === null || untracked === null) return { reason: `git diff against ${base} failed`, repo: true };
4104
5107
  const sql = (p) => p !== void 0 && p.endsWith(".sql");
4105
- const touched = new Set(untracked.split("\n").filter(sql));
5108
+ const touched2 = new Set(untracked.split("\n").filter(sql));
4106
5109
  const edited = [];
4107
5110
  for (const row of diff.split("\n").filter(Boolean)) {
4108
5111
  const [status, a, b] = row.split(" ");
4109
5112
  if (status.startsWith("R")) {
4110
- if (sql(b)) touched.add(b);
5113
+ if (sql(b)) touched2.add(b);
4111
5114
  if (sql(a)) edited.push({ file: a, status: "renamed" });
4112
5115
  continue;
4113
5116
  }
4114
5117
  if (!sql(a)) continue;
4115
- if (status.startsWith("A")) touched.add(a);
5118
+ if (status.startsWith("A")) touched2.add(a);
4116
5119
  else if (status.startsWith("M") || status.startsWith("T")) {
4117
- touched.add(a);
5120
+ touched2.add(a);
4118
5121
  edited.push({ file: a, status: "modified" });
4119
5122
  } else if (status.startsWith("D")) edited.push({ file: a, status: "deleted" });
4120
5123
  }
4121
- return { touched, edited };
5124
+ return { touched: touched2, edited };
4122
5125
  }
4123
5126
  function checkSupabasePack(ctx) {
4124
5127
  const settings2 = ctx.config.supabase ?? {};
4125
5128
  const dir = settings2.migrations ?? DEFAULT_MIGRATIONS;
4126
- const abs = path23.join(ctx.root, dir);
5129
+ const abs = path26.join(ctx.root, dir);
4127
5130
  if (!existsSync(abs)) throw new DoctorConfigError(`the supabase pack reads ${dir}, which doesn't exist; set doctor.supabase.migrations`);
4128
- const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path23.join(abs, n), "utf8")) }));
5131
+ const migrations = readdirSync(abs).filter((n) => n.endsWith(".sql")).sort().map((n) => ({ file: `${dir}/${n}`, statements: sqlStatements(readFileSync(path26.join(abs, n), "utf8")) }));
4129
5132
  const exposed = new Set((settings2.exposedSchemas ?? DEFAULT_EXPOSED).map((s) => s.toLowerCase()));
4130
5133
  const base = settings2.base ?? DEFAULT_BASE;
4131
5134
  const view = gitView(ctx.root, dir, base);
@@ -4142,7 +5145,7 @@ function checkSupabasePack(ctx) {
4142
5145
  }
4143
5146
  }
4144
5147
  const since = settings2.since;
4145
- const afterSince = (file) => since === void 0 || path23.posix.basename(file) >= since;
5148
+ const afterSince = (file) => since === void 0 || path26.posix.basename(file) >= since;
4146
5149
  if ("reason" in view && since === void 0) {
4147
5150
  ctx.report({
4148
5151
  rule: "migration-grants",
@@ -4413,18 +5416,18 @@ var init_supabase = __esm({
4413
5416
  }
4414
5417
  });
4415
5418
  function nodeModulesOf(dir) {
4416
- const parent = path23.dirname(dir);
4417
- return path23.basename(parent).startsWith("@") ? path23.dirname(parent) : parent;
5419
+ const parent = path26.dirname(dir);
5420
+ return path26.basename(parent).startsWith("@") ? path26.dirname(parent) : parent;
4418
5421
  }
4419
5422
  function packagesIn(nodeModules) {
4420
5423
  if (!existsSync(nodeModules)) return [];
4421
5424
  const out = [];
4422
5425
  for (const entry of readdirSync(nodeModules)) {
4423
5426
  if (entry.startsWith(".")) continue;
4424
- const p = path23.join(nodeModules, entry);
5427
+ const p = path26.join(nodeModules, entry);
4425
5428
  if (entry.startsWith("@")) {
4426
5429
  try {
4427
- for (const sub of readdirSync(p)) out.push(path23.join(p, sub));
5430
+ for (const sub of readdirSync(p)) out.push(path26.join(p, sub));
4428
5431
  } catch {
4429
5432
  }
4430
5433
  } else {
@@ -4436,7 +5439,7 @@ function packagesIn(nodeModules) {
4436
5439
  function genesisInstalls(root) {
4437
5440
  const copies = /* @__PURE__ */ new Map();
4438
5441
  const realRoot = real(root);
4439
- const rel = (abs) => path23.relative(realRoot, abs).split(path23.sep).join("/") || ".";
5442
+ const rel = (abs) => path26.relative(realRoot, abs).split(path26.sep).join("/") || ".";
4440
5443
  const via = /* @__PURE__ */ new Map();
4441
5444
  const record = (real2, manifest, by, range, root2) => {
4442
5445
  let copy = copies.get(real2);
@@ -4456,7 +5459,7 @@ function genesisInstalls(root) {
4456
5459
  if (!manifest?.name) return;
4457
5460
  if (kind !== "dev" && DEV_TOOLS.has(manifest.name)) return;
4458
5461
  const realDir = real(dir);
4459
- if (GENESIS.test(manifest.name)) record(realDir, manifest, by, range, kind);
5462
+ if (GENESIS2.test(manifest.name)) record(realDir, manifest, by, range, kind);
4460
5463
  if (expanded.has(realDir)) return;
4461
5464
  expanded.add(realDir);
4462
5465
  queue.push({ real: realDir, manifest, label: `${manifest.name}@${manifest.version ?? "?"}` });
@@ -4481,7 +5484,7 @@ function genesisInstalls(root) {
4481
5484
  if (!dir) return null;
4482
5485
  if (!ownInstall || name in declared) return dir;
4483
5486
  const realDir = real(dir);
4484
- if (realDir.startsWith(realRoot + path23.sep)) return dir;
5487
+ if (realDir.startsWith(realRoot + path26.sep)) return dir;
4485
5488
  return nodeModulesOf(realDir) === nodeModulesOf(from) ? dir : null;
4486
5489
  };
4487
5490
  const rootsOf = (deps, by) => Object.entries(deps).flatMap(([name, range]) => {
@@ -4489,7 +5492,7 @@ function genesisInstalls(root) {
4489
5492
  return dir ? [{ dir, by, ...range ? { range } : {} }] : [];
4490
5493
  });
4491
5494
  const app = readManifest(root);
4492
- const ownInstall = LOCKFILES.some((f) => existsSync(path23.join(root, f)));
5495
+ const ownInstall = LOCKFILES.some((f) => existsSync(path26.join(root, f)));
4493
5496
  const declared = { ...app?.devDependencies, ...app?.peerDependencies, ...app?.optionalDependencies, ...app?.dependencies };
4494
5497
  const declaredDev = Object.entries(app?.devDependencies ?? {});
4495
5498
  const runtimeDeps = {
@@ -4500,11 +5503,11 @@ function genesisInstalls(root) {
4500
5503
  };
4501
5504
  const devDeps = Object.fromEntries(declaredDev.filter(([n]) => NON_SHIPPING.test(n) && !(n in runtimeDeps)));
4502
5505
  walk2("runtime", rootsOf(runtimeDeps, "the app"));
4503
- const top = path23.join(root, "node_modules");
5506
+ const top = path26.join(root, "node_modules");
4504
5507
  walk2(
4505
5508
  "hoisted",
4506
5509
  packagesIn(top).filter((dir) => {
4507
- const name = path23.relative(top, dir).split(path23.sep).join("/");
5510
+ const name = path26.relative(top, dir).split(path26.sep).join("/");
4508
5511
  return !(name in runtimeDeps) && !(name in devDeps);
4509
5512
  }).map((dir) => ({ dir, by: "hoisted, not a direct dependency" }))
4510
5513
  );
@@ -4546,13 +5549,13 @@ function checkDuplicatePackages(ctx) {
4546
5549
  }
4547
5550
  }
4548
5551
  function checkPeerRanges(ctx) {
4549
- const rel = (abs) => path23.relative(ctx.root, abs).split(path23.sep).join("/");
5552
+ const rel = (abs) => path26.relative(ctx.root, abs).split(path26.sep).join("/");
4550
5553
  for (const copies of genesisInstalls(ctx.root).values()) {
4551
5554
  for (const copy of copies) {
4552
5555
  const dir = copy.absolutePath;
4553
5556
  const peers = readManifest(dir)?.peerDependencies ?? {};
4554
5557
  for (const [peer, range] of Object.entries(peers)) {
4555
- if (!GENESIS.test(peer)) continue;
5558
+ if (!GENESIS2.test(peer)) continue;
4556
5559
  const peerDir = findPackageDir(dir, peer);
4557
5560
  const installed = peerDir && readManifest(peerDir)?.version;
4558
5561
  if (!peerDir || !installed) continue;
@@ -4569,17 +5572,17 @@ function checkPeerRanges(ctx) {
4569
5572
  }
4570
5573
  }
4571
5574
  }
4572
- var GENESIS, DEV_TOOLS, NON_SHIPPING, readManifest, real, LOCKFILES;
5575
+ var GENESIS2, DEV_TOOLS, NON_SHIPPING, readManifest, real, LOCKFILES;
4573
5576
  var init_installs = __esm({
4574
5577
  "src/doctor/installs.ts"() {
4575
5578
  init_genesis();
4576
5579
  init_semver();
4577
- GENESIS = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
5580
+ GENESIS2 = /^@marktiderman\/genesis(?:-[\w.-]+)?$/;
4578
5581
  DEV_TOOLS = /* @__PURE__ */ new Set(["@marktiderman/genesis-cli"]);
4579
5582
  NON_SHIPPING = /^(?:@marktiderman\/genesis-cli|vitest|@vitest\/.+|jest|jest-.+|@jest\/.+|ts-jest|babel-jest|mocha|ava|c8|nyc|@playwright\/test|playwright|cypress|@testing-library\/.+|happy-dom|jsdom|msw|@types\/.+|typescript|tsx|ts-node|eslint|eslint-.+|@eslint\/.+|@typescript-eslint\/.+|typescript-eslint|prettier|prettier-.+|@biomejs\/.+|oxlint|vite|@vitejs\/.+|vite-plugin-.+|webpack|webpack-.+|rollup|@rollup\/.+|esbuild|tsup|turbo|@storybook\/.+|storybook|@changesets\/.+|husky|lint-staged|wrangler|knip|concurrently|npm-run-all2?|rimraf|cross-env|dotenv-cli)$/;
4580
5583
  readManifest = (dir) => {
4581
5584
  try {
4582
- return JSON.parse(readFileSync(path23.join(dir, "package.json"), "utf8"));
5585
+ return JSON.parse(readFileSync(path26.join(dir, "package.json"), "utf8"));
4583
5586
  } catch {
4584
5587
  return null;
4585
5588
  }
@@ -4594,119 +5597,6 @@ var init_installs = __esm({
4594
5597
  LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"];
4595
5598
  }
4596
5599
  });
4597
- function routesDir(ctx) {
4598
- if (ctx.config.routesDir) return ctx.config.routesDir;
4599
- return ROUTES_DIR_CANDIDATES.find((d) => existsSync(path23.join(ctx.root, d))) ?? null;
4600
- }
4601
- function flavorOf(dir, rels) {
4602
- const stems = rels.map((r) => r.split("/").pop());
4603
- if (stems.includes("__root")) return "tanstack";
4604
- if (stems.some((s) => s === "page" || s === "layout")) return "next-app";
4605
- if (/(?:^|\/)pages$/.test(dir) && stems.some((s) => s === "_app" || s === "_document")) return "next-pages";
4606
- return "tanstack";
4607
- }
4608
- function renders(code) {
4609
- const elements = renderedElements(code);
4610
- if (elements.some((e) => !NON_PAGE_ELEMENTS.has(e)) || HTML_ELEMENT.test(code)) return true;
4611
- const definedHere = (name) => new RegExp(`\\b(?:function|const|let|var|class)\\s+${name.replace(/\$/g, "\\$")}\\b`).test(code);
4612
- const named = COMPONENT_OPTION.exec(code)?.[1];
4613
- if (named && !definedHere(named)) return true;
4614
- if (/\bexport\s*\{\s*default\b[^}]*\}\s*from\b/.test(code)) return true;
4615
- const exported = /\bexport\s+default\s+([A-Z][\w$]*)\s*;?\s*$/m.exec(code)?.[1];
4616
- return exported !== void 0 && !definedHere(exported);
4617
- }
4618
- function webRoutes(ctx) {
4619
- const dir = routesDir(ctx);
4620
- if (!dir) return [];
4621
- const candidates = ctx.files.filter((f) => JSX_EXTS2.has(f.ext) && f.path.startsWith(`${dir}/`)).map((file) => ({ file, rel: file.path.slice(dir.length + 1).replace(/\.[^.]+$/, "") }));
4622
- const flavor = flavorOf(dir, candidates.map((c) => c.rel));
4623
- const stems = STEMS[flavor];
4624
- const groups = /* @__PURE__ */ new Map();
4625
- for (const { file, rel } of candidates) {
4626
- const parts = rel.split("/");
4627
- if (parts.some((p) => p.startsWith("-"))) continue;
4628
- if (flavor !== "tanstack" && parts.slice(0, -1).some((p) => p.startsWith("_"))) continue;
4629
- if (flavor === "next-pages" && parts[0] === "api") continue;
4630
- if (stems.skip.test(parts.at(-1))) continue;
4631
- if (flavor === "next-app" && !stems.layout.has(parts.at(-1)) && !stems.index.has(parts.at(-1))) continue;
4632
- const id = flavor === "tanstack" ? rel.replace(/\.lazy$/, "") : rel;
4633
- groups.set(id, [...groups.get(id) ?? [], file]);
4634
- }
4635
- const trail = trailFor(ctx);
4636
- const routes = [];
4637
- for (const [id, files] of groups) {
4638
- const parts = id.split("/");
4639
- const stem = parts.pop();
4640
- const folders = flavor === "next-app" ? parts.map((p) => p.replace(/^\((?:\.{1,3}|\.\.\)\(\.\.)\)(?=.)/, "")).filter((p) => !/^\(.*\)$/.test(p) && !p.startsWith("@")) : parts;
4641
- const named = stems.layout.has(stem) || stems.index.has(stem);
4642
- const own = named ? [] : flavor === "tanstack" ? stem.split(".") : [stem];
4643
- const segments = [...folders, ...own];
4644
- const tree = [...parts, ...own];
4645
- let index = stems.index.has(stem);
4646
- if (!index && !stems.layout.has(stem) && flavor === "tanstack" && stems.index.has(segments.at(-1) ?? "")) {
4647
- segments.pop();
4648
- tree.pop();
4649
- index = true;
4650
- }
4651
- const code = files.map((f) => f.code).join("\n");
4652
- const elements = renderedElements(code);
4653
- const pathless = flavor === "tanstack" && !index && /^_(?!_)/.test(tree.at(-1) ?? "");
4654
- const outlet = elements.includes("Outlet") || !stems.index.has(stem) && files.some((f) => trail.reach(f, RENDERS_OUTLET, 2) === "yes");
4655
- const layout = stems.layout.has(stem) || pathless || outlet;
4656
- const rendering = renders(code);
4657
- const ownContent = new RegExp(OWN_CONTENT).test(code);
4658
- const pure = stem === "__root" || flavor !== "tanstack" && stems.layout.has(stem);
4659
- const page = !pure && !pathless && (!layout || ownContent);
4660
- routes.push({
4661
- file: files.find((f) => /\.lazy\.[^.]+$/.test(f.path)) ?? files[0],
4662
- files,
4663
- segments,
4664
- tree,
4665
- index,
4666
- layout,
4667
- page,
4668
- detail: page && !index && /^(?:\$|\[)/.test(segments.at(-1) ?? ""),
4669
- redirectOnly: !rendering,
4670
- parents: []
4671
- });
4672
- }
4673
- for (const r of routes) {
4674
- const own = r.tree;
4675
- for (const p of routes) {
4676
- if (p === r || !p.layout) continue;
4677
- const n = p.tree.length;
4678
- if (n > own.length || n === own.length && !(r.index && !r.layout)) continue;
4679
- if (key(own.slice(0, n)) !== key(p.tree)) continue;
4680
- if (n > 0 && own[n - 1].endsWith("_") && !p.tree[n - 1].endsWith("_")) continue;
4681
- r.parents.push(p);
4682
- }
4683
- r.parents.sort((a, b) => b.tree.length - a.tree.length);
4684
- }
4685
- return routes;
4686
- }
4687
- var ROUTES_DIR_CANDIDATES, STEMS, NON_PAGE_ELEMENTS, HTML_ELEMENT, COMPONENT_OPTION, RENDERS_OUTLET, OWN_CONTENT, key;
4688
- var init_routes = __esm({
4689
- "src/doctor/routes.ts"() {
4690
- init_source();
4691
- init_trail();
4692
- ROUTES_DIR_CANDIDATES = ["src/routes", "src/app", "app", "src/pages", "pages"];
4693
- STEMS = {
4694
- tanstack: { layout: /* @__PURE__ */ new Set(["route", "__root"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^$/ },
4695
- "next-app": {
4696
- layout: /* @__PURE__ */ new Set(["layout"]),
4697
- index: /* @__PURE__ */ new Set(["page"]),
4698
- skip: /^(?:error|global-error|loading|not-found|forbidden|unauthorized|template|default|route|middleware|instrumentation|opengraph-image|twitter-image|icon|apple-icon|sitemap|robots|manifest)$/
4699
- },
4700
- "next-pages": { layout: /* @__PURE__ */ new Set(["_app"]), index: /* @__PURE__ */ new Set(["index"]), skip: /^(?:_document|_error|404|500)$/ }
4701
- };
4702
- NON_PAGE_ELEMENTS = /* @__PURE__ */ new Set(["Navigate", "Redirect", "Outlet", "Fragment", "React.Fragment"]);
4703
- HTML_ELEMENT = /(?<![\w$.])<(?:[a-z][\w-]*(?=[\s>/])|>)/;
4704
- COMPONENT_OPTION = /\bcomponent\s*:\s*(?!undefined\b|null\b)([A-Za-z_$][\w$]*)/;
4705
- RENDERS_OUTLET = (code) => /<Outlet(?=[\s>/])/.test(code);
4706
- OWN_CONTENT = /(?<![=-])>\s*[A-Za-z][^<>{}]*</.source + "|" + /(?<![\w$.])<(?:h[1-6]|ul|ol|table|dl|H[1-6]|[A-Z]\w*(?:Heading|Title|Table|List|Grid))(?=[\s>/])/.source;
4707
- key = (segments) => segments.map((s) => s.replace(/_$/, "")).join("/");
4708
- }
4709
- });
4710
5600
 
4711
5601
  // src/doctor/structure.ts
4712
5602
  function routeReach(ctx, r, test2) {
@@ -4725,7 +5615,7 @@ function insideShell(ctx, routes) {
4725
5615
  return (r) => !shell.has(r) && (anyShell || r.parents.some((p) => shell.has(p)));
4726
5616
  }
4727
5617
  function checkHandRolledSubNav(ctx) {
4728
- if (isNative(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
5618
+ if (isNative2(ctx) || !ctx.genesis.values.has("useAppShellSubNav")) return;
4729
5619
  const routes = webRoutes(ctx);
4730
5620
  if (routes.length === 0) return;
4731
5621
  const inShell = insideShell(ctx, routes);
@@ -4782,7 +5672,7 @@ function checkLocalGenesisCopies(ctx) {
4782
5672
  }
4783
5673
  }
4784
5674
  function checkResourceWorkspaces(ctx) {
4785
- if (isNative(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
5675
+ if (isNative2(ctx) || !ctx.genesis.values.has("AppShellPageHeader")) return;
4786
5676
  const header = /<AppShellPageHeader(?=[\s>/])/;
4787
5677
  const byFolder = /* @__PURE__ */ new Map();
4788
5678
  for (const r of webRoutes(ctx)) {
@@ -4807,7 +5697,7 @@ function checkResourceWorkspaces(ctx) {
4807
5697
  }
4808
5698
  }
4809
5699
  function checkPageLayouts(ctx) {
4810
- if (isNative(ctx)) return;
5700
+ if (isNative2(ctx)) return;
4811
5701
  const layouts = new Set(ctx.genesis.components.filter((n) => PAGE_LAYOUT.test(n)));
4812
5702
  for (const c of ctx.genesis.companions) for (const n of c.components) if (PAGE_LAYOUT.test(n)) layouts.add(n);
4813
5703
  if (layouts.size === 0) return;
@@ -4836,7 +5726,7 @@ function checkPageLayouts(ctx) {
4836
5726
  });
4837
5727
  }
4838
5728
  }
4839
- var SUB_NAV_DOCS, CONTAINER, SWITCHER, SHELL, GENESIS_PACKAGE2, PAGE_LAYOUT, EMBEDDED_RESOURCE_VIEW, PACKAGE_SCREEN, isNative, rendersRe, routeVia;
5729
+ var SUB_NAV_DOCS, CONTAINER, SWITCHER, SHELL, GENESIS_PACKAGE2, PAGE_LAYOUT, EMBEDDED_RESOURCE_VIEW, PACKAGE_SCREEN, isNative2, rendersRe, routeVia;
4840
5730
  var init_structure = __esm({
4841
5731
  "src/doctor/structure.ts"() {
4842
5732
  init_scan();
@@ -4851,7 +5741,7 @@ var init_structure = __esm({
4851
5741
  PAGE_LAYOUT = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell)|ResourceView)$/;
4852
5742
  EMBEDDED_RESOURCE_VIEW = /<ResourceView\b[^>]*?\blayout\s*=\s*(?:(["'`]) {8}\1|\{\s*(["'`]) {8}\2\s*\})[^>]*>/g;
4853
5743
  PACKAGE_SCREEN = /^(?:(?!Breadcrumb)[A-Z]\w*(?:Page|PageShell|Screen|Workspace)|ResourceView)$/;
4854
- isNative = (ctx) => ctx.config.packs?.includes("native") ?? false;
5744
+ isNative2 = (ctx) => ctx.config.packs?.includes("native") ?? false;
4855
5745
  rendersRe = (names) => {
4856
5746
  const list = [...names];
4857
5747
  return list.length ? new RegExp(`<(?:${list.map((n) => n.replace(/[.$]/g, "\\$&")).join("|")})(?=[\\s>/])`) : null;
@@ -4908,7 +5798,7 @@ function bumpPackageJson(file, text, wanted) {
4908
5798
  const changes = [], skipped = [];
4909
5799
  for (const section of SECTIONS) {
4910
5800
  for (const [name, spec] of Object.entries(pkg[section] ?? {})) {
4911
- if (!GENESIS2.test(name)) continue;
5801
+ if (!GENESIS3.test(name)) continue;
4912
5802
  const m = EXACT.exec(spec);
4913
5803
  if (!m) {
4914
5804
  skipped.push({ file, name, spec, why: "not a plain version" });
@@ -4946,11 +5836,11 @@ function bumpSummary(version, changes, skipped) {
4946
5836
  ...skipped.length ? ["", "Left alone:", "", ...skipped.map((s) => `- \`${s.name}\` ${s.spec} in ${s.file}: ${s.why}`)] : []
4947
5837
  ].join("\n");
4948
5838
  }
4949
- var UMBRELLA, GENESIS2, EXACT, PLAIN, SECTIONS;
5839
+ var UMBRELLA, GENESIS3, EXACT, PLAIN, SECTIONS;
4950
5840
  var init_bump_core = __esm({
4951
5841
  "src/upgrade/bump-core.mjs"() {
4952
5842
  UMBRELLA = "@marktiderman/genesis";
4953
- GENESIS2 = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
5843
+ GENESIS3 = /^@marktiderman\/genesis(-[a-z0-9-]+)?$/;
4954
5844
  EXACT = /^(\^|~|=)?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/;
4955
5845
  PLAIN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
4956
5846
  SECTIONS = ["dependencies", "devDependencies", "optionalDependencies"];
@@ -5171,11 +6061,11 @@ function appScripts(root) {
5171
6061
  const out = [];
5172
6062
  const walk2 = (dir) => {
5173
6063
  for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
5174
- const abs = path23.join(dir, entry.name);
6064
+ const abs = path26.join(dir, entry.name);
5175
6065
  if (entry.isDirectory()) {
5176
6066
  if (!SKIP_DIRS3.has(entry.name)) walk2(abs);
5177
- } else if (entry.isFile() && SCRIPT.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
5178
- out.push(path23.relative(root, abs).split(path23.sep).join("/"));
6067
+ } else if (entry.isFile() && SCRIPT2.test(entry.name) && statSync(abs).size <= MAX_BYTES) {
6068
+ out.push(path26.relative(root, abs).split(path26.sep).join("/"));
5179
6069
  }
5180
6070
  }
5181
6071
  };
@@ -5197,13 +6087,13 @@ function uncoveredBreaks(changes, registry = CODEMODS) {
5197
6087
  };
5198
6088
  return changes.filter((c) => major(c.from) !== major(c.to) && codemodsFor([c], registry).length === 0);
5199
6089
  }
5200
- var SKIP_DIRS3, SCRIPT, MAX_BYTES, scopeNeutralNames, CODEMODS, bare;
6090
+ var SKIP_DIRS3, SCRIPT2, MAX_BYTES, scopeNeutralNames, CODEMODS, bare;
5201
6091
  var init_codemods = __esm({
5202
6092
  "src/upgrade/codemods.ts"() {
5203
6093
  init_bump_core();
5204
6094
  init_scope_names();
5205
6095
  SKIP_DIRS3 = /* @__PURE__ */ new Set(["node_modules", "dist", "build", ".git", ".next", ".output", ".turbo", ".expo", "coverage", "ios", "android"]);
5206
- SCRIPT = /\.(?:[cm]?[jt]sx?)$/;
6096
+ SCRIPT2 = /\.(?:[cm]?[jt]sx?)$/;
5207
6097
  MAX_BYTES = 2 * 1024 * 1024;
5208
6098
  scopeNeutralNames = {
5209
6099
  id: "genesis-core-2-scope-names",
@@ -5215,7 +6105,7 @@ var init_codemods = __esm({
5215
6105
  let readsId = false;
5216
6106
  let augmented = false;
5217
6107
  for (const rel of appScripts(root)) {
5218
- const abs = path23.join(root, rel);
6108
+ const abs = path26.join(root, rel);
5219
6109
  const text = readFileSync(abs, "utf8");
5220
6110
  if (augmentsResourceScope(text)) augmented = true;
5221
6111
  if (!IMPORTS_GENESIS.test(text)) continue;
@@ -5311,7 +6201,7 @@ function checkTreeViews(ctx) {
5311
6201
  function moduleFiles(ctx) {
5312
6202
  const scanned = new Set(ctx.files.map((f) => f.path));
5313
6203
  const ignored = globMatcher([...DEFAULT_IGNORE, ...ctx.config.ignore ?? []]);
5314
- const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path23.join(ctx.root, rel), "utf8"), true) }));
6204
+ const extra = appScripts(ctx.root).filter((rel) => /\.(c|m)js$/.test(rel) && !scanned.has(rel) && !ignored(rel)).map((rel) => ({ path: rel, code: stripBlockComments(readFileSync(path26.join(ctx.root, rel), "utf8"), true) }));
5315
6205
  return [...ctx.files.filter((f) => SCRIPT_EXTS5.has(f.ext)), ...extra];
5316
6206
  }
5317
6207
  function checkStudioServerImports(ctx) {
@@ -5341,7 +6231,7 @@ function checkStudioServerImports(ctx) {
5341
6231
  }
5342
6232
  function checkRemovedScopeNames(ctx) {
5343
6233
  let augmentedMemo;
5344
- const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path23.join(ctx.root, rel), "utf8")));
6234
+ const augmented = () => augmentedMemo ??= ctx.files.some((f) => augmentsResourceScope(f.code)) || appScripts(ctx.root).filter((rel) => rel.endsWith(".d.ts")).some((rel) => augmentsResourceScope(readFileSync(path26.join(ctx.root, rel), "utf8")));
5345
6235
  for (const file of ctx.files) {
5346
6236
  if (!SCRIPT_EXTS5.has(file.ext)) continue;
5347
6237
  for (const hit of findRemovedScopeNames(file.code)) {
@@ -5388,6 +6278,313 @@ var init_api_usage = __esm({
5388
6278
  };
5389
6279
  }
5390
6280
  });
6281
+ function git3(root, args) {
6282
+ const r = spawnSync("git", args, { cwd: root, encoding: "utf8" });
6283
+ return r.status === 0 ? r.stdout : null;
6284
+ }
6285
+ function changedSince(root, base) {
6286
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6287
+ if (!mergeBase) return null;
6288
+ const committed = git3(root, ["diff", "-z", "--name-only", "--relative", `${mergeBase}`, "--"]);
6289
+ const untracked = git3(root, ["ls-files", "-z", "--others", "--exclude-standard"]);
6290
+ if (committed === null || untracked === null) return null;
6291
+ return new Set([...committed.split("\0"), ...untracked.split("\0")].filter(Boolean));
6292
+ }
6293
+ function showAt(dir, rev, file) {
6294
+ const at = `${rev}:./${file}`;
6295
+ if (git3(dir, ["cat-file", "-e", at]) === null) return void 0;
6296
+ return git3(dir, ["show", at]);
6297
+ }
6298
+ function configAtBase(root, base, explicitFile) {
6299
+ const mergeBase = git3(root, ["merge-base", base, "HEAD"])?.trim();
6300
+ if (!mergeBase) return null;
6301
+ const candidates = explicitFile ? [{ dir: path26.dirname(explicitFile), file: path26.basename(explicitFile), explicit: true }] : [
6302
+ { dir: root, file: "genesis.config.json", explicit: false },
6303
+ { dir: root, file: "package.json", explicit: false }
6304
+ ];
6305
+ for (const c of candidates) {
6306
+ const text = showAt(c.dir, mergeBase, c.file);
6307
+ if (text === null) return null;
6308
+ if (text === void 0) continue;
6309
+ let block;
6310
+ try {
6311
+ block = doctorBlock(JSON.parse(text), c.file, c.explicit);
6312
+ } catch {
6313
+ return null;
6314
+ }
6315
+ if (block === void 0 || c.file === "package.json" && !c.explicit && isPackageDeclaration(block)) {
6316
+ if (c.file === "genesis.config.json") return "absent";
6317
+ continue;
6318
+ }
6319
+ const b = objectOr(block);
6320
+ return { allow: Array.isArray(b.allow) ? b.allow : [], rules: objectOr(b.rules), packageRules: objectOr(b.packageRules) };
6321
+ }
6322
+ return "absent";
6323
+ }
6324
+ function allowGrew(allow, before, base) {
6325
+ const had = new Set(before.map(allowKey));
6326
+ return allow.filter((a) => !had.has(allowKey(a))).map((a) => ({
6327
+ rule: "allow-grew",
6328
+ file: a.file ?? "genesis config",
6329
+ subject: a.rule,
6330
+ message: `allow gained an entry for ${a.rule}${a.match ? ` (${a.match})` : ""} since ${base}; the list only shrinks, so fix what it hides instead`
6331
+ }));
6332
+ }
6333
+ function rulesWeakened(config, before, base) {
6334
+ const out = [];
6335
+ const levelIn = (c, rule) => c.rules?.[rule] ?? c.packageRules?.[rule]?.level;
6336
+ const ids = /* @__PURE__ */ new Set([...Object.keys(config.rules ?? {}), ...Object.keys(config.packageRules ?? {})]);
6337
+ for (const rule of ids) {
6338
+ const set = levelIn(config, rule);
6339
+ if (set === void 0) continue;
6340
+ const was = levelIn(before, rule);
6341
+ if (was === void 0 ? set === "off" : RANK[set] < RANK[was]) {
6342
+ out.push({ rule: "rules-weakened", file: "genesis config", subject: rule, message: `${rule} is set to "${set}"${was ? `, lower than "${was}"` : ""} since ${base}; rules only tighten, so fix what it finds instead` });
6343
+ }
6344
+ }
6345
+ for (const [rule, setting] of Object.entries(config.packageRules ?? {})) {
6346
+ const had = new Set(before.packageRules[rule]?.exclude ?? []);
6347
+ const added = (setting.exclude ?? []).filter((g) => !had.has(g));
6348
+ if (added.length) {
6349
+ out.push({ rule: "rules-weakened", file: "genesis config", subject: rule, message: `packageRules excludes ${added.join(", ")} from ${rule} since ${base}; rules only tighten, so fix what it finds instead` });
6350
+ }
6351
+ }
6352
+ return out;
6353
+ }
6354
+ function touched(file, changed) {
6355
+ if (changed.has(file)) return true;
6356
+ const prefix = file.endsWith("/") ? file : `${file}/`;
6357
+ for (const c of changed) if (c.startsWith(prefix)) return true;
6358
+ return false;
6359
+ }
6360
+ function applyRatchet(findings, options) {
6361
+ const { config, newOnly, changed, base, isAppPath } = options;
6362
+ const ratcheted = (rule) => !NEVER_RATCHETED.has(rule) && (config.ratchet === true || newOnly.has(rule) || Array.isArray(config.ratchet) && config.ratchet.includes(rule));
6363
+ return findings.map((f) => {
6364
+ if (f.level === "info" || !ratcheted(f.rule) || !isAppPath(f.file) || touched(f.file, changed)) return f;
6365
+ return { ...f, level: "info", message: `${f.message} (ratcheted: unchanged since ${base})` };
6366
+ });
6367
+ }
6368
+ var objectOr, allowKey, RANK, NEVER_RATCHETED;
6369
+ var init_ratchet = __esm({
6370
+ "src/doctor/ratchet.ts"() {
6371
+ init_config();
6372
+ objectOr = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
6373
+ allowKey = (a) => `${a.rule}\0${a.file ?? ""}\0${a.match ?? ""}`;
6374
+ RANK = { off: 0, info: 1, warn: 2, error: 3 };
6375
+ NEVER_RATCHETED = /* @__PURE__ */ new Set([
6376
+ ...META_RULES,
6377
+ "stale-exception",
6378
+ "package-rule-override",
6379
+ "package-rules-invalid",
6380
+ "package-doctor-declaration",
6381
+ "plugin-error",
6382
+ "build",
6383
+ "agent-guide-stale",
6384
+ "contracts-stale"
6385
+ ]);
6386
+ }
6387
+ });
6388
+ function primitivesCatalog(packages) {
6389
+ const rows = [...CORE];
6390
+ for (const rule of preferRules(packages)) {
6391
+ rows.push({
6392
+ need: rule.need ?? rule.id.replace(/-/g, " "),
6393
+ use: rule.use,
6394
+ ...rule.import ? { import: rule.import } : {},
6395
+ ...rule.docs ? { docs: rule.docs } : {},
6396
+ rule: rule.ruleId,
6397
+ from: rule.package
6398
+ });
6399
+ }
6400
+ for (const p of packages) {
6401
+ for (const e of p.declaration?.primitives ?? []) {
6402
+ rows.push({ need: e.need, use: e.use, ...e.import ? { import: e.import } : {}, ...e.docs ? { docs: e.docs } : {}, from: p.name });
6403
+ }
6404
+ }
6405
+ return rows;
6406
+ }
6407
+ function primitivesSummary(packages) {
6408
+ const rules = preferRules(packages);
6409
+ const withPlugin = packages.filter((p) => p.declaration?.plugin);
6410
+ return { rules: rules.length + withPlugin.length, packages: (/* @__PURE__ */ new Set([...rules.map((r) => r.package), ...withPlugin.map((p) => p.name)])).size };
6411
+ }
6412
+ function catalogTable(rows, options = {}) {
6413
+ const head = options.docs ? "| Need | Use | Import | Enforced by | Docs |\n| --- | --- | --- | --- | --- |" : "| Need | Use | Import |\n| --- | --- | --- |";
6414
+ const body = rows.map(
6415
+ (r) => options.docs ? `| ${cell(r.need)} | ${cell(r.use)} | ${r.import ? importCell(r.import) : ""} | ${r.rule ? `\`${r.rule}\`` : ""} | ${r.docs ? `[docs](${r.docs})` : ""} |` : `| ${cell(r.need)} | ${cell(r.use)} | ${r.import ? importCell(r.import) : ""} |`
6416
+ );
6417
+ return [head, ...body].join("\n");
6418
+ }
6419
+ function formatPrimitives(rows) {
6420
+ const lines = ["Genesis primitives: what to use for each need (reuse, then extend, then invent).", ""];
6421
+ for (const r of rows) {
6422
+ lines.push(`- ${r.need}: ${r.use}`);
6423
+ if (r.import) lines.push(` import ${r.import}`);
6424
+ if (r.rule) lines.push(` rule ${r.rule}`);
6425
+ if (r.docs) lines.push(` docs ${r.docs}`);
6426
+ }
6427
+ return lines.join("\n");
6428
+ }
6429
+ function renderSkill(rows) {
6430
+ return [
6431
+ "---",
6432
+ "name: genesis",
6433
+ "description: Which Genesis primitive to use for each need (list screens, record pages, forms, data access, dates and more), with its import and docs. Load before writing any screen, list, form or data access in a Genesis app.",
6434
+ "---",
6435
+ "",
6436
+ "<!-- Generated by `genesis agents` from the installed Genesis packages. Don't edit; run `genesis agents` after upgrading Genesis. -->",
6437
+ "",
6438
+ "# Genesis primitives",
6439
+ "",
6440
+ ...RULES.map((r) => `- ${r}`),
6441
+ "",
6442
+ "## What to use for each need",
6443
+ "",
6444
+ catalogTable(rows, { docs: true }),
6445
+ "",
6446
+ "`genesis primitives` prints the same list; `genesis doctor` enforces the rules named above.",
6447
+ ""
6448
+ ].join("\n");
6449
+ }
6450
+ function renderAgentsBlock(rows) {
6451
+ return [
6452
+ AGENTS_START,
6453
+ "## Building with Genesis",
6454
+ "",
6455
+ "Generated by `genesis agents` from the installed Genesis packages. Don't edit this block; run `genesis agents` after upgrading Genesis.",
6456
+ "",
6457
+ `Before writing a screen, read \`${SKILL_PATH}\` (or run \`genesis primitives\`).`,
6458
+ "",
6459
+ ...RULES.map((r) => `- ${r}`),
6460
+ "",
6461
+ catalogTable(rows),
6462
+ AGENTS_END
6463
+ ].join("\n");
6464
+ }
6465
+ function blockSpan(text) {
6466
+ const s = text.indexOf(AGENTS_START);
6467
+ const e = text.indexOf(AGENTS_END);
6468
+ if (s < 0 && e < 0) return "absent";
6469
+ if (s < 0 || e < 0 || e < s || text.indexOf(AGENTS_START, s + 1) >= 0 || text.indexOf(AGENTS_END, e + 1) >= 0) return "broken";
6470
+ return { start: s, end: e + AGENTS_END.length };
6471
+ }
6472
+ function mergeAgentsBlock(agents, block) {
6473
+ const text = agents ?? "# Agent notes\n";
6474
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
6475
+ const own = block.replace(/\n/g, eol);
6476
+ const span = blockSpan(text);
6477
+ if (span === "broken") throw new Error(`AGENTS.md has a broken ${AGENTS_START} \u2026 ${AGENTS_END} block; fix it by hand.`);
6478
+ if (span === "absent") return `${text.replace(/\s*$/, "")}${eol}${eol}${own}${eol}`;
6479
+ return `${text.slice(0, span.start)}${own}${text.slice(span.end)}`;
6480
+ }
6481
+ function currentAgentsBlock(agents) {
6482
+ if (!agents) return null;
6483
+ const span = blockSpan(agents);
6484
+ if (span === "absent") return null;
6485
+ if (span === "broken") return "broken";
6486
+ return agents.slice(span.start, span.end).replace(/\r\n/g, "\n");
6487
+ }
6488
+ function writeAgentGuide(root, packages, agentsFile = "AGENTS.md") {
6489
+ const rows = primitivesCatalog(packages);
6490
+ const changed = [];
6491
+ const agents = path26.join(root, agentsFile);
6492
+ const before = read(agents);
6493
+ const after = mergeAgentsBlock(before, renderAgentsBlock(rows));
6494
+ const skill = path26.join(root, SKILL_PATH);
6495
+ const skillText = renderSkill(rows);
6496
+ if (read(skill)?.replace(/\r\n/g, "\n") !== skillText) {
6497
+ mkdirSync(path26.dirname(skill), { recursive: true });
6498
+ writeFileSync(skill, skillText);
6499
+ changed.push(SKILL_PATH);
6500
+ }
6501
+ if (before !== after) {
6502
+ writeFileSync(agents, after);
6503
+ changed.push(agentsFile);
6504
+ }
6505
+ return changed;
6506
+ }
6507
+ function agentGuideState(root, packages, agentsFile = "AGENTS.md") {
6508
+ const rows = primitivesCatalog(packages);
6509
+ const skill = read(path26.join(root, SKILL_PATH))?.replace(/\r\n/g, "\n") ?? null;
6510
+ const block = currentAgentsBlock(read(path26.join(root, agentsFile)));
6511
+ return {
6512
+ skill: skill === null ? "missing" : skill === renderSkill(rows) ? "ok" : "stale",
6513
+ agents: block === null || block === "broken" ? block ?? "missing" : block === renderAgentsBlock(rows) ? "ok" : "stale"
6514
+ };
6515
+ }
6516
+ function checkAgentGuide(ctx) {
6517
+ const state = agentGuideState(ctx.root, ctx.packages);
6518
+ if (state.skill === "missing" && state.agents === "missing") return;
6519
+ const fix = "run genesis agents and commit the result";
6520
+ if (state.skill !== "ok") {
6521
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: SKILL_PATH, message: `${state.skill === "missing" ? "is missing" : "doesn't match the installed Genesis packages"}; ${fix}` });
6522
+ }
6523
+ if (state.agents !== "ok") {
6524
+ const message = {
6525
+ missing: `has no genesis-primitives block; ${fix}`,
6526
+ broken: `has a broken genesis-primitives block (a ${AGENTS_START} or ${AGENTS_END} marker is missing, repeated or out of order); fix the markers by hand, then ${fix}`,
6527
+ stale: `has a genesis-primitives block that doesn't match the installed Genesis packages; ${fix}`
6528
+ }[state.agents];
6529
+ ctx.report({ rule: "agent-guide-stale", level: "warn", file: "AGENTS.md", message });
6530
+ }
6531
+ }
6532
+ var GENESIS_DOCS, CORE, cell, importCell, SKILL_PATH, AGENTS_START, AGENTS_END, RULES, read;
6533
+ var init_primitives = __esm({
6534
+ "src/doctor/primitives.ts"() {
6535
+ init_package_rules();
6536
+ GENESIS_DOCS = "https://github.com/marktiderman/genesis/blob/main/docs";
6537
+ CORE = [
6538
+ {
6539
+ need: "anything, before building it",
6540
+ use: 'search what exists: `genesis features find <term>`, this catalog, and the doctor\'s "Available but unused" list',
6541
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6542
+ from: "genesis-cli"
6543
+ },
6544
+ {
6545
+ need: "a page inside the app shell",
6546
+ use: "a Genesis page layout (`DashboardPage`, `SettingsPage`, `FormPage`, `DetailPage`, from `@marktiderman/genesis-ui`) or `ResourceView` (from `@marktiderman/genesis-ui/data`)",
6547
+ import: "@marktiderman/genesis-ui",
6548
+ rule: "page-layout",
6549
+ from: "genesis-cli"
6550
+ },
6551
+ {
6552
+ need: "a button, input, table, dialog or other component",
6553
+ use: "the Genesis component, never the raw tag or a local copy",
6554
+ import: "@marktiderman/genesis-ui/<component>",
6555
+ rule: "raw-tag",
6556
+ from: "genesis-cli"
6557
+ },
6558
+ {
6559
+ need: "colors and spacing",
6560
+ use: "semantic tokens (`bg-primary`, `text-muted-foreground`), never literal colors",
6561
+ import: "@marktiderman/genesis-design-system",
6562
+ rule: "raw-color",
6563
+ from: "genesis-cli"
6564
+ },
6565
+ {
6566
+ need: "something no primitive covers",
6567
+ use: "write the gap up for Genesis (an issue or a proposal) first, then invent in the app, on Genesis primitives",
6568
+ docs: `${GENESIS_DOCS}/FRAMEWORK.md`,
6569
+ from: "genesis-cli"
6570
+ }
6571
+ ];
6572
+ cell = (s) => (s ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ").replace(/(`[^`]*`)|<([A-Za-z][\w.]*)>/g, (m, code, name) => code ?? `\`<${name}>\``);
6573
+ importCell = (s) => `\`${s.replace(/`/g, "").replace(/\|/g, "\\|").replace(/\n/g, " ")}\``;
6574
+ SKILL_PATH = ".claude/skills/genesis/SKILL.md";
6575
+ AGENTS_START = "<!-- genesis-primitives:start -->";
6576
+ AGENTS_END = "<!-- genesis-primitives:end -->";
6577
+ RULES = [
6578
+ "Use the Genesis primitive for the need first: reuse, then extend, then invent (docs/FRAMEWORK.md, G1 to G6).",
6579
+ "Never copy an older screen as a template. Old screens predate the primitives; the doctor flags what they did.",
6580
+ "A list screen is a view (`defineView`) rendered by `ResourceView`; a record page is `ResourceWorkspace`; on the phone, `NativeResourceView`.",
6581
+ "Screens never call the database client (`supabase.from`, `.rpc`) directly: reads go through a view or a named data function, writes through the resource's provider rules.",
6582
+ "When no primitive fits, write the gap up for Genesis before inventing, then invent in the app on Genesis primitives.",
6583
+ "Run `genesis doctor` before you finish; it enforces these rules."
6584
+ ];
6585
+ read = (file) => existsSync(file) ? readFileSync(file, "utf8") : null;
6586
+ }
6587
+ });
5391
6588
 
5392
6589
  // src/doctor/index.ts
5393
6590
  var doctor_exports = {};
@@ -5395,9 +6592,17 @@ __export(doctor_exports, {
5395
6592
  BUILTIN_RULES: () => BUILTIN_RULES,
5396
6593
  DoctorConfigError: () => DoctorConfigError,
5397
6594
  GenesisConfigError: () => GenesisConfigError,
6595
+ PackageDeclarationError: () => PackageDeclarationError,
6596
+ SKILL_PATH: () => SKILL_PATH,
6597
+ agentGuideState: () => agentGuideState,
5398
6598
  builtinChecks: () => builtinChecks,
6599
+ catalogTable: () => catalogTable,
6600
+ changedSince: () => changedSince,
6601
+ clearPackageRulesCache: () => clearPackageRulesCache,
5399
6602
  defineDoctorPlugin: () => defineDoctorPlugin,
6603
+ discoverPackages: () => discoverPackages,
5400
6604
  findPackageDir: () => findPackageDir,
6605
+ formatPrimitives: () => formatPrimitives,
5401
6606
  formatReport: () => formatReport,
5402
6607
  genesisInstalls: () => genesisInstalls,
5403
6608
  genesisSummary: () => genesisSummary,
@@ -5407,33 +6612,45 @@ __export(doctor_exports, {
5407
6612
  nativeLayouts: () => nativeLayouts,
5408
6613
  parseExportNames: () => parseExportNames,
5409
6614
  parseRulesMarkdown: () => parseRulesMarkdown,
6615
+ postgresContract: () => postgresContract,
6616
+ postgresSource: () => postgresSource,
6617
+ preferRules: () => preferRules,
6618
+ primitivesCatalog: () => primitivesCatalog,
6619
+ primitivesSummary: () => primitivesSummary,
5410
6620
  readGenesisConfig: () => readGenesisConfig,
5411
6621
  readPackageExports: () => readPackageExports,
5412
6622
  readReleaseManifest: () => readReleaseManifest,
6623
+ renderAgentsBlock: () => renderAgentsBlock,
6624
+ renderSkill: () => renderSkill,
5413
6625
  routesDir: () => routesDir,
6626
+ ruleNamespace: () => ruleNamespace,
5414
6627
  runDoctor: () => runDoctor,
5415
6628
  satisfies: () => satisfies,
5416
6629
  sqlStatements: () => sqlStatements,
5417
6630
  toJson: () => toJson,
5418
6631
  validateConfig: () => validateConfig,
6632
+ validateDeclaration: () => validateDeclaration,
5419
6633
  validateLinks: () => validateLinks,
5420
- webRoutes: () => webRoutes
6634
+ webRoutes: () => webRoutes,
6635
+ writeAgentGuide: () => writeAgentGuide
5421
6636
  });
5422
6637
  async function runDoctor(options = {}) {
5423
- const root = path23.resolve(options.root ?? process.cwd());
6638
+ const root = path26.resolve(options.root ?? process.cwd());
5424
6639
  const loaded = options.config ? { config: options.config, dir: root } : loadConfig(root, options.configPath);
5425
6640
  const config = loaded.config;
5426
6641
  const genesis = options.genesis ?? loadGenesis(root, config);
5427
6642
  const files = scanFiles(root, config);
5428
6643
  const patterns = loadPatternRules(root, config.patterns, config.rulesDoc);
5429
6644
  const plugins = await loadPlugins(config.plugins, loaded.dir);
6645
+ const packages = discoverPackages(root);
6646
+ const packagePlugins = await packageRulesPlugins(packages);
5430
6647
  const builtinIds = new Set(BUILTIN_RULES);
5431
6648
  for (const p of config.patterns ?? []) {
5432
- if (builtinIds.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
6649
+ if (builtinIds.has(p.id) || META_RULES.has(p.id)) throw new DoctorConfigError(`doctor.patterns: "${p.id}" is a built-in rule id; pick another`);
5433
6650
  }
5434
6651
  const raw = [];
5435
- const ctx = { root, files, genesis, config, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
5436
- for (const plugin of [...builtinChecks(config), ...patterns ? [patterns.plugin] : [], ...plugins]) {
6652
+ const ctx = { root, files, genesis, config, packages, ...options.base ? { base: options.base } : {}, report: (f) => raw.push(f) };
6653
+ for (const plugin of [...builtinChecks(config, { contracts: options.contracts ?? true }), ...packagePlugins, ...patterns ? [patterns.plugin] : [], ...plugins]) {
5437
6654
  try {
5438
6655
  await plugin.check(ctx);
5439
6656
  } catch (err) {
@@ -5445,7 +6662,34 @@ async function runDoctor(options = {}) {
5445
6662
  const failure = runBuild(root, buildCommands(root, config), options.quietBuild ?? false);
5446
6663
  if (failure) raw.push(failure);
5447
6664
  }
5448
- const findings = applyConfig(raw, config);
6665
+ raw.push(...unknownPackageRuleSettings(config, packages, raw));
6666
+ const newOnly = /* @__PURE__ */ new Set([...patterns?.newOnly ?? [], ...preferRules(packages).filter((r) => r.newOnly).map((r) => r.ruleId)]);
6667
+ let changed = null;
6668
+ let skipped = false;
6669
+ if (options.base && (newOnly.size > 0 || config.ratchet)) {
6670
+ changed = options.changedFiles ? new Set(options.changedFiles) : changedSince(root, options.base);
6671
+ skipped ||= !changed;
6672
+ }
6673
+ const configFile = "file" in loaded ? loaded.file : null;
6674
+ const guarded = (config.allow?.length ?? 0) + Object.keys(config.rules ?? {}).length + Object.keys(config.packageRules ?? {}).length > 0;
6675
+ let configSkipped = false;
6676
+ if (options.base && configFile) {
6677
+ const before = configAtBase(root, options.base, options.configPath !== void 0 ? configFile : void 0);
6678
+ if (before && before !== "absent") {
6679
+ raw.push(...allowGrew(config.allow ?? [], before.allow, options.base));
6680
+ raw.push(...rulesWeakened(config, before, options.base));
6681
+ }
6682
+ configSkipped = !before && guarded;
6683
+ }
6684
+ if (skipped || configSkipped) {
6685
+ raw.push(
6686
+ configSkipped ? { rule: "ratchet-skipped", level: "error", file: "genesis config", message: `couldn't compare allow, rules and packageRules against ${options.base} (not a git repository, or the ref isn't fetched; in CI check out with fetch-depth: 0)` } : { rule: "ratchet-skipped", level: "warn", file: "genesis config", message: `couldn't compare against ${options.base} (not a git repository, or the ref isn't fetched); every rule ran at its full level` }
6687
+ );
6688
+ }
6689
+ let findings = applyConfig(raw, config, packageRuleIds(packages));
6690
+ if (options.base && changed) {
6691
+ findings = applyRatchet(findings, { config, newOnly, changed, base: options.base, isAppPath: (f) => existsSync(path26.join(root, f)) });
6692
+ }
5449
6693
  const errors = findings.filter((f) => f.level === "error").length;
5450
6694
  const warnings = findings.filter((f) => f.level === "warn").length;
5451
6695
  const infos = findings.length - errors - warnings;
@@ -5456,12 +6700,13 @@ async function runDoctor(options = {}) {
5456
6700
  findings,
5457
6701
  unused: unusedComponents(ctx),
5458
6702
  ruleCount: (patterns?.count ?? 0) + plugins.length,
6703
+ primitives: primitivesSummary(packages),
5459
6704
  errors,
5460
6705
  warnings,
5461
6706
  infos
5462
6707
  };
5463
6708
  }
5464
- function builtinChecks(config) {
6709
+ function builtinChecks(config, options = {}) {
5465
6710
  const packs = {
5466
6711
  native: { name: "native", check: checkNativePack },
5467
6712
  supabase: { name: "supabase", check: checkSupabasePack },
@@ -5485,14 +6730,28 @@ function builtinChecks(config) {
5485
6730
  { name: "resource-view-trees", check: checkTreeViews },
5486
6731
  { name: "studio-server-imports", check: checkStudioServerImports },
5487
6732
  { name: "removed-scope-names", check: checkRemovedScopeNames },
5488
- ...(config.packs ?? []).map((p) => packs[p])
6733
+ { name: "agent-guide", check: checkAgentGuide },
6734
+ ...(config.packs ?? []).map((p) => packs[p]),
6735
+ ...config.packs?.includes("supabase") && config.contracts && options.contracts !== false ? [{ name: "contracts", check: (ctx) => checkContracts(ctx) }] : []
5489
6736
  ];
5490
6737
  }
5491
- function applyConfig(raw, config) {
6738
+ function applyConfig(raw, config, packageIds) {
5492
6739
  const allow = (config.allow ?? []).map((entry) => ({ entry, file: entry.file ? globToRegExp(entry.file) : null, used: false }));
5493
6740
  const out = [];
6741
+ const levelOf = (rule) => META_RULES.has(rule) ? void 0 : config.rules?.[rule] ?? config.packageRules?.[rule]?.level;
6742
+ for (const [rule, level] of Object.entries(config.rules ?? {})) {
6743
+ if (!packageIds.has(rule) || config.packageRules?.[rule]?.reason) continue;
6744
+ out.push({
6745
+ rule: "package-rule-override",
6746
+ level: "warn",
6747
+ file: "genesis config",
6748
+ line: 0,
6749
+ subject: rule,
6750
+ message: `rules sets the package rule ${rule} to "${level}" without a reason; move it to doctor.packageRules["${rule}"] with { "level": "${level}", "reason": "\u2026" }`
6751
+ });
6752
+ }
5494
6753
  for (const input of raw) {
5495
- const setting = config.rules?.[input.rule];
6754
+ const setting = levelOf(input.rule);
5496
6755
  if (setting === "off") continue;
5497
6756
  const finding = {
5498
6757
  rule: input.rule,
@@ -5503,7 +6762,7 @@ function applyConfig(raw, config) {
5503
6762
  ...input.subject !== void 0 ? { subject: input.subject } : {}
5504
6763
  };
5505
6764
  const exception = allow.find(
5506
- (a) => a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
6765
+ (a) => !META_RULES.has(finding.rule) && a.entry.rule === finding.rule && (!a.file || a.file.test(finding.file)) && (a.entry.match === void 0 || a.entry.match === finding.subject)
5507
6766
  );
5508
6767
  if (exception) {
5509
6768
  exception.used = true;
@@ -5513,7 +6772,7 @@ function applyConfig(raw, config) {
5513
6772
  }
5514
6773
  const staleLevel = config.rules?.["stale-exception"];
5515
6774
  for (const a of allow) {
5516
- if (staleLevel === "off" || a.used || config.rules?.[a.entry.rule] === "off") continue;
6775
+ if (staleLevel === "off" || a.used || levelOf(a.entry.rule) === "off") continue;
5517
6776
  out.push({
5518
6777
  rule: "stale-exception",
5519
6778
  level: staleLevel ?? "warn",
@@ -5534,6 +6793,7 @@ function formatReport(result) {
5534
6793
  lines.push(`${f.level.toUpperCase().padEnd(5)} ${f.file}${f.line ? `:${f.line}` : ""} [${f.rule}] ${f.message}`);
5535
6794
  }
5536
6795
  lines.push(`Available but unused (${result.unused.length}): ${result.unused.join(", ") || "none"}`);
6796
+ lines.push(`Primitives: ${result.primitives.rules} rules from ${result.primitives.packages} packages; see genesis primitives`);
5537
6797
  const info = result.infos ? `, ${result.infos} info` : "";
5538
6798
  lines.push(result.ok ? `PASS (${result.warnings} warnings${info})` : `FAIL (${result.errors} errors, ${result.warnings} warnings${info})`);
5539
6799
  return lines.join("\n");
@@ -5546,7 +6806,8 @@ function toJson(result) {
5546
6806
  warnings: result.warnings,
5547
6807
  infos: result.infos,
5548
6808
  findings: result.findings,
5549
- unused: result.unused
6809
+ unused: result.unused,
6810
+ primitives: result.primitives
5550
6811
  };
5551
6812
  }
5552
6813
  function genesisSummary(g) {
@@ -5577,6 +6838,10 @@ var init_doctor = __esm({
5577
6838
  init_structure();
5578
6839
  init_dates();
5579
6840
  init_api_usage();
6841
+ init_package_rules();
6842
+ init_ratchet();
6843
+ init_contracts();
6844
+ init_primitives();
5580
6845
  init_config();
5581
6846
  init_genesis();
5582
6847
  init_patterns();
@@ -5589,6 +6854,10 @@ var init_doctor = __esm({
5589
6854
  init_installs();
5590
6855
  init_semver();
5591
6856
  init_routes();
6857
+ init_package_rules();
6858
+ init_primitives();
6859
+ init_ratchet();
6860
+ init_contracts();
5592
6861
  }
5593
6862
  });
5594
6863
 
@@ -5602,44 +6871,44 @@ __export(features_exports, {
5602
6871
  runFeaturesCheck: () => runFeaturesCheck,
5603
6872
  runFeaturesFind: () => runFeaturesFind
5604
6873
  });
5605
- function isObject3(value) {
6874
+ function isObject4(value) {
5606
6875
  return typeof value === "object" && value !== null && !Array.isArray(value);
5607
6876
  }
5608
6877
  function readObject(file, key2) {
5609
6878
  try {
5610
6879
  const json = JSON.parse(readFileSync(file, "utf-8"));
5611
- return isObject3(json[key2]) ? json[key2] : {};
6880
+ return isObject4(json[key2]) ? json[key2] : {};
5612
6881
  } catch {
5613
6882
  return {};
5614
6883
  }
5615
6884
  }
5616
6885
  function settings(root, options) {
5617
- const fromPackage = readObject(path23.join(root, "package.json"), "genesisFeatures");
5618
- const fromConfig = readObject(path23.join(root, "genesis.config.json"), "features");
6886
+ const fromPackage = readObject(path26.join(root, "package.json"), "genesisFeatures");
6887
+ const fromConfig = readObject(path26.join(root, "genesis.config.json"), "features");
5619
6888
  const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
5620
6889
  return { ...fromPackage, ...fromConfig, ...given };
5621
6890
  }
5622
6891
  async function loadRegistry(input) {
5623
- const root = path23.resolve(input.dir);
6892
+ const root = path26.resolve(input.dir);
5624
6893
  const options = settings(root, input);
5625
- const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path23.join(root, p)));
5626
- if (!registry || !existsSync(path23.join(root, registry))) {
6894
+ const registry = options.registry ?? DEFAULT_REGISTRIES.find((p) => existsSync(path26.join(root, p)));
6895
+ if (!registry || !existsSync(path26.join(root, registry))) {
5627
6896
  throw new Error(`No feature registry found. Looked for ${options.registry ?? DEFAULT_REGISTRIES.join(" and ")}; pass --registry.`);
5628
6897
  }
5629
- const jiti = createJiti(path23.join(root, "package.json"), { moduleCache: false });
5630
- const load = async (file) => await jiti.import(path23.join(root, file));
6898
+ const jiti = createJiti(path26.join(root, "package.json"), { moduleCache: false });
6899
+ const load = async (file) => await jiti.import(path26.join(root, file));
5631
6900
  const mod = await load(registry);
5632
6901
  const features2 = mod.features ?? mod.default;
5633
- if (!isObject3(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
6902
+ if (!isObject4(features2)) throw new Error(`${registry} must export \`features\` (from defineFeatures).`);
5634
6903
  const flags = options.flagsFile ? (await load(options.flagsFile)).flags : mod.flags;
5635
- if (flags !== void 0 && !isObject3(flags)) {
6904
+ if (flags !== void 0 && !isObject4(flags)) {
5636
6905
  throw new Error(`${options.flagsFile ?? registry}'s \`flags\` export must be an object (from defineFlags).`);
5637
6906
  }
5638
6907
  const { dir: _dir, registry: _registry, flagsFile: _flagsFile, prs: _prs, gh: _gh, ...rest } = options;
5639
6908
  const project = {
5640
6909
  ...rest,
5641
6910
  root,
5642
- source: options.source ?? registry.split(path23.sep).join("/"),
6911
+ source: options.source ?? registry.split(path26.sep).join("/"),
5643
6912
  features: features2,
5644
6913
  flags
5645
6914
  };
@@ -5749,8 +7018,8 @@ function routeTags(source) {
5749
7018
  }
5750
7019
  function wireStudioRoute(source, route, pageImportPath) {
5751
7020
  const tags = routeTags(source);
5752
- const relative9 = route.replace(/^\//, "");
5753
- const existing = tags.find((t) => new RegExp(`path=["'](/?${relative9.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
7021
+ const relative10 = route.replace(/^\//, "");
7022
+ const existing = tags.find((t) => new RegExp(`path=["'](/?${relative10.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})["']`).test(t.text));
5754
7023
  if (existing) {
5755
7024
  return { skipped: `Your router already has a page at ${route}. Replace its element with <DataStudioPage /> to use the studio there.` };
5756
7025
  }
@@ -5758,17 +7027,17 @@ function wireStudioRoute(source, route, pageImportPath) {
5758
7027
  const roots = layouts.length ? layouts : tags.filter((t) => !t.selfClosing && t.close !== void 0 && /path=["']\/["']/.test(t.text));
5759
7028
  if (roots.length !== 1) {
5760
7029
  return {
5761
- skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative9}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
7030
+ skipped: roots.length === 0 ? `No layout route found to put the page under. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.` : `More than one layout route; add <Route path="${relative10}" element={<DataStudioPage />} /> inside the one your other admin pages use.`
5762
7031
  };
5763
7032
  }
5764
7033
  const layout = roots[0];
5765
7034
  const base = (/\bpath=["']([^"']*)["']/.exec(layout.text)?.[1] ?? "").replace(/^\/+|\/+$/g, "");
5766
- if (base && !relative9.startsWith(`${base}/`)) {
7035
+ if (base && !relative10.startsWith(`${base}/`)) {
5767
7036
  return {
5768
7037
  skipped: `Your layout route lives at /${base}, outside ${route}. Add <Route path="${route}" element={<DataStudioPage />} /> where your app's other pages are.`
5769
7038
  };
5770
7039
  }
5771
- const childPath = base ? relative9.slice(base.length + 1) : relative9;
7040
+ const childPath = base ? relative10.slice(base.length + 1) : relative10;
5772
7041
  const guard = GUARD.exec(source)?.[1];
5773
7042
  const element = guard ? `<${guard}><DataStudioPage /></${guard}>` : "<DataStudioPage />";
5774
7043
  const before = source.slice(0, layout.close);
@@ -6168,9 +7437,9 @@ function ownedKeyProblem(key2, source, localNames = /* @__PURE__ */ new Set()) {
6168
7437
  return `${key2} doesn't match its source ${source}`;
6169
7438
  }
6170
7439
  function mergeThreeWay(mine, base, theirs) {
6171
- const dir = mkdtempSync(path23.join(tmpdir(), "genesis-merge-"));
7440
+ const dir = mkdtempSync(path26.join(tmpdir(), "genesis-merge-"));
6172
7441
  try {
6173
- const [m, b, t] = ["mine", "base", "theirs"].map((n) => path23.join(dir, n));
7442
+ const [m, b, t] = ["mine", "base", "theirs"].map((n) => path26.join(dir, n));
6174
7443
  writeFileSync(m, mine);
6175
7444
  writeFileSync(b, base);
6176
7445
  writeFileSync(t, theirs);
@@ -6340,12 +7609,12 @@ var init_registry_edit = __esm({
6340
7609
  });
6341
7610
  function routerRoot2(root) {
6342
7611
  try {
6343
- const config = JSON.parse(readFileSync(path23.join(root, "genesis.config.json"), "utf8"));
7612
+ const config = JSON.parse(readFileSync(path26.join(root, "genesis.config.json"), "utf8"));
6344
7613
  const configured = config.doctor?.native?.routerRoot;
6345
- if (configured && existsSync(path23.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
7614
+ if (configured && existsSync(path26.join(root, configured, "_layout.tsx"))) return configured.replace(/\/+$/, "");
6346
7615
  } catch {
6347
7616
  }
6348
- for (const dir of ["src/app", "app"]) if (existsSync(path23.join(root, dir, "_layout.tsx"))) return dir;
7617
+ for (const dir of ["src/app", "app"]) if (existsSync(path26.join(root, dir, "_layout.tsx"))) return dir;
6349
7618
  return null;
6350
7619
  }
6351
7620
  function routeOf(file) {
@@ -6406,23 +7675,23 @@ __export(add_exports, {
6406
7675
  });
6407
7676
  function appDependencies(root) {
6408
7677
  try {
6409
- const pkg = JSON.parse(readFileSync(path23.join(root, "package.json"), "utf8"));
7678
+ const pkg = JSON.parse(readFileSync(path26.join(root, "package.json"), "utf8"));
6410
7679
  return { ...pkg["dependencies"], ...pkg["devDependencies"], ...pkg["optionalDependencies"] };
6411
7680
  } catch {
6412
7681
  return {};
6413
7682
  }
6414
7683
  }
6415
7684
  function registryFile(root) {
6416
- const read = (file, key2) => {
7685
+ const read2 = (file, key2) => {
6417
7686
  try {
6418
- const v = JSON.parse(readFileSync(path23.join(root, file), "utf8"))[key2]?.registry;
7687
+ const v = JSON.parse(readFileSync(path26.join(root, file), "utf8"))[key2]?.registry;
6419
7688
  return typeof v === "string" ? v : void 0;
6420
7689
  } catch {
6421
7690
  return void 0;
6422
7691
  }
6423
7692
  };
6424
- const named = read("genesis.config.json", "features") ?? read("package.json", "genesisFeatures");
6425
- for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path23.join(root, candidate))) return candidate;
7693
+ const named = read2("genesis.config.json", "features") ?? read2("package.json", "genesisFeatures");
7694
+ for (const candidate of named ? [named] : ["src/features.ts", "features.ts"]) if (existsSync(path26.join(root, candidate))) return candidate;
6426
7695
  return null;
6427
7696
  }
6428
7697
  async function registryIds(root, file) {
@@ -6499,7 +7768,7 @@ verify_jwt = false
6499
7768
  return { content: `${config.replace(/\s*$/, "\n")}${add}`, names };
6500
7769
  }
6501
7770
  async function runAdd(options) {
6502
- const root = path23.resolve(options.root);
7771
+ const root = path26.resolve(options.root);
6503
7772
  const log = options.log ?? SILENT;
6504
7773
  const now = options.now ?? /* @__PURE__ */ new Date();
6505
7774
  const warnings = [];
@@ -6676,7 +7945,7 @@ __export(migrate_exports, {
6676
7945
  runMigrate: () => runMigrate
6677
7946
  });
6678
7947
  async function runMigrate(options) {
6679
- const root = path23.resolve(options.root);
7948
+ const root = path26.resolve(options.root);
6680
7949
  const lock = readLock(root);
6681
7950
  const warnings = [];
6682
7951
  const ids = [.../* @__PURE__ */ new Set([...Object.keys(lock.blocks), ...options.blocks ?? []])];
@@ -6744,11 +8013,11 @@ function npmLookup(cwd) {
6744
8013
  if (!EXACT_OR_TAG.test(target)) throw new Error(`--version must be an exact version or a dist-tag, not "${target}"`);
6745
8014
  const version = JSON.parse(npm(["view", `${UMBRELLA}@${target}`, "version", "--json"], cwd) || "null");
6746
8015
  if (typeof version !== "string") throw new Error(`${UMBRELLA}@${target} is not one published version`);
6747
- const tmp = mkdtempSync(path23.join(tmpdir(), "genesis-umbrella-"));
8016
+ const tmp = mkdtempSync(path26.join(tmpdir(), "genesis-umbrella-"));
6748
8017
  try {
6749
8018
  const [packed] = JSON.parse(npm(["pack", `${UMBRELLA}@${version}`, "--pack-destination", tmp, "--json"], cwd));
6750
- execFileSync("tar", ["-xzf", path23.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
6751
- const manifest = JSON.parse(readFileSync(path23.join(tmp, "package/dist/versions.json"), "utf8"));
8019
+ execFileSync("tar", ["-xzf", path26.join(tmp, packed.filename), "-C", tmp, "package/dist/versions.json"]);
8020
+ const manifest = JSON.parse(readFileSync(path26.join(tmp, "package/dist/versions.json"), "utf8"));
6752
8021
  if (manifest.version !== version) throw new Error(`${UMBRELLA}@${version} ships a versions.json for ${manifest.version}`);
6753
8022
  return manifest;
6754
8023
  } finally {
@@ -6775,7 +8044,7 @@ function packageJsons(root) {
6775
8044
  if (files.length) return files;
6776
8045
  } catch {
6777
8046
  }
6778
- return existsSync(path23.join(root, "package.json")) ? ["package.json"] : [];
8047
+ return existsSync(path26.join(root, "package.json")) ? ["package.json"] : [];
6779
8048
  }
6780
8049
  function sourceText(root, source, substitutions) {
6781
8050
  const { package: pkg, path: rel } = parseSource(source);
@@ -6794,11 +8063,11 @@ function sourceText(root, source, substitutions) {
6794
8063
  }
6795
8064
  }
6796
8065
  async function runUpgrade(options) {
6797
- const root = path23.resolve(options.root);
8066
+ const root = path26.resolve(options.root);
6798
8067
  const log = options.log ?? (() => {
6799
8068
  });
6800
8069
  const lookup = options.lookup ?? npmLookup(root);
6801
- const release = options.manifest ? JSON.parse(readFileSync(path23.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
8070
+ const release = options.manifest ? JSON.parse(readFileSync(path26.resolve(options.manifest), "utf8")) : lookup.release(options.version ?? "latest");
6802
8071
  const pinned = { [UMBRELLA]: release.version, ...release.packages };
6803
8072
  const wanted = (name) => pinned[name] ?? lookup.latest(name);
6804
8073
  const prBase = options.pr && !options.dryRun ? checkPullRequest(root, release.version) : void 0;
@@ -6916,9 +8185,9 @@ async function runUpgrade(options) {
6916
8185
  const lines = [bumpSummary(release.version, changes, skipped)];
6917
8186
  if (codemodRuns.length) lines.push("", "Codemods:", "", ...codemodRuns.map((c) => `- ${c.id}${c.files.length ? `: ${c.files.join(", ")}` : ""}`));
6918
8187
  if (breaks.length) lines.push("", "Major moves with no codemod (read their changelogs):", "", ...breaks.map((b) => `- \`${b.name}\` ${b.from} \u2192 ${b.to}`));
6919
- const touched = refreshed.filter((r) => r.outcome !== "unchanged");
6920
- if (touched.length || added.length) {
6921
- lines.push("", options.dryRun ? "Files Genesis owns (against the packages installed now; a real run compares with the new versions after the install):" : "Files Genesis owns:", "", ...touched.map((r) => `- ${r.path}: ${r.outcome}${r.detail ? ` (${r.detail})` : ""}`), ...added.map((a) => `- ${a}: added`));
8188
+ const touched2 = refreshed.filter((r) => r.outcome !== "unchanged");
8189
+ if (touched2.length || added.length) {
8190
+ lines.push("", options.dryRun ? "Files Genesis owns (against the packages installed now; a real run compares with the new versions after the install):" : "Files Genesis owns:", "", ...touched2.map((r) => `- ${r.path}: ${r.outcome}${r.detail ? ` (${r.detail})` : ""}`), ...added.map((a) => `- ${a}: added`));
6922
8191
  }
6923
8192
  if (next.size) lines.push("", "Review and delete these before merging (not committed by --pr):", "", ...[...next].map((n) => `- ${n}`));
6924
8193
  if (lock.substitutions && Object.keys(lock.substitutions).length) lines.push("", `Templates renamed with genesis.lock.json's substitutions: ${Object.entries(lock.substitutions).map(([a, b]) => `${a} \u2192 ${b}`).join(", ")}.`);
@@ -6934,7 +8203,7 @@ function checkSubstitutions(substitutions) {
6934
8203
  if (!substitutions || !Object.keys(substitutions).length) return;
6935
8204
  let allowed;
6936
8205
  try {
6937
- const was = starterIdentity(readFileSync(path23.join(starterDir(), "starter.config.ts"), "utf8"));
8206
+ const was = starterIdentity(readFileSync(path26.join(starterDir(), "starter.config.ts"), "utf8"));
6938
8207
  allowed = [was.name, was.slug, was.scheme, was.bundleId];
6939
8208
  } catch {
6940
8209
  allowed = [];
@@ -6946,15 +8215,15 @@ function checkSubstitutions(substitutions) {
6946
8215
  }
6947
8216
  }
6948
8217
  function checkPullRequest(root, version) {
6949
- const git3 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6950
- if (git3("status", "--porcelain")) throw new Error("--pr needs a clean working tree (commit or stash your changes first).");
6951
- const base = git3("rev-parse", "--abbrev-ref", "HEAD");
8218
+ const git4 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8219
+ if (git4("status", "--porcelain")) throw new Error("--pr needs a clean working tree (commit or stash your changes first).");
8220
+ const base = git4("rev-parse", "--abbrev-ref", "HEAD");
6952
8221
  if (base === "HEAD") throw new Error("--pr needs a branch checked out, not a detached HEAD.");
6953
8222
  const branch = `genesis-upgrade/${version}`;
6954
- git3("check-ref-format", "--branch", branch);
8223
+ git4("check-ref-format", "--branch", branch);
6955
8224
  let exists = true;
6956
8225
  try {
6957
- git3("rev-parse", "--verify", "--quiet", `refs/heads/${branch}`);
8226
+ git4("rev-parse", "--verify", "--quiet", `refs/heads/${branch}`);
6958
8227
  } catch {
6959
8228
  exists = false;
6960
8229
  }
@@ -6962,20 +8231,20 @@ function checkPullRequest(root, version) {
6962
8231
  return base;
6963
8232
  }
6964
8233
  function openPullRequest(root, version, report, base) {
6965
- const git3 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
8234
+ const git4 = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
6966
8235
  const branch = `genesis-upgrade/${version}`;
6967
- git3("switch", "-c", branch);
6968
- const top = git3("rev-parse", "--show-toplevel");
8236
+ git4("switch", "-c", branch);
8237
+ const top = git4("rev-parse", "--show-toplevel");
6969
8238
  const lockfiles = [];
6970
- for (let dir = path23.resolve(root); ; dir = path23.dirname(dir)) {
6971
- for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path23.join(dir, f))) lockfiles.push(path23.relative(root, path23.join(dir, f)));
6972
- if (lockfiles.length || dir === top || path23.dirname(dir) === dir) break;
6973
- }
6974
- const paths = [...report.files.filter((f) => existsSync(path23.join(root, f))), ...lockfiles];
6975
- git3("add", "--", ...paths);
6976
- git3("commit", "-q", "-m", `chore(deps): upgrade Genesis to ${version}`);
6977
- git3("push", "-u", "origin", branch);
6978
- const body = path23.join(mkdtempSync(path23.join(tmpdir(), "genesis-pr-")), "body.md");
8239
+ for (let dir = path26.resolve(root); ; dir = path26.dirname(dir)) {
8240
+ for (const f of ["pnpm-lock.yaml", "bun.lock", "bun.lockb", "package-lock.json", "yarn.lock"]) if (existsSync(path26.join(dir, f))) lockfiles.push(path26.relative(root, path26.join(dir, f)));
8241
+ if (lockfiles.length || dir === top || path26.dirname(dir) === dir) break;
8242
+ }
8243
+ const paths = [...report.files.filter((f) => existsSync(path26.join(root, f))), ...lockfiles];
8244
+ git4("add", "--", ...paths);
8245
+ git4("commit", "-q", "-m", `chore(deps): upgrade Genesis to ${version}`);
8246
+ git4("push", "-u", "origin", branch);
8247
+ const body = path26.join(mkdtempSync(path26.join(tmpdir(), "genesis-pr-")), "body.md");
6979
8248
  writeFileSync(body, `${report.summary}
6980
8249
 
6981
8250
  Opened by \`genesis upgrade --pr\`.
@@ -7099,9 +8368,9 @@ async function runScaffold(opts, fs2) {
7099
8368
  function joinPath(...parts) {
7100
8369
  return parts.filter(Boolean).join("/").replace(/\/+/g, "/");
7101
8370
  }
7102
- function dirname(path37) {
7103
- const idx = path37.lastIndexOf("/");
7104
- return idx === -1 ? "." : path37.slice(0, idx);
8371
+ function dirname(path41) {
8372
+ const idx = path41.lastIndexOf("/");
8373
+ return idx === -1 ? "." : path41.slice(0, idx);
7105
8374
  }
7106
8375
  function brandPackageJson(consumer, genesisVersion) {
7107
8376
  return JSON.stringify(
@@ -7340,7 +8609,7 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
7340
8609
  const { runInitNative: runInitNative2 } = await Promise.resolve().then(() => (init_init_native(), init_native_exports));
7341
8610
  const result2 = await runInitNative2({
7342
8611
  name: consumer,
7343
- target: path23.resolve(opts.target ?? consumer),
8612
+ target: path26.resolve(opts.target ?? consumer),
7344
8613
  ...opts.displayName ? { displayName: opts.displayName } : {},
7345
8614
  ...opts.bundleId ? { bundleId: opts.bundleId } : {},
7346
8615
  ...opts.scheme ? { scheme: opts.scheme } : {}
@@ -7350,7 +8619,7 @@ program.command("init").description("Scaffold a new Genesis consumer (brand pack
7350
8619
  console.log(` Genesis packages: ${Object.entries(result2.dependencies).map(([n, v]) => `${n}@${v}`).join(", ")}`);
7351
8620
  console.log("");
7352
8621
  console.log("Next steps:");
7353
- [`cd ${path23.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
8622
+ [`cd ${path26.relative(process.cwd(), result2.target) || "."} && pnpm install (or your package manager)`, ...result2.steps].forEach((s, i) => console.log(` ${i + 1}. ${s}`));
7354
8623
  return;
7355
8624
  }
7356
8625
  opts.target ??= process.cwd();
@@ -7413,13 +8682,13 @@ program.command("introspect").description("Write a checked-in contract (resource
7413
8682
  } finally {
7414
8683
  await sql.end();
7415
8684
  }
7416
- source = `Postgres (${schemas.join(", ")})`;
8685
+ source = (await Promise.resolve().then(() => (init_contracts(), contracts_exports))).postgresSource(schemas);
7417
8686
  }
7418
8687
  const content = emitContracts2(tables, { source });
7419
- const target = path23.resolve(opts.out);
8688
+ const target = path26.resolve(opts.out);
7420
8689
  if (opts.check) {
7421
8690
  const current = await fs.readFile(target, "utf-8").catch(() => null);
7422
- if (current !== content) {
8691
+ if (current?.replace(/\r\n/g, "\n") !== content) {
7423
8692
  console.error(`\u2717 ${opts.out} is out of date. Run \`genesis introspect\` and commit the result.`);
7424
8693
  process.exit(1);
7425
8694
  }
@@ -7429,9 +8698,9 @@ program.command("introspect").description("Write a checked-in contract (resource
7429
8698
  await fs.writeFile(target, content, "utf-8");
7430
8699
  console.log(`\u2714 Wrote ${opts.out}: ${tables.length} tables.`);
7431
8700
  });
7432
- program.command("doctor").description("Check this app against the installed Genesis: components, tokens, imports, colors, plus the app's own rules").option("--strict", "Fail on warnings too", false).option("--json", "Print the report as JSON", false).option("--build", "Also run the app's typecheck and build (doctor.build, or its typecheck/build scripts)", false).option("-c, --config <path>", 'Config file (default: genesis.config.json, then package.json "genesis")').option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--print-genesis", "Print the components, tokens and raw tags read from Genesis, and exit", false).option("--base <ref>", "The git ref change checks compare against (the packages pack's change gate), e.g. origin/main").action(async (opts) => {
8701
+ program.command("doctor").description("Check this app against the installed Genesis: components, tokens, imports, colors, plus the app's own rules").option("--strict", "Fail on warnings too", false).option("--json", "Print the report as JSON", false).option("--build", "Also run the app's typecheck and build (doctor.build, or its typecheck/build scripts)", false).option("-c, --config <path>", 'Config file (default: genesis.config.json, then package.json "genesis")').option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--print-genesis", "Print the components, tokens and raw tags read from Genesis, and exit", false).option("--base <ref>", "The git ref change checks compare against (the packages pack's change gate, and the ratchet: newOnly rules report unchanged files as info), e.g. origin/main").action(async (opts) => {
7433
8702
  const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
7434
- const root = path23.resolve(opts.dir);
8703
+ const root = path26.resolve(opts.dir);
7435
8704
  try {
7436
8705
  if (opts.printGenesis) {
7437
8706
  const { config } = doctor.loadConfig(root, opts.config);
@@ -7448,6 +8717,45 @@ program.command("doctor").description("Check this app against the installed Gene
7448
8717
  process.exitCode = 2;
7449
8718
  }
7450
8719
  });
8720
+ program.command("primitives").description("Print the Genesis primitives catalog: for each need, what to use, its import and docs, from every installed Genesis package's declarations").option("--json", "Print the catalog as JSON", false).option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
8721
+ const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
8722
+ const packages = doctor.discoverPackages(path26.resolve(opts.dir));
8723
+ const rows = doctor.primitivesCatalog(packages);
8724
+ const broken = packages.filter((p) => p.error);
8725
+ if (opts.json) {
8726
+ console.log(JSON.stringify({ primitives: rows, ...doctor.primitivesSummary(packages), errors: broken.map((p) => p.error) }, null, 2));
8727
+ } else {
8728
+ console.log(doctor.formatPrimitives(rows));
8729
+ }
8730
+ for (const p of broken) console.error(`! ${p.error}`);
8731
+ for (const note of packages.flatMap((p) => p.ignored ?? [])) console.error(`! ${note}`);
8732
+ if (broken.length) process.exitCode = 1;
8733
+ });
8734
+ program.command("agents").description(`Write the agent guide from the installed Genesis packages: .claude/skills/genesis/SKILL.md and a marked block in AGENTS.md`).option("--check", "Write nothing; exit 1 if either is missing or out of date (for CI)", false).option("-d, --dir <dir>", "The app's folder", process.cwd()).action(async (opts) => {
8735
+ const doctor = await Promise.resolve().then(() => (init_doctor(), doctor_exports));
8736
+ const root = path26.resolve(opts.dir);
8737
+ const packages = doctor.discoverPackages(root);
8738
+ const broken = packages.filter((p) => p.error);
8739
+ if (broken.length) {
8740
+ for (const p of broken) console.error(`\u2717 ${p.error}`);
8741
+ console.error("\u2717 The agent guide can't include these packages; fix their declarations (or upgrade @marktiderman/genesis-cli) first.");
8742
+ process.exitCode = 1;
8743
+ return;
8744
+ }
8745
+ if (opts.check) {
8746
+ const state = doctor.agentGuideState(root, packages);
8747
+ const bad = Object.entries(state).filter(([, v]) => v !== "ok");
8748
+ if (bad.length) {
8749
+ console.error(`\u2717 The agent guide is ${bad.map(([k, v]) => `${k === "skill" ? doctor.SKILL_PATH : "AGENTS.md"} ${v}`).join(", ")}. Run \`genesis agents\` and commit the result.`);
8750
+ process.exitCode = 1;
8751
+ return;
8752
+ }
8753
+ console.log("\u2714 The agent guide matches the installed Genesis packages.");
8754
+ return;
8755
+ }
8756
+ const changed = doctor.writeAgentGuide(root, packages);
8757
+ console.log(changed.length ? `\u2714 Wrote ${changed.join(", ")}` : "= The agent guide is up to date.");
8758
+ });
7451
8759
  var features = program.command("features").description('The feature registry: one typed features.ts, everything else generated from it. Settings: genesis.config.json "features" (or package.json "genesisFeatures")');
7452
8760
  function featureOptions(command) {
7453
8761
  return command.option("-d, --dir <dir>", "The repo root", process.cwd()).option("-r, --registry <file>", "The registry (default: src/features.ts, then features.ts)").option("--flags-file <file>", "A flags file exporting `flags` (default: the registry's own `flags` export)").option("--agents <file>", "The AGENTS.md that holds the pointer block (default AGENTS.md)").option("--json <file>", "The JSON copy, also the record of every id (default features.json)").option("--command <text>", "How people run this CLI here, named in generated files (default `genesis features`)");
@@ -7496,24 +8804,24 @@ featureOptions(
7496
8804
  var studio = program.command("studio").description("The Genesis Data Studio");
7497
8805
  studio.command("init").description("Turn the Data Studio on in this app: a server for every table, a page, and one migration to review").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--host <host>", "next, tanstack-start or supabase-function (default: detected)").option("--route <path>", "Where the page lives", "/admin/data").option("--login-role <name>", "The studio's database login", "genesis_studio_login").option("--force", "Overwrite files that already exist", false).action(async (opts) => {
7498
8806
  const { planStudioInit: planStudioInit2 } = await Promise.resolve().then(() => (init_init(), init_exports));
7499
- const root = path23.resolve(opts.dir);
7500
- const packageJson = JSON.parse(await fs.readFile(path23.join(root, "package.json"), "utf-8").catch(() => "{}"));
7501
- const existsSync28 = (await import('fs')).existsSync;
8807
+ const root = path26.resolve(opts.dir);
8808
+ const packageJson = JSON.parse(await fs.readFile(path26.join(root, "package.json"), "utf-8").catch(() => "{}"));
8809
+ const existsSync31 = (await import('fs')).existsSync;
7502
8810
  const readSync = (await import('fs')).readFileSync;
7503
- const readdirSync13 = (await import('fs')).readdirSync;
8811
+ const readdirSync14 = (await import('fs')).readdirSync;
7504
8812
  if (opts.host && !["next", "tanstack-start", "supabase-function"].includes(opts.host)) {
7505
8813
  throw new Error("--host must be next, tanstack-start or supabase-function.");
7506
8814
  }
7507
8815
  const plan = planStudioInit2(
7508
8816
  {
7509
8817
  packageJson,
7510
- exists: (p) => existsSync28(path23.join(root, p)),
7511
- read: (p) => existsSync28(path23.join(root, p)) ? readSync(path23.join(root, p), "utf-8") : null,
8818
+ exists: (p) => existsSync31(path26.join(root, p)),
8819
+ read: (p) => existsSync31(path26.join(root, p)) ? readSync(path26.join(root, p), "utf-8") : null,
7512
8820
  timestamp: (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14),
7513
8821
  listDeep: (p) => {
7514
8822
  const out = [];
7515
8823
  const walk2 = (rel) => {
7516
- for (const entry of readdirSync13(path23.join(root, rel), { withFileTypes: true })) {
8824
+ for (const entry of readdirSync14(path26.join(root, rel), { withFileTypes: true })) {
7517
8825
  const child = `${rel}/${entry.name}`;
7518
8826
  if (entry.isDirectory()) walk2(child);
7519
8827
  else out.push(child);
@@ -7527,7 +8835,7 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
7527
8835
  },
7528
8836
  list: (p) => {
7529
8837
  try {
7530
- return readdirSync13(path23.join(root, p));
8838
+ return readdirSync14(path26.join(root, p));
7531
8839
  } catch {
7532
8840
  return [];
7533
8841
  }
@@ -7536,8 +8844,8 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
7536
8844
  { host: opts.host, route: opts.route, loginRole: opts.loginRole }
7537
8845
  );
7538
8846
  for (const file of plan.files) {
7539
- const target = path23.join(root, file.path);
7540
- await fs.mkdir(path23.dirname(target), { recursive: true });
8847
+ const target = path26.join(root, file.path);
8848
+ await fs.mkdir(path26.dirname(target), { recursive: true });
7541
8849
  if (file.edit) {
7542
8850
  await fs.writeFile(target, file.content, "utf-8");
7543
8851
  console.log(`~ ${file.path} (${file.edit})`);
@@ -7548,14 +8856,14 @@ studio.command("init").description("Turn the Data Studio on in this app: a serve
7548
8856
  console.log(`+ ${file.path} (appended)`);
7549
8857
  continue;
7550
8858
  }
7551
- if (existsSync28(target) && !opts.force) {
8859
+ if (existsSync31(target) && !opts.force) {
7552
8860
  console.log(`= ${file.path} exists; left as it is (--force to replace)`);
7553
8861
  continue;
7554
8862
  }
7555
8863
  await fs.writeFile(target, file.content, "utf-8");
7556
8864
  console.log(`+ ${file.path}`);
7557
8865
  }
7558
- const pm = existsSync28(path23.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync28(path23.join(root, "yarn.lock")) ? "yarn add" : existsSync28(path23.join(root, "bun.lock")) || existsSync28(path23.join(root, "bun.lockb")) ? "bun add" : "npm install";
8866
+ const pm = existsSync31(path26.join(root, "pnpm-lock.yaml")) ? "pnpm add" : existsSync31(path26.join(root, "yarn.lock")) ? "yarn add" : existsSync31(path26.join(root, "bun.lock")) || existsSync31(path26.join(root, "bun.lockb")) ? "bun add" : "npm install";
7559
8867
  console.log("");
7560
8868
  console.log(`\u2714 The Data Studio is set up for ${{ next: "Next.js", "tanstack-start": "TanStack Start", "supabase-function": "a Supabase Edge Function" }[plan.host]}. To finish:`);
7561
8869
  console.log(` 1. ${pm} ${plan.install.join(" ")}`);
@@ -7573,7 +8881,7 @@ async function confirm(question) {
7573
8881
  }
7574
8882
  var logger = { info: (m) => console.log(m), warn: (m) => console.warn(`! ${m}`) };
7575
8883
  program.command("add").description("Add a block (a feature an app adds whole) from the Genesis package that declares it: install, migrations, functions, skills, routes, registry entry").argument("[block]", "The block's id, e.g. tenant-features").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--package <name>", "The package that declares it, when two do").option("--list", "List the blocks this app can add, and exit", false).option("--dry-run", "Print the plan; write and install nothing", false).option("-y, --yes", "Don't ask before writing", false).option("--no-install", "Don't install packages (print the command instead)").option("--no-features-build", "Don't run features build after").action(async (block, opts) => {
7576
- const root = path23.resolve(opts.dir);
8884
+ const root = path26.resolve(opts.dir);
7577
8885
  if (opts.list || !block) {
7578
8886
  const { allBlocks: allBlocks2 } = await Promise.resolve().then(() => (init_discover(), discover_exports));
7579
8887
  const { readLock: readLock2 } = await Promise.resolve().then(() => (init_lock(), lock_exports));
@@ -7602,7 +8910,7 @@ program.command("add").description("Add a block (a feature an app adds whole) fr
7602
8910
  program.command("migrate").description("Copy new package migrations of the app's blocks in as new timestamped files; report edited or changed ones (never rewritten)").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--block <id...>", "Also check these blocks (beyond genesis.lock.json's)").option("--dry-run", "Report only", false).option("--forward", "Write a forward migration stub for each edited or changed migration", false).action(async (opts) => {
7603
8911
  const { runMigrate: runMigrate2 } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
7604
8912
  const { formatMigrationRows: formatMigrationRows2 } = await Promise.resolve().then(() => (init_migrations(), migrations_exports));
7605
- const report = await runMigrate2({ root: path23.resolve(opts.dir), ...opts.block ? { blocks: opts.block } : {}, dryRun: opts.dryRun, forward: opts.forward });
8913
+ const report = await runMigrate2({ root: path26.resolve(opts.dir), ...opts.block ? { blocks: opts.block } : {}, dryRun: opts.dryRun, forward: opts.forward });
7606
8914
  for (const w of report.warnings) logger.warn(w);
7607
8915
  console.log(formatMigrationRows2(report.plan.rows));
7608
8916
  for (const c of report.plan.creates) if (c.kind !== "migration") console.log(`+ ${c.path} (${c.kind === "test" ? "pgTAP test" : "forward migration: fill it in"})`);
@@ -7617,7 +8925,7 @@ program.command("migrate").description("Copy new package migrations of the app's
7617
8925
  program.command("upgrade").description("Move every @marktiderman/genesis* dependency to one Genesis release, refresh the files Genesis owns, run codemods and the doctor").option("-d, --dir <dir>", "The app's folder", process.cwd()).option("--version <v>", "The @marktiderman/genesis release: an exact version or a dist-tag", "latest").option("--manifest <file>", "Read the release from this versions.json instead of npm").option("--dry-run", "Report the bump, and owned files compared with the packages installed now; change nothing", false).option("--no-install", "Don't reinstall after the bump").option("--no-doctor", "Don't run genesis doctor after").option("--keep-mine", "Never merge an owned file you changed; write the new text to .genesis-next", false).option("--pr", "Commit to a genesis-upgrade/<version> branch, push it and open a pull request", false).action(async (opts) => {
7618
8926
  const { runUpgrade: runUpgrade2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
7619
8927
  const report = await runUpgrade2({
7620
- root: path23.resolve(opts.dir),
8928
+ root: path26.resolve(opts.dir),
7621
8929
  version: opts.version,
7622
8930
  ...opts.manifest ? { manifest: opts.manifest } : {},
7623
8931
  dryRun: opts.dryRun,
@@ -7643,7 +8951,7 @@ program.command("codemod [id]").description("Run one of Genesis's codemods by ha
7643
8951
  }
7644
8952
  const mod = codemodById2(id);
7645
8953
  if (!mod) throw new Error(`No codemod "${id}". Run genesis codemod to list them.`);
7646
- const changed = await mod.run({ root: path23.resolve(opts.dir), dryRun: opts.dryRun, log: (m) => console.log(m) });
8954
+ const changed = await mod.run({ root: path26.resolve(opts.dir), dryRun: opts.dryRun, log: (m) => console.log(m) });
7647
8955
  console.log(changed.length ? `${opts.dryRun ? "Would change" : "\u2714 Changed"} ${changed.length} file${changed.length === 1 ? "" : "s"}:
7648
8956
  ${changed.map((f) => ` ${f}`).join("\n")}` : "Nothing to change.");
7649
8957
  });
@@ -7694,7 +9002,7 @@ function redactUrl(location) {
7694
9002
  const url = new URL(location);
7695
9003
  return `${url.origin}${url.pathname}`;
7696
9004
  } catch {
7697
- return path23.basename(location);
9005
+ return path26.basename(location);
7698
9006
  }
7699
9007
  }
7700
9008
  //# sourceMappingURL=cli.js.map